blob: db59b518b731174afd3bc702bda4ddff1f2b50b2 [file] [log] [blame]
Steve Naroffb29b4272008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattner77cd2a02007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner77cd2a02007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Daniel Dunbar9b414d32010-06-15 17:48:49 +000014#include "clang/Rewrite/ASTConsumers.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattner77cd2a02007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff8599e7a2008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner8a12c272007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffebf2b562007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner07506182007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattner26de4652007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer6cb7c1a2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner158ecb92007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremeneka95d3752008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000028#include "llvm/ADT/DenseSet.h"
Fariborz Jahanian72952fc2010-03-01 23:36:21 +000029
Chris Lattner77cd2a02007-10-11 00:43:27 +000030using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000031using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000032
Chris Lattner77cd2a02007-10-11 00:43:27 +000033namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000034 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000035 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000036 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 block, ... */
38 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
39 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
40 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000041 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000042 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 support routines */
45 BLOCK_BYREF_CURRENT_MAX = 256
46 };
47
48 enum {
49 BLOCK_NEEDS_FREE = (1 << 24),
50 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
51 BLOCK_HAS_CXX_OBJ = (1 << 26),
52 BLOCK_IS_GC = (1 << 27),
53 BLOCK_IS_GLOBAL = (1 << 28),
54 BLOCK_HAS_DESCRIPTOR = (1 << 29)
55 };
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
Chris Lattner5f9e2722011-07-23 10:55:15 +000070 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
71 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000072 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;
Chris Lattner5f9e2722011-07-23 10:55:15 +000076 SmallVector<Stmt *, 32> Stmts;
77 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;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000116 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.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockExpr *, 32> Blocks;
125 SmallVector<int, 32> InnerDeclRefsCount;
126 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000127
Chris Lattner5f9e2722011-07-23 10:55:15 +0000128 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000129
Steve Naroff54055232008-10-27 17:20:55 +0000130 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000131 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000133 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000134 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000135 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000136 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000137 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
138
Steve Naroff54055232008-10-27 17:20:55 +0000139 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
140
Steve Naroffc77a6362008-12-04 16:24:46 +0000141 // This maps a property to it's assignment statement.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000142 llvm::DenseMap<Expr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000143 // This maps a property to it's synthesied message expression.
144 // This allows us to rewrite chained getters (e.g. o.a.b.c).
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000145 llvm::DenseMap<Expr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000146
Steve Naroff4c3580e2008-12-04 23:50:32 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000151
Steve Naroff54055232008-10-27 17:20:55 +0000152 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000153 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000154 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000155
Steve Naroffb619d952008-12-09 12:56:34 +0000156 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000157
Nick Lewycky7e749242010-10-31 21:07:24 +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) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000164 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
165 if (isa<ObjCClassDecl>((*I))) {
166 RewriteForwardClassDecl(D);
167 break;
168 }
Chris Lattner682bf922009-03-29 16:50:03 +0000169 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000170 }
Chris Lattner682bf922009-03-29 16:50:03 +0000171 }
172 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000173 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000174 RewriteObjC(std::string inFile, raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000175 Diagnostic &D, const LangOptions &LOpts,
176 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000177
178 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000179
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000180 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000181
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000182 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000183 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000184
Steve Naroff4c3580e2008-12-04 23:50:32 +0000185 if (ReplacingStmt)
186 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000187
Steve Naroffb619d952008-12-09 12:56:34 +0000188 if (DisableReplaceStmt)
189 return; // Used when rewriting the assignment of a property setter.
190
Steve Naroff4c3580e2008-12-04 23:50:32 +0000191 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000192 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000193 ReplacedNodes[Old] = New;
194 return;
195 }
196 if (SilenceRewriteMacroWarning)
197 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000198 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
199 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000200 }
Steve Naroffb619d952008-12-09 12:56:34 +0000201
202 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
Nick Lewycky7e749242010-10-31 21:07:24 +0000203 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000204 int Size = Rewrite.getRangeSize(SrcRange);
205 if (Size == -1) {
206 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
207 << Old->getSourceRange();
208 return;
209 }
210 // Get the new text.
211 std::string SStr;
212 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000213 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000214 const std::string &Str = S.str();
215
216 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000217 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000218 ReplacedNodes[Old] = New;
219 return;
220 }
221 if (SilenceRewriteMacroWarning)
222 return;
223 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
224 << Old->getSourceRange();
225 }
226
Chris Lattner5f9e2722011-07-23 10:55:15 +0000227 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000228 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000229 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000230 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000231 SilenceRewriteMacroWarning)
232 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000233
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000234 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
235 }
Mike Stump1eb44332009-09-09 15:08:12 +0000236
Chris Lattneraadaf782008-01-31 19:51:04 +0000237 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000238 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000240 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000241 SilenceRewriteMacroWarning)
242 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
245 }
Mike Stump1eb44332009-09-09 15:08:12 +0000246
Chris Lattnerf04da132007-10-24 17:06:59 +0000247 // Syntactic Rewriting.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000248 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000249 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000250 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
251 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
252 const std::string &typedefString);
253
Steve Naroffa0876e82008-12-02 17:36:43 +0000254 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
255 ObjCImplementationDecl *IMD,
256 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000257 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000258 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000259 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
260 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000261 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
262 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000263 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000264 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
266 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
267 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
268 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000269 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000270 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000271 void RewriteBlockPointerType(std::string& Str, QualType Type);
272 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000273 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000274 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000275 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000276 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000277 bool needToScanForQualifiers(QualType T);
Steve Naroff874e2322007-11-15 10:28:18 +0000278 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000279 QualType getConstantStringStructType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +0000280 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
Steve Naroffbaf58c32008-05-31 14:15:04 +0000281 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000282
Chris Lattnerf04da132007-10-24 17:06:59 +0000283 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000284 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000285 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000286
Steve Naroff8599e7a2008-12-08 16:43:47 +0000287 Stmt *CurrentBody;
288 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000289
Chris Lattnere64b7772007-10-24 16:57:36 +0000290 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000291 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
292 bool &replaced);
293 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +0000294 Stmt *RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr);
295 Stmt *RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000296 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000297 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000298 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000299 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000300 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000301 void WarnAboutReturnGotoStmts(Stmt *S);
302 void HasReturnStmts(Stmt *S, bool &hasReturns);
303 void RewriteTryReturnStmts(Stmt *S);
304 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000305 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000306 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000307 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000308 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
309 SourceLocation OrigEnd);
Fariborz Jahanian42f1e652011-02-24 21:29:21 +0000310 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Mike Stump1eb44332009-09-09 15:08:12 +0000311 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +0000312 Expr **args, unsigned nargs,
313 SourceLocation StartLoc=SourceLocation(),
314 SourceLocation EndLoc=SourceLocation());
315 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
316 SourceLocation StartLoc=SourceLocation(),
317 SourceLocation EndLoc=SourceLocation());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000318 Stmt *RewriteBreakStmt(BreakStmt *S);
319 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000320 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000321
Steve Naroff09b266e2007-10-30 23:14:51 +0000322 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000323 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000324 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000325 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000326 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000327 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000328 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000329 void SynthGetSuperClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000330 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000331 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000332
Chris Lattnerf04da132007-10-24 17:06:59 +0000333 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000334 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000335 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000336
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000337 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000338 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000339
Douglas Gregor653f1b12009-04-23 01:02:12 +0000340 template<typename MethodIterator>
341 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
342 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000343 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000344 StringRef prefix,
345 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +0000346 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Steve Naroff621edce2009-04-29 16:37:50 +0000348 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000349 StringRef prefix,
350 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000351 std::string &Result);
352 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000353 StringRef prefix,
354 StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +0000355 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000356 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000357 std::string &Result);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000358 void SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000359 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000360 void RewriteImplementations();
361 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000362
Steve Naroff54055232008-10-27 17:20:55 +0000363 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000364 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000365 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000366
Steve Naroff54055232008-10-27 17:20:55 +0000367 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
368 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000369
370 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000371 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000372 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000373 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000374 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000375 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000376 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000377
378 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000379 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000380 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000381 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000382 std::string SynthesizeBlockImpl(BlockExpr *CE,
383 std::string Tag, std::string Desc);
384 std::string SynthesizeBlockDescriptor(std::string DescTag,
385 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000386 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000387 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000388 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000389 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390 StringRef FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000391 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000392
Steve Naroff54055232008-10-27 17:20:55 +0000393 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000394 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000395 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000396 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000397 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000398
Steve Naroff54055232008-10-27 17:20:55 +0000399 // We avoid calling Type::isBlockPointerType(), since it operates on the
400 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000401 bool isTopLevelBlockPointerType(QualType T) {
402 return isa<BlockPointerType>(T);
403 }
Mike Stump1eb44332009-09-09 15:08:12 +0000404
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000405 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
406 /// to a function pointer type and upon success, returns true; false
407 /// otherwise.
408 bool convertBlockPointerToFunctionPointer(QualType &T) {
409 if (isTopLevelBlockPointerType(T)) {
410 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
411 T = Context->getPointerType(BPT->getPointeeType());
412 return true;
413 }
414 return false;
415 }
416
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000417 void convertToUnqualifiedObjCType(QualType &T) {
418 if (T->isObjCQualifiedIdType())
419 T = Context->getObjCIdType();
420 else if (T->isObjCQualifiedClassType())
421 T = Context->getObjCClassType();
422 else if (T->isObjCObjectPointerType() &&
423 T->getPointeeType()->isObjCQualifiedInterfaceType())
424 T = Context->getObjCIdType();
425 }
426
Steve Naroff54055232008-10-27 17:20:55 +0000427 // FIXME: This predicate seems like it would be useful to add to ASTContext.
428 bool isObjCType(QualType T) {
429 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
430 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000431
Steve Naroff54055232008-10-27 17:20:55 +0000432 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000433
Steve Naroff54055232008-10-27 17:20:55 +0000434 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
435 OCT == Context->getCanonicalType(Context->getObjCClassType()))
436 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Ted Kremenek6217b802009-07-29 21:53:49 +0000438 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000439 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000440 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000441 return true;
442 }
443 return false;
444 }
445 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000446 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000447 void GetExtentOfArgList(const char *Name, const char *&LParen,
448 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000449 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000450
Chris Lattner5f9e2722011-07-23 10:55:15 +0000451 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000452 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000453 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000454
Steve Naroff621edce2009-04-29 16:37:50 +0000455 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000456 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000457 if (From[i] == '"')
458 To += "\\\"";
459 else
460 To += From[i];
461 }
462 }
John McCalle23cf432010-12-14 08:05:40 +0000463
464 QualType getSimpleFunctionType(QualType result,
465 const QualType *args,
466 unsigned numArgs,
467 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000468 if (result == Context->getObjCInstanceType())
469 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000470 FunctionProtoType::ExtProtoInfo fpi;
471 fpi.Variadic = variadic;
472 return Context->getFunctionType(result, args, numArgs, fpi);
473 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000474 };
John McCall9d125032010-01-15 18:39:57 +0000475
476 // Helper function: create a CStyleCastExpr with trivial type source info.
477 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000478 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000479 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000480 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000481 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000482 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000483}
484
Mike Stump1eb44332009-09-09 15:08:12 +0000485void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
486 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000487 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000488 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000489 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000490 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000491 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000492 // All the args are checked/rewritten. Don't call twice!
493 RewriteBlockPointerDecl(D);
494 break;
495 }
496 }
497}
498
499void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000500 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000501 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000502 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000503}
504
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000505static bool IsHeaderFile(const std::string &Filename) {
506 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000507
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000508 if (DotPos == std::string::npos) {
509 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000510 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000511 }
Mike Stump1eb44332009-09-09 15:08:12 +0000512
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000513 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
514 // C header: .h
515 // C++ header: .hh or .H;
516 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000517}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000518
Chris Lattner5f9e2722011-07-23 10:55:15 +0000519RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000520 Diagnostic &D, const LangOptions &LOpts,
521 bool silenceMacroWarn)
522 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
523 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000524 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000525 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000526 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000527 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000528 "rewriter doesn't support user-specified control flow semantics "
529 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000530}
531
Eli Friedmanbce831b2009-05-18 22:29:17 +0000532ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000533 raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000534 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000535 const LangOptions &LOpts,
536 bool SilenceRewriteMacroWarning) {
537 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000538}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000539
Steve Naroffb29b4272008-04-14 22:03:09 +0000540void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000541 Context = &context;
542 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000543 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000544 MsgSendFunctionDecl = 0;
545 MsgSendSuperFunctionDecl = 0;
546 MsgSendStretFunctionDecl = 0;
547 MsgSendSuperStretFunctionDecl = 0;
548 MsgSendFpretFunctionDecl = 0;
549 GetClassFunctionDecl = 0;
550 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000551 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000552 SelGetUidFunctionDecl = 0;
553 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000554 ConstantStringClassReference = 0;
555 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000556 CurMethodDef = 0;
557 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000558 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000559 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000560 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000561 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000562 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000563 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000564 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000565 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000566 PropParentMap = 0;
567 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000568 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000569 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000570
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000571 // Get the ID and start/end of the main file.
572 MainFileID = SM->getMainFileID();
573 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
574 MainFileStart = MainBuf->getBufferStart();
575 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner2c78b872009-04-14 23:22:57 +0000577 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000578
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000579 // declaring objc_selector outside the parameter list removes a silly
580 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000582 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000584 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000585 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000586 if (LangOpts.Microsoft) {
587 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000588 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
589 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000591 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000593 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
594 Preamble += "typedef struct objc_object Protocol;\n";
595 Preamble += "#define _REWRITER_typedef_Protocol\n";
596 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000597 if (LangOpts.Microsoft) {
598 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
599 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
600 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000601 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000603 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000604 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000605 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000608 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000609 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000610 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000611 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000612 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000613 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000614 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
615 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000616 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000617 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000618 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
619 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
620 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
621 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
622 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000623 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000624 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
626 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
627 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000628 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
629 Preamble += "struct __objcFastEnumerationState {\n\t";
630 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000631 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000632 Preamble += "unsigned long *mutationsPtr;\n\t";
633 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000634 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000635 Preamble += "#define __FASTENUMERATIONSTATE\n";
636 Preamble += "#endif\n";
637 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
638 Preamble += "struct __NSConstantStringImpl {\n";
639 Preamble += " int *isa;\n";
640 Preamble += " int flags;\n";
641 Preamble += " char *str;\n";
642 Preamble += " long length;\n";
643 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000644 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
645 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
646 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000647 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000648 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000649 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
650 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000651 // Blocks preamble.
652 Preamble += "#ifndef BLOCK_IMPL\n";
653 Preamble += "#define BLOCK_IMPL\n";
654 Preamble += "struct __block_impl {\n";
655 Preamble += " void *isa;\n";
656 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000657 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000658 Preamble += " void *FuncPtr;\n";
659 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000660 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000661 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000662 Preamble += "extern \"C\" __declspec(dllexport) "
663 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000664 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
665 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
666 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
667 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000668 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
669 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000670 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
671 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
672 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000673 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000674 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000675 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
676 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000677 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000678 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000679 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000680 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000681 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000682 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000683 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000684 Preamble += "#define __weak\n";
685 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000686 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
687 // as this avoids warning in any 64bit/32bit compilation model.
688 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000689}
690
691
Chris Lattnerf04da132007-10-24 17:06:59 +0000692//===----------------------------------------------------------------------===//
693// Top Level Driver Code
694//===----------------------------------------------------------------------===//
695
Chris Lattner682bf922009-03-29 16:50:03 +0000696void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000697 if (Diags.hasErrorOccurred())
698 return;
699
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000700 // Two cases: either the decl could be in the main file, or it could be in a
701 // #included file. If the former, rewrite it now. If the later, check to see
702 // if we rewrote the #include/#import.
703 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000704 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000705
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000706 // If this is for a builtin, ignore it.
707 if (Loc.isInvalid()) return;
708
Steve Naroffebf2b562007-10-23 23:50:29 +0000709 // Look for built-in declarations that we need to refer during the rewrite.
710 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000711 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000712 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000713 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000714 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000715 ConstantStringClassReference = FVD;
716 return;
717 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000718 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000719 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000721 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000722 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000723 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000724 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000725 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000726 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000727 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
728 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000729 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
730 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000731 DI != DIEnd; ) {
732 if (isa<ObjCClassDecl>((*DI))) {
733 SmallVector<Decl *, 8> DG;
734 Decl *D = (*DI);
735 SourceLocation Loc = D->getLocation();
736 while (DI != DIEnd &&
737 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
738 DG.push_back(D);
739 ++DI;
740 D = (*DI);
741 }
742 RewriteForwardClassDecl(DG);
743 continue;
744 }
Chris Lattner682bf922009-03-29 16:50:03 +0000745 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000746 ++DI;
747 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000748 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000749 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000750 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000751 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000752}
753
Chris Lattnerf04da132007-10-24 17:06:59 +0000754//===----------------------------------------------------------------------===//
755// Syntactic (non-AST) Rewriting Code
756//===----------------------------------------------------------------------===//
757
Steve Naroffb29b4272008-04-14 22:03:09 +0000758void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000759 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000760 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000761 const char *MainBufStart = MainBuf.begin();
762 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000763 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000764
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000765 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000766 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
767 if (*BufPtr == '#') {
768 if (++BufPtr == MainBufEnd)
769 return;
770 while (*BufPtr == ' ' || *BufPtr == '\t')
771 if (++BufPtr == MainBufEnd)
772 return;
773 if (!strncmp(BufPtr, "import", ImportLen)) {
774 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000775 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000776 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000777 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000778 BufPtr += ImportLen;
779 }
780 }
781 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000782}
783
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000784static std::string getIvarAccessString(ObjCIvarDecl *OID) {
785 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 std::string S;
787 S = "((struct ";
788 S += ClassDecl->getIdentifier()->getName();
789 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000790 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000791 return S;
792}
793
Steve Naroffa0876e82008-12-02 17:36:43 +0000794void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
795 ObjCImplementationDecl *IMD,
796 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000797 static bool objcGetPropertyDefined = false;
798 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000799 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000800 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000801 const char *startBuf = SM->getCharacterData(startLoc);
802 assert((*startBuf == '@') && "bogus @synthesize location");
803 const char *semiBuf = strchr(startBuf, ';');
804 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000805 SourceLocation onePastSemiLoc =
806 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000807
808 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
809 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000810
Steve Naroffeb0646c2008-12-02 15:48:25 +0000811 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000812 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000813 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000814
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000815 if (!OID)
816 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000817 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000818 if (!PD->getGetterMethodDecl()->isDefined()) {
819 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
820 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
821 ObjCPropertyDecl::OBJC_PR_copy));
822 std::string Getr;
823 if (GenGetProperty && !objcGetPropertyDefined) {
824 objcGetPropertyDefined = true;
825 // FIXME. Is this attribute correct in all cases?
826 Getr = "\nextern \"C\" __declspec(dllimport) "
827 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000828 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000829 RewriteObjCMethodDecl(OID->getContainingInterface(),
830 PD->getGetterMethodDecl(), Getr);
831 Getr += "{ ";
832 // Synthesize an explicit cast to gain access to the ivar.
833 // See objc-act.c:objc_synthesize_new_getter() for details.
834 if (GenGetProperty) {
835 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
836 Getr += "typedef ";
837 const FunctionType *FPRetType = 0;
838 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
839 FPRetType);
840 Getr += " _TYPE";
841 if (FPRetType) {
842 Getr += ")"; // close the precedence "scope" for "*".
843
844 // Now, emit the argument types (if any).
845 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
846 Getr += "(";
847 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
848 if (i) Getr += ", ";
849 std::string ParamStr = FT->getArgType(i).getAsString(
850 Context->PrintingPolicy);
851 Getr += ParamStr;
852 }
853 if (FT->isVariadic()) {
854 if (FT->getNumArgs()) Getr += ", ";
855 Getr += "...";
856 }
857 Getr += ")";
858 } else
859 Getr += "()";
860 }
861 Getr += ";\n";
862 Getr += "return (_TYPE)";
863 Getr += "objc_getProperty(self, _cmd, ";
864 SynthesizeIvarOffsetComputation(OID, Getr);
865 Getr += ", 1)";
866 }
867 else
868 Getr += "return " + getIvarAccessString(OID);
869 Getr += "; }";
870 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000871 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000872
873 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000874 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000875
Steve Naroffeb0646c2008-12-02 15:48:25 +0000876 // Generate the 'setter' function.
877 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000878 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
879 ObjCPropertyDecl::OBJC_PR_copy);
880 if (GenSetProperty && !objcSetPropertyDefined) {
881 objcSetPropertyDefined = true;
882 // FIXME. Is this attribute correct in all cases?
883 Setr = "\nextern \"C\" __declspec(dllimport) "
884 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
885 }
886
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000887 RewriteObjCMethodDecl(OID->getContainingInterface(),
888 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000889 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000890 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000891 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000892 if (GenSetProperty) {
893 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000894 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000895 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000896 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000897 Setr += ", ";
898 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
899 Setr += "0, ";
900 else
901 Setr += "1, ";
902 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
903 Setr += "1)";
904 else
905 Setr += "0)";
906 }
907 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000908 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000909 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000910 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000911 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000912 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000913}
Chris Lattner8a12c272007-10-11 18:38:32 +0000914
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000915static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
916 std::string &typedefString) {
917 typedefString += "#ifndef _REWRITER_typedef_";
918 typedefString += ForwardDecl->getNameAsString();
919 typedefString += "\n";
920 typedefString += "#define _REWRITER_typedef_";
921 typedefString += ForwardDecl->getNameAsString();
922 typedefString += "\n";
923 typedefString += "typedef struct objc_object ";
924 typedefString += ForwardDecl->getNameAsString();
925 typedefString += ";\n#endif\n";
926}
927
928void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
929 const std::string &typedefString) {
930 SourceLocation startLoc = ClassDecl->getLocation();
931 const char *startBuf = SM->getCharacterData(startLoc);
932 const char *semiPtr = strchr(startBuf, ';');
933 // Replace the @class with typedefs corresponding to the classes.
934 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
935}
936
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000937void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000938 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000939 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
940 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
941 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
942 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000943 // Translate to typedef's that forward reference structs with the same name
944 // as the class. As a convenience, we include the original declaration
945 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000946 typedefString += "// @class ";
947 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000948 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000949 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000950 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000951 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000952 DeclGroupRef::iterator I = D.begin();
953 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
954}
Mike Stump1eb44332009-09-09 15:08:12 +0000955
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000956void RewriteObjC::RewriteForwardClassDecl(
957 const llvm::SmallVector<Decl*, 8> &D) {
958 std::string typedefString;
959 for (unsigned i = 0; i < D.size(); i++) {
960 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
961 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
962 if (i == 0) {
963 typedefString += "// @class ";
964 typedefString += ForwardDecl->getNameAsString();
965 typedefString += ";\n";
966 }
967 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
968 }
969 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000970}
971
Steve Naroffb29b4272008-04-14 22:03:09 +0000972void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000973 // When method is a synthesized one, such as a getter/setter there is
974 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000975 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000976 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000977 SourceLocation LocStart = Method->getLocStart();
978 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000979
Chandler Carruth64211622011-07-25 21:09:52 +0000980 if (SM->getExpansionLineNumber(LocEnd) >
981 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000982 InsertText(LocStart, "#if 0\n");
983 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000985 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000986 }
987}
988
Mike Stump1eb44332009-09-09 15:08:12 +0000989void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000990 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000991
Benjamin Kramerd999b372010-02-14 14:14:16 +0000992 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000993 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000994}
995
Steve Naroffb29b4272008-04-14 22:03:09 +0000996void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000997 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Steve Naroff423cb562007-10-30 13:30:57 +0000999 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001000 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001002 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1003 E = CatDecl->prop_end(); I != E; ++I)
1004 RewriteProperty(*I);
1005
Mike Stump1eb44332009-09-09 15:08:12 +00001006 for (ObjCCategoryDecl::instmeth_iterator
1007 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001008 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001009 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001010 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001011 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001012 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001013 RewriteMethodDeclaration(*I);
1014
Steve Naroff423cb562007-10-30 13:30:57 +00001015 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001016 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1017 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001018}
1019
Steve Naroffb29b4272008-04-14 22:03:09 +00001020void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001021 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001022
Steve Naroff752d6ef2007-10-30 16:42:30 +00001023 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001024 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001025
1026 for (ObjCProtocolDecl::instmeth_iterator
1027 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001028 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001029 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001030 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001031 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001032 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001033 RewriteMethodDeclaration(*I);
1034
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001035 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1036 E = PDecl->prop_end(); I != E; ++I)
1037 RewriteProperty(*I);
1038
Steve Naroff752d6ef2007-10-30 16:42:30 +00001039 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001040 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001041 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001042
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001043 // Must comment out @optional/@required
1044 const char *startBuf = SM->getCharacterData(LocStart);
1045 const char *endBuf = SM->getCharacterData(LocEnd);
1046 for (const char *p = startBuf; p < endBuf; p++) {
1047 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001048 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001049 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001050
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001051 }
1052 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001053 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001054 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001055
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001056 }
1057 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001058}
1059
Steve Naroffb29b4272008-04-14 22:03:09 +00001060void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001061 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001062 if (LocStart.isInvalid())
1063 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001064 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001065 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001066}
1067
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001068void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1069 const FunctionType *&FPRetType) {
1070 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001071 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001072 else if (T->isFunctionPointerType() ||
1073 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001074 // needs special handling, since pointer-to-functions have special
1075 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001076 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001077 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001078 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001079 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001080 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001081 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001082 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001083 ResultStr += FPRetType->getResultType().getAsString(
1084 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001085 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001086 }
1087 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001088 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001089}
1090
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001091void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1092 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001093 std::string &ResultStr) {
1094 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1095 const FunctionType *FPRetType = 0;
1096 ResultStr += "\nstatic ";
1097 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001098 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001099
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001100 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001101 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001102
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001103 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001104 NameStr += "_I_";
1105 else
1106 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001107
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001108 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001109 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001110
1111 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001112 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001113 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001114 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001115 }
Mike Stump1eb44332009-09-09 15:08:12 +00001116 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001117 {
1118 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001119 int len = selString.size();
1120 for (int i = 0; i < len; i++)
1121 if (selString[i] == ':')
1122 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001123 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001124 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001125 // Remember this name for metadata emission
1126 MethodInternalNames[OMD] = NameStr;
1127 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001128
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001129 // Rewrite arguments
1130 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001131
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001132 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001133 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001134 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001135 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001136 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001137 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001138 ResultStr += "struct ";
1139 }
1140 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001141 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001142 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001143 }
1144 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001145 ResultStr += Context->getObjCClassType().getAsString(
1146 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001148 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001149 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001151
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001152 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001153 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1154 E = OMD->param_end(); PI != E; ++PI) {
1155 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001156 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001157 if (PDecl->getType()->isObjCQualifiedIdType()) {
1158 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001159 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001160 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001161 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001162 QualType QT = PDecl->getType();
1163 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1164 if (convertBlockPointerToFunctionPointer(QT))
1165 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1166 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001167 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001168 ResultStr += Name;
1169 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001170 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001171 if (OMD->isVariadic())
1172 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001173 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001174
Steve Naroff76e429d2008-07-16 14:40:40 +00001175 if (FPRetType) {
1176 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Steve Naroff76e429d2008-07-16 14:40:40 +00001178 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001179 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001180 ResultStr += "(";
1181 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1182 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001183 std::string ParamStr = FT->getArgType(i).getAsString(
1184 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001185 ResultStr += ParamStr;
1186 }
1187 if (FT->isVariadic()) {
1188 if (FT->getNumArgs()) ResultStr += ", ";
1189 ResultStr += "...";
1190 }
1191 ResultStr += ")";
1192 } else {
1193 ResultStr += "()";
1194 }
1195 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001196}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001197void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001198 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1199 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001201 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001202
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001203 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001204 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1205 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001206 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001207 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001208 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001209 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001210 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001211 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001212
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001213 const char *startBuf = SM->getCharacterData(LocStart);
1214 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001215 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001216 }
Mike Stump1eb44332009-09-09 15:08:12 +00001217
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001218 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001219 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1220 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001221 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001222 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001223 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001224 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001225 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001226 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001227
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001228 const char *startBuf = SM->getCharacterData(LocStart);
1229 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001230 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001231 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001232 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001233 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001234 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001235 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001236 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001237 }
1238
Benjamin Kramerd999b372010-02-14 14:14:16 +00001239 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001240}
1241
Steve Naroffb29b4272008-04-14 22:03:09 +00001242void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001243 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001244 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001245 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001246 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001247 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001248 ResultStr += "\n";
1249 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001250 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001251 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001252 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001253 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001254 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001255 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001256 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001257 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001258 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001259
1260 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001261 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001262 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001263 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001264 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001265 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001266 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001267 for (ObjCInterfaceDecl::classmeth_iterator
1268 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001269 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001270 RewriteMethodDeclaration(*I);
1271
Steve Naroff2feac5e2007-10-30 03:43:13 +00001272 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001273 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1274 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001275}
1276
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001277Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001278 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001279 ObjCMethodDecl *OMD = 0;
1280 QualType Ty;
1281 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001282 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001283 bool Super = false;
1284 QualType SuperTy;
1285 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001286 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001287 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001288 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001289 if (ObjCPropertyRefExpr *PropRefExpr =
1290 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001291 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001292 if (PropRefExpr->isExplicitProperty()) {
1293 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1294 OMD = PDecl->getSetterMethodDecl();
1295 Ty = PDecl->getType();
1296 Sel = PDecl->getSetterName();
1297 } else {
1298 OMD = PropRefExpr->getImplicitPropertySetter();
1299 Sel = OMD->getSelector();
1300 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001301 }
John McCall12f78a62010-12-02 01:19:52 +00001302 Super = PropRefExpr->isSuperReceiver();
1303 if (!Super) {
1304 Receiver = PropRefExpr->getBase();
1305 } else {
1306 SuperTy = PropRefExpr->getSuperReceiverType();
1307 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001308 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001309 }
1310
1311 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001312 SmallVector<Expr *, 1> ExprVec;
Steve Naroffc77a6362008-12-04 16:24:46 +00001313 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001314
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001315 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001316 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001317 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001318 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001319 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001320 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001321 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001322 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001323 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001324 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001325 &ExprVec[0], 1,
1326 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001327 else {
1328 // FIXME. Refactor this into common code with that in
1329 // RewritePropertyOrImplicitGetter
1330 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1331 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1332 if (PropGetters[Exp])
1333 // This allows us to handle chain/nested property/implicit getters.
1334 Receiver = PropGetters[Exp];
1335
Douglas Gregor04badcf2010-04-21 00:45:42 +00001336 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001337 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001338 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001339 /*FIXME: */SourceLocation(),
1340 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001341 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001342 &ExprVec[0], 1,
1343 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001344 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001345 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001346
Steve Naroffc77a6362008-12-04 16:24:46 +00001347 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001348 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001349 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001350 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1351 // to things that stay around.
1352 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001353 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001354}
1355
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001356Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1357 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001358 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001359 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001360 ObjCMethodDecl *OMD = 0;
1361 QualType Ty;
1362 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001363 bool Super = false;
1364 QualType SuperTy;
1365 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001366 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001367 if (ObjCPropertyRefExpr *PropRefExpr =
1368 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001369 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001370 if (PropRefExpr->isExplicitProperty()) {
1371 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1372 OMD = PDecl->getGetterMethodDecl();
1373 Ty = PDecl->getType();
1374 Sel = PDecl->getGetterName();
1375 } else {
1376 OMD = PropRefExpr->getImplicitPropertyGetter();
1377 Sel = OMD->getSelector();
1378 Ty = PropRefExpr->getType();
1379 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001380 Super = PropRefExpr->isSuperReceiver();
1381 if (!Super)
1382 Receiver = PropRefExpr->getBase();
1383 else {
John McCall12f78a62010-12-02 01:19:52 +00001384 SuperTy = PropRefExpr->getSuperReceiverType();
1385 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001386 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001387 }
1388
1389 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1390
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001391 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001392 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001393 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001394 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001395 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001396 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001397 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001398 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001399 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001400 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001401 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001402 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001403 else {
1404 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1405 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1406 if (PropGetters[Exp])
1407 // This allows us to handle chain/nested property/implicit getters.
1408 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001409 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001410 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001411 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001412 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001413 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001414 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001415 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001416 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001417 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001418
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001419 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1420 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001421
1422 if (!PropParentMap)
1423 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001424 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001425 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001426 ImplicitCastExpr*ICE=0;
1427 if (Parent)
1428 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1429 assert((ICE->getCastKind() == CK_GetObjCProperty)
1430 && "RewritePropertyOrImplicitGetter");
1431 Parent = PropParentMap->getParent(Parent);
1432 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1433 }
1434 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001435 // We stash away the ReplacingStmt since actually doing the
1436 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001437 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001438 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1439 // to things that stay around.
1440 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001441 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001442 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001443 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001444 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001445 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1446 // to things that stay around.
1447 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001448 return ReplacingStmt;
1449 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001450}
1451
Mike Stump1eb44332009-09-09 15:08:12 +00001452Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001453 SourceLocation OrigStart,
1454 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001455 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001456 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001457 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001458 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001459 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001460 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001461 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001462 // lookup which class implements the instance variable.
1463 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001464 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001465 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001466 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001467
Steve Narofff0757612008-05-08 17:52:16 +00001468 // Synthesize an explicit cast to gain access to the ivar.
1469 std::string RecName = clsDeclared->getIdentifier()->getName();
1470 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001471 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001472 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001473 SourceLocation(), SourceLocation(),
1474 II);
Steve Narofff0757612008-05-08 17:52:16 +00001475 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1476 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001477 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001478 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001479 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001480 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001481 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001482 IV->getBase()->getLocEnd(),
1483 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001484 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001485 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001486 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001487 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001488 IV->getLocation(),
1489 D->getType(),
1490 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001491 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001492 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001493 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001494 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001495 // Cannot delete IV->getBase(), since PE points to it.
1496 // Replace the old base with the cast. This is important when doing
1497 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001498 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001499 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001500 }
Steve Naroff84472a82008-04-18 21:55:08 +00001501 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001502 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001503
Steve Naroff9f525972008-05-06 23:20:07 +00001504 // Explicit ivar refs need to have a cast inserted.
1505 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001506 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001507 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001508 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001509 // lookup which class implements the instance variable.
1510 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001511 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001512 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001513 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001514
Steve Naroff9f525972008-05-06 23:20:07 +00001515 // Synthesize an explicit cast to gain access to the ivar.
1516 std::string RecName = clsDeclared->getIdentifier()->getName();
1517 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001518 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001519 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001520 SourceLocation(), SourceLocation(),
1521 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001522 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1523 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001524 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001525 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001526 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001527 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001528 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001529 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001530 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001531 // Cannot delete IV->getBase(), since PE points to it.
1532 // Replace the old base with the cast. This is important when doing
1533 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001534 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001535 return IV;
1536 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001537 }
Steve Naroff84472a82008-04-18 21:55:08 +00001538 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001539}
1540
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001541Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001542 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001543 if (*CI) {
1544 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1545 if (newStmt)
1546 *CI = newStmt;
1547 }
1548 }
1549 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1550 SourceRange OrigStmtRange = S->getSourceRange();
1551 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1552 replaced);
1553 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001554 }
1555 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1556 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1557 return newStmt;
1558 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001559 return S;
1560}
1561
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001562/// SynthCountByEnumWithState - To print:
1563/// ((unsigned int (*)
1564/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001565/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001566/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001567/// "countByEnumeratingWithState:objects:count:"),
1568/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569/// (id *)items, (unsigned int)16)
1570///
Steve Naroffb29b4272008-04-14 22:03:09 +00001571void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001572 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1573 "id *, unsigned int))(void *)objc_msgSend)";
1574 buf += "\n\t\t";
1575 buf += "((id)l_collection,\n\t\t";
1576 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1577 buf += "\n\t\t";
1578 buf += "&enumState, "
1579 "(id *)items, (unsigned int)16)";
1580}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001581
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001582/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1583/// statement to exit to its outer synthesized loop.
1584///
Steve Naroffb29b4272008-04-14 22:03:09 +00001585Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001586 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1587 return S;
1588 // replace break with goto __break_label
1589 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001590
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001591 SourceLocation startLoc = S->getLocStart();
1592 buf = "goto __break_label_";
1593 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001594 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001595
1596 return 0;
1597}
1598
1599/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1600/// statement to continue with its inner synthesized loop.
1601///
Steve Naroffb29b4272008-04-14 22:03:09 +00001602Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001603 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1604 return S;
1605 // replace continue with goto __continue_label
1606 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001607
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 SourceLocation startLoc = S->getLocStart();
1609 buf = "goto __continue_label_";
1610 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001611 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001613 return 0;
1614}
1615
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001616/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001617/// It rewrites:
1618/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001619
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001620/// Into:
1621/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001622/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001623/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001624/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001626/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001627/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001628/// if (limit) {
1629/// unsigned long startMutations = *enumState.mutationsPtr;
1630/// do {
1631/// unsigned long counter = 0;
1632/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001633/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001634/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001635/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001636/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001637/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001638/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001639/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001640/// objects:items count:16]);
1641/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001642/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001643/// }
1644/// else
1645/// elem = nil;
1646/// }
1647///
Steve Naroffb29b4272008-04-14 22:03:09 +00001648Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001649 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001650 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001651 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001652 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001653 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001654 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001655
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001656 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001657 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001658 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001659 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001660 std::string buf;
1661 buf = "\n{\n\t";
1662 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1663 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001664 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001665 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001666 if (ElementType->isObjCQualifiedIdType() ||
1667 ElementType->isObjCQualifiedInterfaceType())
1668 // Simply use 'id' for all qualified types.
1669 elementTypeAsString = "id";
1670 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001671 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001672 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001673 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001674 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001675 buf += elementName;
1676 buf += ";\n\t";
1677 }
Chris Lattner06767512008-04-08 05:52:18 +00001678 else {
1679 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001680 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001681 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1682 if (VD->getType()->isObjCQualifiedIdType() ||
1683 VD->getType()->isObjCQualifiedInterfaceType())
1684 // Simply use 'id' for all qualified types.
1685 elementTypeAsString = "id";
1686 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001687 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001688 }
Mike Stump1eb44332009-09-09 15:08:12 +00001689
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001690 // struct __objcFastEnumerationState enumState = { 0 };
1691 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1692 // id items[16];
1693 buf += "id items[16];\n\t";
1694 // id l_collection = (id)
1695 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001696 // Find start location of 'collection' the hard way!
1697 const char *startCollectionBuf = startBuf;
1698 startCollectionBuf += 3; // skip 'for'
1699 startCollectionBuf = strchr(startCollectionBuf, '(');
1700 startCollectionBuf++; // skip '('
1701 // find 'in' and skip it.
1702 while (*startCollectionBuf != ' ' ||
1703 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1704 (*(startCollectionBuf+3) != ' ' &&
1705 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1706 startCollectionBuf++;
1707 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001708
1709 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001710 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001711 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001712 SourceLocation rightParenLoc = S->getRParenLoc();
1713 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1714 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001715 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001716
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001717 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1718 // objects:items count:16];
1719 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001720 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001721 // ((unsigned int (*)
1722 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001724 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001725 // "countByEnumeratingWithState:objects:count:"),
1726 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001727 // (id *)items, (unsigned int)16);
1728 buf += "unsigned long limit =\n\t\t";
1729 SynthCountByEnumWithState(buf);
1730 buf += ";\n\t";
1731 /// if (limit) {
1732 /// unsigned long startMutations = *enumState.mutationsPtr;
1733 /// do {
1734 /// unsigned long counter = 0;
1735 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001736 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001737 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001738 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001739 buf += "if (limit) {\n\t";
1740 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1741 buf += "do {\n\t\t";
1742 buf += "unsigned long counter = 0;\n\t\t";
1743 buf += "do {\n\t\t\t";
1744 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1745 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1746 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001747 buf += " = (";
1748 buf += elementTypeAsString;
1749 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001750 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001751 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001752
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001753 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001754 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001755 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001756 /// objects:items count:16]);
1757 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001758 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001759 /// }
1760 /// else
1761 /// elem = nil;
1762 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001763 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001764 buf = ";\n\t";
1765 buf += "__continue_label_";
1766 buf += utostr(ObjCBcLabelNo.back());
1767 buf += ": ;";
1768 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001769 buf += "} while (counter < limit);\n\t";
1770 buf += "} while (limit = ";
1771 SynthCountByEnumWithState(buf);
1772 buf += ");\n\t";
1773 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001774 buf += " = ((";
1775 buf += elementTypeAsString;
1776 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001777 buf += "__break_label_";
1778 buf += utostr(ObjCBcLabelNo.back());
1779 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001780 buf += "}\n\t";
1781 buf += "else\n\t\t";
1782 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001783 buf += " = ((";
1784 buf += elementTypeAsString;
1785 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001786 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001788 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001789 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001790 if (isa<CompoundStmt>(S->getBody())) {
1791 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001792 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001793 } else {
1794 /* Need to treat single statements specially. For example:
1795 *
1796 * for (A *a in b) if (stuff()) break;
1797 * for (A *a in b) xxxyy;
1798 *
1799 * The following code simply scans ahead to the semi to find the actual end.
1800 */
1801 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1802 const char *semiBuf = strchr(stmtBuf, ';');
1803 assert(semiBuf && "Can't find ';'");
1804 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001805 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001806 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001807 Stmts.pop_back();
1808 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001809 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001810}
1811
Mike Stump1eb44332009-09-09 15:08:12 +00001812/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001813/// This routine rewrites @synchronized(expr) stmt;
1814/// into:
1815/// objc_sync_enter(expr);
1816/// @try stmt @finally { objc_sync_exit(expr); }
1817///
Steve Naroffb29b4272008-04-14 22:03:09 +00001818Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001819 // Get the start location and compute the semi location.
1820 SourceLocation startLoc = S->getLocStart();
1821 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001822
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001823 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001824
1825 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001826 buf = "objc_sync_enter((id)";
1827 const char *lparenBuf = startBuf;
1828 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001829 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001830 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1831 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001832 // been rewritten! (which implies the SourceLocation's are invalid).
1833 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001834 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001835 while (*endBuf != ')') endBuf--;
1836 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001837 buf = ");\n";
1838 // declare a new scope with two variables, _stack and _rethrow.
1839 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1840 buf += "int buf[18/*32-bit i386*/];\n";
1841 buf += "char *pointers[4];} _stack;\n";
1842 buf += "id volatile _rethrow = 0;\n";
1843 buf += "objc_exception_try_enter(&_stack);\n";
1844 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001845 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001846 startLoc = S->getSynchBody()->getLocEnd();
1847 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001848
Steve Naroffc7089f12008-08-19 13:04:19 +00001849 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001850 SourceLocation lastCurlyLoc = startLoc;
1851 buf = "}\nelse {\n";
1852 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001853 buf += "}\n";
1854 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001855 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001856
1857 std::string syncBuf;
1858 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001859
1860 Expr *syncExpr = S->getSynchExpr();
1861 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1862 ? CK_BitCast :
1863 syncExpr->getType()->isBlockPointerType()
1864 ? CK_BlockPointerToObjCPointerCast
1865 : CK_CPointerToObjCPointerCast;
1866 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1867 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001868 std::string syncExprBufS;
1869 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001870 syncExpr->printPretty(syncExprBuf, *Context, 0,
1871 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001872 syncBuf += syncExprBuf.str();
1873 syncBuf += ");";
1874
1875 buf += syncBuf;
1876 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001877 buf += "}\n";
1878 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001879
Benjamin Kramerd999b372010-02-14 14:14:16 +00001880 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001881
1882 bool hasReturns = false;
1883 HasReturnStmts(S->getSynchBody(), hasReturns);
1884 if (hasReturns)
1885 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1886
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001887 return 0;
1888}
1889
Steve Naroffb85e77a2009-12-05 21:43:12 +00001890void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1891{
Steve Naroff8c565152008-12-05 17:03:39 +00001892 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001893 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001894 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001895 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001896
Steve Naroffb85e77a2009-12-05 21:43:12 +00001897 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001898 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001899 TryFinallyContainsReturnDiag);
1900 }
1901 return;
1902}
1903
Steve Naroffb85e77a2009-12-05 21:43:12 +00001904void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1905{
1906 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001907 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001908 if (*CI)
1909 HasReturnStmts(*CI, hasReturns);
1910
1911 if (isa<ReturnStmt>(S))
1912 hasReturns = true;
1913 return;
1914}
1915
1916void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1917 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001918 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001919 if (*CI) {
1920 RewriteTryReturnStmts(*CI);
1921 }
1922 if (isa<ReturnStmt>(S)) {
1923 SourceLocation startLoc = S->getLocStart();
1924 const char *startBuf = SM->getCharacterData(startLoc);
1925
1926 const char *semiBuf = strchr(startBuf, ';');
1927 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1928 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1929
1930 std::string buf;
1931 buf = "{ objc_exception_try_exit(&_stack); return";
1932
Benjamin Kramerd999b372010-02-14 14:14:16 +00001933 ReplaceText(startLoc, 6, buf);
1934 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001935 }
1936 return;
1937}
1938
1939void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1940 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001941 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001942 if (*CI) {
1943 RewriteSyncReturnStmts(*CI, syncExitBuf);
1944 }
1945 if (isa<ReturnStmt>(S)) {
1946 SourceLocation startLoc = S->getLocStart();
1947 const char *startBuf = SM->getCharacterData(startLoc);
1948
1949 const char *semiBuf = strchr(startBuf, ';');
1950 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1951 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1952
1953 std::string buf;
1954 buf = "{ objc_exception_try_exit(&_stack);";
1955 buf += syncExitBuf;
1956 buf += " return";
1957
Benjamin Kramerd999b372010-02-14 14:14:16 +00001958 ReplaceText(startLoc, 6, buf);
1959 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001960 }
1961 return;
1962}
1963
Steve Naroffb29b4272008-04-14 22:03:09 +00001964Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001965 // Get the start location and compute the semi location.
1966 SourceLocation startLoc = S->getLocStart();
1967 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001968
Steve Naroff75730982007-11-07 04:08:17 +00001969 assert((*startBuf == '@') && "bogus @try location");
1970
1971 std::string buf;
1972 // declare a new scope with two variables, _stack and _rethrow.
1973 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1974 buf += "int buf[18/*32-bit i386*/];\n";
1975 buf += "char *pointers[4];} _stack;\n";
1976 buf += "id volatile _rethrow = 0;\n";
1977 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001978 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001979
Benjamin Kramerd999b372010-02-14 14:14:16 +00001980 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001981
Steve Naroff75730982007-11-07 04:08:17 +00001982 startLoc = S->getTryBody()->getLocEnd();
1983 startBuf = SM->getCharacterData(startLoc);
1984
1985 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Steve Naroff75730982007-11-07 04:08:17 +00001987 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001988 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001989 startLoc = startLoc.getFileLocWithOffset(1);
1990 buf = " /* @catch begin */ else {\n";
1991 buf += " id _caught = objc_exception_extract(&_stack);\n";
1992 buf += " objc_exception_try_enter (&_stack);\n";
1993 buf += " if (_setjmp(_stack.buf))\n";
1994 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1995 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001996
Benjamin Kramerd999b372010-02-14 14:14:16 +00001997 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001998 } else { /* no catch list */
1999 buf = "}\nelse {\n";
2000 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2001 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00002003 }
Steve Naroff75730982007-11-07 04:08:17 +00002004 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002005 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2006 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00002007 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00002008
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002009 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00002010 buf = "if ("; // we are generating code for the first catch clause
2011 else
2012 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002013 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00002014 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Steve Naroff75730982007-11-07 04:08:17 +00002016 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00002017
Steve Naroff75730982007-11-07 04:08:17 +00002018 const char *lParenLoc = strchr(startBuf, '(');
2019
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002020 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00002021 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002022 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002023 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2024 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002025 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002026 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002027 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Steve Naroffe12e6922008-02-01 20:02:07 +00002029 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002030 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002031 } else if (catchDecl) {
2032 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002033 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002034 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002035 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002036 } else if (const ObjCObjectPointerType *Ptr =
2037 t->getAs<ObjCObjectPointerType>()) {
2038 // Should be a pointer to a class.
2039 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2040 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002041 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002042 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002043 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002044 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002045 }
2046 }
2047 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002048 lastCatchBody = Catch->getCatchBody();
2049 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002050 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2051 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2052 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2053 assert((*rParenBuf == ')') && "bogus @catch paren location");
2054 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Mike Stump1eb44332009-09-09 15:08:12 +00002056 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002057 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002058 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002059 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002060 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002061 }
Steve Naroff75730982007-11-07 04:08:17 +00002062 }
2063 // Complete the catch list...
2064 if (lastCatchBody) {
2065 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002066 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2067 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002068
Steve Naroff378f47a2008-09-11 15:29:03 +00002069 // Insert the last (implicit) else clause *before* the right curly brace.
2070 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2071 buf = "} /* last catch end */\n";
2072 buf += "else {\n";
2073 buf += " _rethrow = _caught;\n";
2074 buf += " objc_exception_try_exit(&_stack);\n";
2075 buf += "} } /* @catch end */\n";
2076 if (!S->getFinallyStmt())
2077 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002078 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002079
Steve Naroff75730982007-11-07 04:08:17 +00002080 // Set lastCurlyLoc
2081 lastCurlyLoc = lastCatchBody->getLocEnd();
2082 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002083 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002084 startLoc = finalStmt->getLocStart();
2085 startBuf = SM->getCharacterData(startLoc);
2086 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Benjamin Kramerd999b372010-02-14 14:14:16 +00002088 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Steve Naroff75730982007-11-07 04:08:17 +00002090 Stmt *body = finalStmt->getFinallyBody();
2091 SourceLocation startLoc = body->getLocStart();
2092 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002093 assert(*SM->getCharacterData(startLoc) == '{' &&
2094 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002095 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002096 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002097
Steve Naroff75730982007-11-07 04:08:17 +00002098 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002099 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002100 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002101 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Steve Naroff75730982007-11-07 04:08:17 +00002103 // Set lastCurlyLoc
2104 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002105
Steve Naroff8c565152008-12-05 17:03:39 +00002106 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002107 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002108 } else { /* no finally clause - make sure we synthesize an implicit one */
2109 buf = "{ /* implicit finally clause */\n";
2110 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2111 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2112 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002113 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002114
2115 // Now check for any return/continue/go statements within the @try.
2116 // The implicit finally clause won't called if the @try contains any
2117 // jump statements.
2118 bool hasReturns = false;
2119 HasReturnStmts(S->getTryBody(), hasReturns);
2120 if (hasReturns)
2121 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002122 }
2123 // Now emit the final closing curly brace...
2124 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002125 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002126 return 0;
2127}
2128
Mike Stump1eb44332009-09-09 15:08:12 +00002129// This can't be done with ReplaceStmt(S, ThrowExpr), since
2130// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002131// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002132Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002133 // Get the start location and compute the semi location.
2134 SourceLocation startLoc = S->getLocStart();
2135 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002136
Steve Naroff2bd03922007-11-07 15:32:26 +00002137 assert((*startBuf == '@') && "bogus @throw location");
2138
2139 std::string buf;
2140 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002141 if (S->getThrowExpr())
2142 buf = "objc_exception_throw(";
2143 else // add an implicit argument
2144 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002145
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002146 // handle "@ throw" correctly.
2147 const char *wBuf = strchr(startBuf, 'w');
2148 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002149 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Steve Naroff2bd03922007-11-07 15:32:26 +00002151 const char *semiBuf = strchr(startBuf, ';');
2152 assert((*semiBuf == ';') && "@throw: can't find ';'");
2153 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002154 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002155 return 0;
2156}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002157
Steve Naroffb29b4272008-04-14 22:03:09 +00002158Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002159 // Create a new string expression.
2160 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002161 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002162 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002163 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002164 StringLiteral::Ascii, false,
2165 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002166 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Chris Lattner07506182007-11-30 22:53:43 +00002168 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002169 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002170 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002171}
2172
Steve Naroffb29b4272008-04-14 22:03:09 +00002173Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002174 if (!SelGetUidFunctionDecl)
2175 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002176 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2177 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002178 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002179 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002180 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002181 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002182 StringLiteral::Ascii, false,
2183 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002184 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2185 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002186 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002187 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002188 return SelExp;
2189}
2190
Steve Naroffb29b4272008-04-14 22:03:09 +00002191CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002192 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2193 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002194 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002195 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002196
Steve Naroffebf2b562007-10-23 23:50:29 +00002197 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002198 DeclRefExpr *DRE =
2199 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Steve Naroffebf2b562007-10-23 23:50:29 +00002201 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002202 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002203 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002204 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002205 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002206
John McCall183700f2009-09-21 23:43:11 +00002207 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002208
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002209 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002210 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002211 FT->getCallResultType(*Context),
2212 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002213 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002214}
2215
Steve Naroffd5255f52007-11-01 13:24:47 +00002216static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2217 const char *&startRef, const char *&endRef) {
2218 while (startBuf < endBuf) {
2219 if (*startBuf == '<')
2220 startRef = startBuf; // mark the start.
2221 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002222 if (startRef && *startRef == '<') {
2223 endRef = startBuf; // mark the end.
2224 return true;
2225 }
2226 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002227 }
2228 startBuf++;
2229 }
2230 return false;
2231}
2232
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002233static void scanToNextArgument(const char *&argRef) {
2234 int angle = 0;
2235 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2236 if (*argRef == '<')
2237 angle++;
2238 else if (*argRef == '>')
2239 angle--;
2240 argRef++;
2241 }
2242 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2243}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002244
Steve Naroffb29b4272008-04-14 22:03:09 +00002245bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002246 if (T->isObjCQualifiedIdType())
2247 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002248 if (const PointerType *PT = T->getAs<PointerType>()) {
2249 if (PT->getPointeeType()->isObjCQualifiedIdType())
2250 return true;
2251 }
2252 if (T->isObjCObjectPointerType()) {
2253 T = T->getPointeeType();
2254 return T->isObjCQualifiedInterfaceType();
2255 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002256 if (T->isArrayType()) {
2257 QualType ElemTy = Context->getBaseElementType(T);
2258 return needToScanForQualifiers(ElemTy);
2259 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002260 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002261}
2262
Steve Naroff4f95b752008-07-29 18:15:38 +00002263void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2264 QualType Type = E->getType();
2265 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002266 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002267
Steve Naroffcda658e2008-11-19 21:15:47 +00002268 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2269 Loc = ECE->getLParenLoc();
2270 EndLoc = ECE->getRParenLoc();
2271 } else {
2272 Loc = E->getLocStart();
2273 EndLoc = E->getLocEnd();
2274 }
2275 // This will defend against trying to rewrite synthesized expressions.
2276 if (Loc.isInvalid() || EndLoc.isInvalid())
2277 return;
2278
Steve Naroff4f95b752008-07-29 18:15:38 +00002279 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002280 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002281 const char *startRef = 0, *endRef = 0;
2282 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2283 // Get the locations of the startRef, endRef.
2284 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2285 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2286 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002287 InsertText(LessLoc, "/*");
2288 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002289 }
2290 }
2291}
2292
Steve Naroffb29b4272008-04-14 22:03:09 +00002293void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002294 SourceLocation Loc;
2295 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002296 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002297 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2298 Loc = VD->getLocation();
2299 Type = VD->getType();
2300 }
2301 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2302 Loc = FD->getLocation();
2303 // Check for ObjC 'id' and class types that have been adorned with protocol
2304 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002305 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002306 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002307 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002308 if (!proto)
2309 return;
2310 Type = proto->getResultType();
2311 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002312 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2313 Loc = FD->getLocation();
2314 Type = FD->getType();
2315 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002316 else
2317 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002318
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002319 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002320 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002321
Steve Naroffd5255f52007-11-01 13:24:47 +00002322 const char *endBuf = SM->getCharacterData(Loc);
2323 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002324 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002325 startBuf--; // scan backward (from the decl location) for return type.
2326 const char *startRef = 0, *endRef = 0;
2327 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2328 // Get the locations of the startRef, endRef.
2329 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2330 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2331 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002332 InsertText(LessLoc, "/*");
2333 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002334 }
2335 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002336 if (!proto)
2337 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002338 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002339 const char *startBuf = SM->getCharacterData(Loc);
2340 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002341 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2342 if (needToScanForQualifiers(proto->getArgType(i))) {
2343 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002344
Steve Naroffd5255f52007-11-01 13:24:47 +00002345 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002346 // scan forward (from the decl location) for argument types.
2347 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002348 const char *startRef = 0, *endRef = 0;
2349 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2350 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002351 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002352 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002353 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002354 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002355 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002356 InsertText(LessLoc, "/*");
2357 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002358 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002359 startBuf = ++endBuf;
2360 }
2361 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002362 // If the function name is derived from a macro expansion, then the
2363 // argument buffer will not follow the name. Need to speak with Chris.
2364 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002365 startBuf++; // scan forward (from the decl location) for argument types.
2366 startBuf++;
2367 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002368 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002369}
2370
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002371void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2372 QualType QT = ND->getType();
2373 const Type* TypePtr = QT->getAs<Type>();
2374 if (!isa<TypeOfExprType>(TypePtr))
2375 return;
2376 while (isa<TypeOfExprType>(TypePtr)) {
2377 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2378 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2379 TypePtr = QT->getAs<Type>();
2380 }
2381 // FIXME. This will not work for multiple declarators; as in:
2382 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002383 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002384 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2385 const char *startBuf = SM->getCharacterData(DeclLoc);
2386 if (ND->getInit()) {
2387 std::string Name(ND->getNameAsString());
2388 TypeAsString += " " + Name + " = ";
2389 Expr *E = ND->getInit();
2390 SourceLocation startLoc;
2391 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2392 startLoc = ECE->getLParenLoc();
2393 else
2394 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002395 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002396 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002397 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002398 }
2399 else {
2400 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002401 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002402 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002403 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002404 }
2405}
2406
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002407// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002408void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002409 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002410 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002411 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002412 QualType getFuncType =
2413 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002414 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002415 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002416 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002417 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002418 SC_Extern,
2419 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002420}
2421
Steve Naroffb29b4272008-04-14 22:03:09 +00002422void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002423 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002424 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002425 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002426 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002427 return;
2428 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002429 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002430}
2431
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002432void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2433 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002434 const char *argPtr = TypeString.c_str();
2435 if (!strchr(argPtr, '^')) {
2436 Str += TypeString;
2437 return;
2438 }
2439 while (*argPtr) {
2440 Str += (*argPtr == '^' ? '*' : *argPtr);
2441 argPtr++;
2442 }
2443}
2444
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002445// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002446void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2447 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002448 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002449 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002450 const char *argPtr = TypeString.c_str();
2451 int paren = 0;
2452 while (*argPtr) {
2453 switch (*argPtr) {
2454 case '(':
2455 Str += *argPtr;
2456 paren++;
2457 break;
2458 case ')':
2459 Str += *argPtr;
2460 paren--;
2461 break;
2462 case '^':
2463 Str += '*';
2464 if (paren == 1)
2465 Str += VD->getNameAsString();
2466 break;
2467 default:
2468 Str += *argPtr;
2469 break;
2470 }
2471 argPtr++;
2472 }
2473}
2474
2475
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002476void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2477 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2478 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2479 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2480 if (!proto)
2481 return;
2482 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002483 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002484 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002485 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002486 FdStr += "(";
2487 unsigned numArgs = proto->getNumArgs();
2488 for (unsigned i = 0; i < numArgs; i++) {
2489 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002490 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002491 if (i+1 < numArgs)
2492 FdStr += ", ";
2493 }
2494 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002495 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002496 CurFunctionDeclToDeclareForBlock = 0;
2497}
2498
Steve Naroffc0a123c2008-03-11 17:37:02 +00002499// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002500void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002501 if (SuperContructorFunctionDecl)
2502 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002503 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002504 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002505 QualType argT = Context->getObjCIdType();
2506 assert(!argT.isNull() && "Can't find 'id' type");
2507 ArgTys.push_back(argT);
2508 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002509 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2510 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002511 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002512 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002513 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002514 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002515 SC_Extern,
2516 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002517}
2518
Steve Naroff09b266e2007-10-30 23:14:51 +00002519// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002520void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002521 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002522 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002523 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002524 assert(!argT.isNull() && "Can't find 'id' type");
2525 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002526 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002527 assert(!argT.isNull() && "Can't find 'SEL' type");
2528 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002529 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2530 &ArgTys[0], ArgTys.size(),
2531 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002532 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002533 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002534 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002535 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002536 SC_Extern,
2537 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002538}
2539
Steve Naroff874e2322007-11-15 10:28:18 +00002540// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002541void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002542 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002543 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002544 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002545 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002546 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002547 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2548 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2549 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002550 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002551 assert(!argT.isNull() && "Can't find 'SEL' type");
2552 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002553 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2554 &ArgTys[0], ArgTys.size(),
2555 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002556 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002557 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002558 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002559 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002560 SC_Extern,
2561 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002562}
2563
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002564// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002565void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002566 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002567 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002568 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002569 assert(!argT.isNull() && "Can't find 'id' type");
2570 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002571 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002572 assert(!argT.isNull() && "Can't find 'SEL' type");
2573 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002574 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2575 &ArgTys[0], ArgTys.size(),
2576 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002577 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002578 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002579 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002580 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002581 SC_Extern,
2582 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002583}
2584
Mike Stump1eb44332009-09-09 15:08:12 +00002585// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002586// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002587void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002588 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002589 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002590 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002591 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002592 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002593 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002594 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2595 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2596 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002597 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002598 assert(!argT.isNull() && "Can't find 'SEL' type");
2599 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002600 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2601 &ArgTys[0], ArgTys.size(),
2602 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002603 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002604 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002605 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002606 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002607 SC_Extern,
2608 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002609}
2610
Steve Naroff1284db82008-05-08 22:02:18 +00002611// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002612void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002613 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002614 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002615 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002616 assert(!argT.isNull() && "Can't find 'id' type");
2617 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002618 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002619 assert(!argT.isNull() && "Can't find 'SEL' type");
2620 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002621 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2622 &ArgTys[0], ArgTys.size(),
2623 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002624 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002625 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002626 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002627 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002628 SC_Extern,
2629 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002630}
2631
Steve Naroff09b266e2007-10-30 23:14:51 +00002632// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002633void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002634 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002635 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002636 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002637 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2638 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002639 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002640 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002641 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002642 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002643 SC_Extern,
2644 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002645}
2646
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002647// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2648void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2649 IdentifierInfo *getSuperClassIdent =
2650 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002651 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002652 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002653 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2654 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002655 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002656 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002657 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002658 getSuperClassIdent,
2659 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002660 SC_Extern,
2661 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002662 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002663}
2664
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002665// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002666void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002667 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002668 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002669 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002670 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2671 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002672 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002673 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002674 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002675 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002676 SC_Extern,
2677 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002678}
2679
Steve Naroffb29b4272008-04-14 22:03:09 +00002680Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002681 QualType strType = getConstantStringStructType();
2682
2683 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002684
2685 std::string tmpName = InFileName;
2686 unsigned i;
2687 for (i=0; i < tmpName.length(); i++) {
2688 char c = tmpName.at(i);
2689 // replace any non alphanumeric characters with '_'.
2690 if (!isalpha(c) && (c < '0' || c > '9'))
2691 tmpName[i] = '_';
2692 }
2693 S += tmpName;
2694 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002695 S += utostr(NumObjCStringLiterals++);
2696
Steve Naroffba92b2e2008-03-27 22:29:16 +00002697 Preamble += "static __NSConstantStringImpl " + S;
2698 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2699 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002701 std::string prettyBufS;
2702 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002703 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2704 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002705 Preamble += prettyBuf.str();
2706 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002707 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002708
2709 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002710 SourceLocation(), &Context->Idents.get(S),
2711 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002712 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2713 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002714 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002715 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002716 VK_RValue, OK_Ordinary,
2717 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002718 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002719 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002720 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002721 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002722 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002723 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002724}
2725
Steve Naroff874e2322007-11-15 10:28:18 +00002726// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002727QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002728 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002729 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002730 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002731 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002732 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002733
Steve Naroff874e2322007-11-15 10:28:18 +00002734 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002735 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002736 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002737 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002738
Steve Naroff874e2322007-11-15 10:28:18 +00002739 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002740 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002741 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002742 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002743 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002744 FieldTypes[i], 0,
2745 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002746 /*Mutable=*/false,
2747 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002748 }
Mike Stump1eb44332009-09-09 15:08:12 +00002749
Douglas Gregor838db382010-02-11 01:19:42 +00002750 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002751 }
2752 return Context->getTagDeclType(SuperStructDecl);
2753}
2754
Steve Naroffb29b4272008-04-14 22:03:09 +00002755QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002756 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002757 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002758 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002759 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002760 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002761
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002762 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002763 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002764 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002765 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002766 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002767 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002768 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002769 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002770
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002771 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002772 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002773 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2774 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002775 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002776 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002777 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002778 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002779 /*Mutable=*/true,
2780 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002781 }
2782
Douglas Gregor838db382010-02-11 01:19:42 +00002783 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002784 }
2785 return Context->getTagDeclType(ConstantStringDecl);
2786}
2787
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002788Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2789 SourceLocation StartLoc,
2790 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002791 if (!SelGetUidFunctionDecl)
2792 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002793 if (!MsgSendFunctionDecl)
2794 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002795 if (!MsgSendSuperFunctionDecl)
2796 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002797 if (!MsgSendStretFunctionDecl)
2798 SynthMsgSendStretFunctionDecl();
2799 if (!MsgSendSuperStretFunctionDecl)
2800 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002801 if (!MsgSendFpretFunctionDecl)
2802 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002803 if (!GetClassFunctionDecl)
2804 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002805 if (!GetSuperClassFunctionDecl)
2806 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002807 if (!GetMetaClassFunctionDecl)
2808 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002809
Steve Naroff874e2322007-11-15 10:28:18 +00002810 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002811 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2812 // May need to use objc_msgSend_stret() as well.
2813 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002814 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2815 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002816 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002817 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002818 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002819 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002820 }
Mike Stump1eb44332009-09-09 15:08:12 +00002821
Steve Naroff934f2762007-10-24 22:48:43 +00002822 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002823 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002824 switch (Exp->getReceiverKind()) {
2825 case ObjCMessageExpr::SuperClass: {
2826 MsgSendFlavor = MsgSendSuperFunctionDecl;
2827 if (MsgSendStretFlavor)
2828 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2829 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Douglas Gregor04badcf2010-04-21 00:45:42 +00002831 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002832
Chris Lattner5f9e2722011-07-23 10:55:15 +00002833 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002834
Douglas Gregor04badcf2010-04-21 00:45:42 +00002835 // set the receiver to self, the first argument to all methods.
2836 InitExprs.push_back(
2837 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002838 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002839 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002840 Context->getObjCIdType(),
2841 VK_RValue,
2842 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002843 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002844
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002846 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002847 QualType argType = Context->getPointerType(Context->CharTy);
2848 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002849 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002850 StringLiteral::Ascii, false,
2851 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2853 &ClsExprs[0],
2854 ClsExprs.size(),
2855 StartLoc,
2856 EndLoc);
2857 // (Class)objc_getClass("CurrentClass")
2858 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2859 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002860 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002861 ClsExprs.clear();
2862 ClsExprs.push_back(ArgExpr);
2863 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2864 &ClsExprs[0], ClsExprs.size(),
2865 StartLoc, EndLoc);
2866
2867 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2868 // To turn off a warning, type-cast to 'id'
2869 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2870 NoTypeInfoCStyleCastExpr(Context,
2871 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002872 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002873 // struct objc_super
2874 QualType superType = getSuperStructType();
2875 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002876
Douglas Gregor04badcf2010-04-21 00:45:42 +00002877 if (LangOpts.Microsoft) {
2878 SynthSuperContructorFunctionDecl();
2879 // Simulate a contructor call...
2880 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002881 superType, VK_LValue,
2882 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002883 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2884 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002885 superType, VK_LValue,
2886 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002887 // The code for super is a little tricky to prevent collision with
2888 // the structure definition in the header. The rewriter has it's own
2889 // internal definition (__rw_objc_super) that is uses. This is why
2890 // we need the cast below. For example:
2891 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2892 //
John McCall2de56d12010-08-25 11:45:40 +00002893 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002894 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002895 VK_RValue, OK_Ordinary,
2896 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002897 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2898 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002899 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002900 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002901 // (struct objc_super) { <exprs from above> }
2902 InitListExpr *ILE =
2903 new (Context) InitListExpr(*Context, SourceLocation(),
2904 &InitExprs[0], InitExprs.size(),
2905 SourceLocation());
2906 TypeSourceInfo *superTInfo
2907 = Context->getTrivialTypeSourceInfo(superType);
2908 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002909 superType, VK_LValue,
2910 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002911 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002912 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002913 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002914 VK_RValue, OK_Ordinary,
2915 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002916 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002917 MsgExprs.push_back(SuperRep);
2918 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002919 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002920
2921 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002922 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002923 QualType argType = Context->getPointerType(Context->CharTy);
2924 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002925 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002926 IdentifierInfo *clsName = Class->getIdentifier();
2927 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002928 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002929 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002930 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002931 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2932 &ClsExprs[0],
2933 ClsExprs.size(),
2934 StartLoc, EndLoc);
2935 MsgExprs.push_back(Cls);
2936 break;
2937 }
2938
2939 case ObjCMessageExpr::SuperInstance:{
2940 MsgSendFlavor = MsgSendSuperFunctionDecl;
2941 if (MsgSendStretFlavor)
2942 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2943 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2944 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002945 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002946
2947 InitExprs.push_back(
2948 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002949 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002950 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002951 Context->getObjCIdType(),
2952 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002953 ); // set the 'receiver'.
2954
2955 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002956 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002957 QualType argType = Context->getPointerType(Context->CharTy);
2958 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002959 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002960 StringLiteral::Ascii, false, argType,
2961 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002962 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2963 &ClsExprs[0],
2964 ClsExprs.size(),
2965 StartLoc, EndLoc);
2966 // (Class)objc_getClass("CurrentClass")
2967 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2968 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002969 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002970 ClsExprs.clear();
2971 ClsExprs.push_back(ArgExpr);
2972 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2973 &ClsExprs[0], ClsExprs.size(),
2974 StartLoc, EndLoc);
2975
2976 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2977 // To turn off a warning, type-cast to 'id'
2978 InitExprs.push_back(
2979 // set 'super class', using class_getSuperclass().
2980 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002981 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002982 // struct objc_super
2983 QualType superType = getSuperStructType();
2984 Expr *SuperRep;
2985
2986 if (LangOpts.Microsoft) {
2987 SynthSuperContructorFunctionDecl();
2988 // Simulate a contructor call...
2989 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002990 superType, VK_LValue,
2991 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002992 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2993 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002994 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002995 // The code for super is a little tricky to prevent collision with
2996 // the structure definition in the header. The rewriter has it's own
2997 // internal definition (__rw_objc_super) that is uses. This is why
2998 // we need the cast below. For example:
2999 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3000 //
John McCall2de56d12010-08-25 11:45:40 +00003001 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003002 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003003 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003004 SourceLocation());
3005 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3006 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00003007 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003008 } else {
3009 // (struct objc_super) { <exprs from above> }
3010 InitListExpr *ILE =
3011 new (Context) InitListExpr(*Context, SourceLocation(),
3012 &InitExprs[0], InitExprs.size(),
3013 SourceLocation());
3014 TypeSourceInfo *superTInfo
3015 = Context->getTrivialTypeSourceInfo(superType);
3016 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003017 superType, VK_RValue, ILE,
3018 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003019 }
3020 MsgExprs.push_back(SuperRep);
3021 break;
3022 }
3023
3024 case ObjCMessageExpr::Instance: {
3025 // Remove all type-casts because it may contain objc-style types; e.g.
3026 // Foo<Proto> *.
3027 Expr *recExpr = Exp->getInstanceReceiver();
3028 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3029 recExpr = CE->getSubExpr();
3030 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003031 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003032 MsgExprs.push_back(recExpr);
3033 break;
3034 }
3035 }
3036
Steve Naroffbeaf2992007-11-03 11:27:19 +00003037 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003038 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003039 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003040 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003041 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003042 StringLiteral::Ascii, false,
3043 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003044 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003045 &SelExprs[0], SelExprs.size(),
3046 StartLoc,
3047 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003048 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003049
Steve Naroff934f2762007-10-24 22:48:43 +00003050 // Now push any user supplied arguments.
3051 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003052 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003053 // Make all implicit casts explicit...ICE comes in handy:-)
3054 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3055 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003056 QualType type = ICE->getType();
3057 if (needToScanForQualifiers(type))
3058 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003059 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003060 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003061 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003062 CastKind CK;
3063 if (SubExpr->getType()->isIntegralType(*Context) &&
3064 type->isBooleanType()) {
3065 CK = CK_IntegralToBoolean;
3066 } else if (type->isObjCObjectPointerType()) {
3067 if (SubExpr->getType()->isBlockPointerType()) {
3068 CK = CK_BlockPointerToObjCPointerCast;
3069 } else if (SubExpr->getType()->isPointerType()) {
3070 CK = CK_CPointerToObjCPointerCast;
3071 } else {
3072 CK = CK_BitCast;
3073 }
3074 } else {
3075 CK = CK_BitCast;
3076 }
3077
3078 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003079 }
3080 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003081 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003082 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003083 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003084 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003085 CastKind CK;
3086 if (userExpr->getType()->isIntegralType(*Context)) {
3087 CK = CK_IntegralToPointer;
3088 } else if (userExpr->getType()->isBlockPointerType()) {
3089 CK = CK_BlockPointerToObjCPointerCast;
3090 } else if (userExpr->getType()->isPointerType()) {
3091 CK = CK_CPointerToObjCPointerCast;
3092 } else {
3093 CK = CK_BitCast;
3094 }
John McCall9d125032010-01-15 18:39:57 +00003095 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003096 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003097 }
Mike Stump1eb44332009-09-09 15:08:12 +00003098 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003099 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003100 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3101 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003102 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003103 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003104 }
Steve Naroffab972d32007-11-04 22:37:50 +00003105 // Generate the funky cast.
3106 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003107 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003108 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003109
Steve Naroffab972d32007-11-04 22:37:50 +00003110 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003111 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3112 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3113 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003114 ArgTypes.push_back(Context->getObjCIdType());
3115 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003116 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003117 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003118 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3119 E = OMD->param_end(); PI != E; ++PI) {
3120 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003121 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003122 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003123 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003124 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003125 ArgTypes.push_back(t);
3126 }
Chris Lattner89951a82009-02-20 18:43:26 +00003127 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3128 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003129 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003130 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003131 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003132 }
3133 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003134 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003135
Steve Naroffab972d32007-11-04 22:37:50 +00003136 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003137 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003138 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003139
Mike Stump1eb44332009-09-09 15:08:12 +00003140 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003141 // If we don't do this cast, we get the following bizarre warning/note:
3142 // xx.m:13: warning: function called through a non-compatible type
3143 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003144 cast = NoTypeInfoCStyleCastExpr(Context,
3145 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003146 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003147
Steve Naroffab972d32007-11-04 22:37:50 +00003148 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003149 QualType castType =
3150 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3151 // If we don't have a method decl, force a variadic cast.
3152 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003153 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003154 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003155 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003156
3157 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003158 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003159
John McCall183700f2009-09-21 23:43:11 +00003160 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003161 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003162 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003163 FT->getResultType(), VK_RValue,
3164 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003165 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003166 if (MsgSendStretFlavor) {
3167 // We have the method which returns a struct/union. Must also generate
3168 // call to objc_msgSend_stret and hang both varieties on a conditional
3169 // expression which dictate which one to envoke depending on size of
3170 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003171
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003172 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003173 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003174 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003175 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003176 cast = NoTypeInfoCStyleCastExpr(Context,
3177 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003178 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003179 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003180 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3181 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003182 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003183 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003184 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003185
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003186 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003187 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003188
John McCall183700f2009-09-21 23:43:11 +00003189 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003190 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003191 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003192 FT->getResultType(), VK_RValue,
3193 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003194
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003195 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003196 UnaryExprOrTypeTraitExpr *sizeofExpr =
3197 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3198 Context->getTrivialTypeSourceInfo(returnType),
3199 Context->getSizeType(), SourceLocation(),
3200 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003201 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3202 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3203 // For X86 it is more complicated and some kind of target specific routine
3204 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003205 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003206 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003207 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3208 llvm::APInt(IntSize, 8),
3209 Context->IntTy,
3210 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003211 BinaryOperator *lessThanExpr =
3212 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3213 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003214 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003215 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003216 new (Context) ConditionalOperator(lessThanExpr,
3217 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003218 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003219 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003220 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3221 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003222 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003223 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003224 return ReplacingStmt;
3225}
3226
Steve Naroffb29b4272008-04-14 22:03:09 +00003227Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003228 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3229 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003230
Steve Naroff934f2762007-10-24 22:48:43 +00003231 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003232 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003233
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003234 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003235 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003236}
3237
Steve Naroff621edce2009-04-29 16:37:50 +00003238// typedef struct objc_object Protocol;
3239QualType RewriteObjC::getProtocolType() {
3240 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003241 TypeSourceInfo *TInfo
3242 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003243 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003244 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003245 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003246 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003247 }
3248 return Context->getTypeDeclType(ProtocolTypeDecl);
3249}
3250
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003251/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003252/// a synthesized/forward data reference (to the protocol's metadata).
3253/// The forward references (and metadata) are generated in
3254/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003255Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003256 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3257 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003258 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003259 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003260 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003261 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3262 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003263 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003264 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003265 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003266 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003267 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003268 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003269 ReplaceStmt(Exp, castExpr);
3270 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003271 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003272 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003273
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003274}
3275
Mike Stump1eb44332009-09-09 15:08:12 +00003276bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003277 const char *endBuf) {
3278 while (startBuf < endBuf) {
3279 if (*startBuf == '#') {
3280 // Skip whitespace.
3281 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3282 ;
3283 if (!strncmp(startBuf, "if", strlen("if")) ||
3284 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3285 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3286 !strncmp(startBuf, "define", strlen("define")) ||
3287 !strncmp(startBuf, "undef", strlen("undef")) ||
3288 !strncmp(startBuf, "else", strlen("else")) ||
3289 !strncmp(startBuf, "elif", strlen("elif")) ||
3290 !strncmp(startBuf, "endif", strlen("endif")) ||
3291 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3292 !strncmp(startBuf, "include", strlen("include")) ||
3293 !strncmp(startBuf, "import", strlen("import")) ||
3294 !strncmp(startBuf, "include_next", strlen("include_next")))
3295 return true;
3296 }
3297 startBuf++;
3298 }
3299 return false;
3300}
3301
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003302/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003303/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003304void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003305 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003306 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003307 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003308 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003309 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003310 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003311 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003312 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003313 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003314 SourceLocation LocStart = CDecl->getLocStart();
3315 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003316
Steve Narofffea763e82007-11-14 19:25:57 +00003317 const char *startBuf = SM->getCharacterData(LocStart);
3318 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003319
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003320 // If no ivars and no root or if its root, directly or indirectly,
3321 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003322 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3323 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003324 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003325 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003326 return;
3327 }
Mike Stump1eb44332009-09-09 15:08:12 +00003328
3329 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003330 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003331 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003332 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003333 if (LangOpts.Microsoft)
3334 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003335
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003336 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003337 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003338 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003339 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003340 // If the buffer contains preprocessor directives, we do more fine-grained
3341 // rewrites. This is intended to fix code that looks like (which occurs in
3342 // NSURL.h, for example):
3343 //
3344 // #ifdef XYZ
3345 // @interface Foo : NSObject
3346 // #else
3347 // @interface FooBar : NSObject
3348 // #endif
3349 // {
3350 // int i;
3351 // }
3352 // @end
3353 //
3354 // This clause is segregated to avoid breaking the common case.
3355 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003356 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003357 CDecl->getClassLoc();
3358 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003359 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003360
Chris Lattnercafeb352009-02-20 18:18:36 +00003361 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003362 // advance to the end of the referenced protocols.
3363 while (endHeader < cursor && *endHeader != '>') endHeader++;
3364 endHeader++;
3365 }
3366 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003367 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003368 } else {
3369 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003370 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003371 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003372 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003373 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003374 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003375 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003376 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003377 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003378
Steve Narofffea763e82007-11-14 19:25:57 +00003379 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003380 SourceLocation OnePastCurly =
3381 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003382 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003383 }
3384 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Steve Narofffea763e82007-11-14 19:25:57 +00003386 // Now comment out any visibility specifiers.
3387 while (cursor < endBuf) {
3388 if (*cursor == '@') {
3389 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003390 // Skip whitespace.
3391 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3392 /*scan*/;
3393
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003394 // FIXME: presence of @public, etc. inside comment results in
3395 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003396 if (!strncmp(cursor, "public", strlen("public")) ||
3397 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003398 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003399 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003400 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003401 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003402 // FIXME: If there are cases where '<' is used in ivar declaration part
3403 // of user code, then scan the ivar list and use needToScanForQualifiers
3404 // for type checking.
3405 else if (*cursor == '<') {
3406 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003407 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003408 cursor = strchr(cursor, '>');
3409 cursor++;
3410 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003411 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003412 } else if (*cursor == '^') { // rewrite block specifier.
3413 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003414 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003415 }
Steve Narofffea763e82007-11-14 19:25:57 +00003416 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003417 }
Steve Narofffea763e82007-11-14 19:25:57 +00003418 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003419 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003420 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003421 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003422 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003423 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003424 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003425 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003426 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003427 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003428 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003429 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003430 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003431 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003432}
3433
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003434// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003435/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003436template<typename MethodIterator>
3437void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3438 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003439 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003440 StringRef prefix,
3441 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003442 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003443 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003444
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003445 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003446 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003447 SEL _cmd;
3448 char *method_types;
3449 void *_imp;
3450 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003451 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003452 Result += "\nstruct _objc_method {\n";
3453 Result += "\tSEL _cmd;\n";
3454 Result += "\tchar *method_types;\n";
3455 Result += "\tvoid *_imp;\n";
3456 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003457
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003458 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003459 }
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003461 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003462
Steve Naroff946a6932008-03-11 00:12:29 +00003463 /* struct {
3464 struct _objc_method_list *next_method;
3465 int method_count;
3466 struct _objc_method method_list[];
3467 }
3468 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003469 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003470 Result += "\nstatic struct {\n";
3471 Result += "\tstruct _objc_method_list *next_method;\n";
3472 Result += "\tint method_count;\n";
3473 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003474 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003475 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003476 Result += prefix;
3477 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3478 Result += "_METHODS_";
3479 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003480 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003481 Result += IsInstanceMethod ? "inst" : "cls";
3482 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003483 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003484
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003485 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003486 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003487 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003488 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003489 Result += "\", \"";
3490 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003491 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003492 Result += MethodInternalNames[*MethodBegin];
3493 Result += "}\n";
3494 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3495 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003496 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003497 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003498 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003499 Result += "\", \"";
3500 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003501 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003502 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003503 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003504 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003505 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003506}
3507
Steve Naroff621edce2009-04-29 16:37:50 +00003508/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003509void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003510RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3511 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003512 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003513
3514 // Output struct protocol_methods holder of method selector and type.
3515 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3516 /* struct protocol_methods {
3517 SEL _cmd;
3518 char *method_types;
3519 }
3520 */
3521 Result += "\nstruct _protocol_methods {\n";
3522 Result += "\tstruct objc_selector *_cmd;\n";
3523 Result += "\tchar *method_types;\n";
3524 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003525
Steve Naroff621edce2009-04-29 16:37:50 +00003526 objc_protocol_methods = true;
3527 }
3528 // Do not synthesize the protocol more than once.
3529 if (ObjCSynthesizedProtocols.count(PDecl))
3530 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003531
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003532 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3533 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3534 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003535 /* struct _objc_protocol_method_list {
3536 int protocol_method_count;
3537 struct protocol_methods protocols[];
3538 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003539 */
Steve Naroff621edce2009-04-29 16:37:50 +00003540 Result += "\nstatic struct {\n";
3541 Result += "\tint protocol_method_count;\n";
3542 Result += "\tstruct _protocol_methods protocol_methods[";
3543 Result += utostr(NumMethods);
3544 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3545 Result += PDecl->getNameAsString();
3546 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3547 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003548
Steve Naroff621edce2009-04-29 16:37:50 +00003549 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003550 for (ObjCProtocolDecl::instmeth_iterator
3551 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003552 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003553 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003554 Result += "\t ,{{(struct objc_selector *)\"";
3555 else
3556 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003557 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003558 std::string MethodTypeString;
3559 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3560 Result += "\", \"";
3561 Result += MethodTypeString;
3562 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003563 }
Steve Naroff621edce2009-04-29 16:37:50 +00003564 Result += "\t }\n};\n";
3565 }
Mike Stump1eb44332009-09-09 15:08:12 +00003566
Steve Naroff621edce2009-04-29 16:37:50 +00003567 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003568 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3569 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003570 if (NumMethods > 0) {
3571 /* struct _objc_protocol_method_list {
3572 int protocol_method_count;
3573 struct protocol_methods protocols[];
3574 }
3575 */
3576 Result += "\nstatic struct {\n";
3577 Result += "\tint protocol_method_count;\n";
3578 Result += "\tstruct _protocol_methods protocol_methods[";
3579 Result += utostr(NumMethods);
3580 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3581 Result += PDecl->getNameAsString();
3582 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3583 "{\n\t";
3584 Result += utostr(NumMethods);
3585 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003586
Steve Naroff621edce2009-04-29 16:37:50 +00003587 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003588 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003589 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003590 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003591 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003592 Result += "\t ,{{(struct objc_selector *)\"";
3593 else
3594 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003595 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003596 std::string MethodTypeString;
3597 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3598 Result += "\", \"";
3599 Result += MethodTypeString;
3600 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003601 }
Steve Naroff621edce2009-04-29 16:37:50 +00003602 Result += "\t }\n};\n";
3603 }
3604
3605 // Output:
3606 /* struct _objc_protocol {
3607 // Objective-C 1.0 extensions
3608 struct _objc_protocol_extension *isa;
3609 char *protocol_name;
3610 struct _objc_protocol **protocol_list;
3611 struct _objc_protocol_method_list *instance_methods;
3612 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003613 };
Steve Naroff621edce2009-04-29 16:37:50 +00003614 */
3615 static bool objc_protocol = false;
3616 if (!objc_protocol) {
3617 Result += "\nstruct _objc_protocol {\n";
3618 Result += "\tstruct _objc_protocol_extension *isa;\n";
3619 Result += "\tchar *protocol_name;\n";
3620 Result += "\tstruct _objc_protocol **protocol_list;\n";
3621 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3622 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003623 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003624
Steve Naroff621edce2009-04-29 16:37:50 +00003625 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003626 }
Mike Stump1eb44332009-09-09 15:08:12 +00003627
Steve Naroff621edce2009-04-29 16:37:50 +00003628 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3629 Result += PDecl->getNameAsString();
3630 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3631 "{\n\t0, \"";
3632 Result += PDecl->getNameAsString();
3633 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003634 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003635 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3636 Result += PDecl->getNameAsString();
3637 Result += ", ";
3638 }
3639 else
3640 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003641 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003642 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3643 Result += PDecl->getNameAsString();
3644 Result += "\n";
3645 }
3646 else
3647 Result += "0\n";
3648 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003649
Steve Naroff621edce2009-04-29 16:37:50 +00003650 // Mark this protocol as having been generated.
3651 if (!ObjCSynthesizedProtocols.insert(PDecl))
3652 assert(false && "protocol already synthesized");
3653
3654}
3655
3656void RewriteObjC::
3657RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003658 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003659 std::string &Result) {
3660 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003661
Steve Naroff621edce2009-04-29 16:37:50 +00003662 for (unsigned i = 0; i != Protocols.size(); i++)
3663 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3664
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003665 // Output the top lovel protocol meta-data for the class.
3666 /* struct _objc_protocol_list {
3667 struct _objc_protocol_list *next;
3668 int protocol_count;
3669 struct _objc_protocol *class_protocols[];
3670 }
3671 */
3672 Result += "\nstatic struct {\n";
3673 Result += "\tstruct _objc_protocol_list *next;\n";
3674 Result += "\tint protocol_count;\n";
3675 Result += "\tstruct _objc_protocol *class_protocols[";
3676 Result += utostr(Protocols.size());
3677 Result += "];\n} _OBJC_";
3678 Result += prefix;
3679 Result += "_PROTOCOLS_";
3680 Result += ClassName;
3681 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3682 "{\n\t0, ";
3683 Result += utostr(Protocols.size());
3684 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003685
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003686 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003687 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003688 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003689
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003690 for (unsigned i = 1; i != Protocols.size(); i++) {
3691 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003692 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003693 Result += "\n";
3694 }
3695 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003696}
3697
Steve Naroff621edce2009-04-29 16:37:50 +00003698
Mike Stump1eb44332009-09-09 15:08:12 +00003699/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003700/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003701void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003702 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003703 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003704 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003705 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003706 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003707 CDecl = CDecl->getNextClassCategory())
3708 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3709 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003710
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003711 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003712 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003713 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003714
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003715 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003716 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003717 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003718
3719 // If any of our property implementations have associated getters or
3720 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003721 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3722 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003723 Prop != PropEnd; ++Prop) {
3724 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3725 continue;
3726 if (!(*Prop)->getPropertyIvarDecl())
3727 continue;
3728 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3729 if (!PD)
3730 continue;
3731 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3732 InstanceMethods.push_back(Getter);
3733 if (PD->isReadOnly())
3734 continue;
3735 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3736 InstanceMethods.push_back(Setter);
3737 }
3738 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003739 true, "CATEGORY_", FullCategoryName.c_str(),
3740 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003741
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003742 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003743 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003744 false, "CATEGORY_", FullCategoryName.c_str(),
3745 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003747 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003748 // Null CDecl is case of a category implementation with no category interface
3749 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003750 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003751 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003752 /* struct _objc_category {
3753 char *category_name;
3754 char *class_name;
3755 struct _objc_method_list *instance_methods;
3756 struct _objc_method_list *class_methods;
3757 struct _objc_protocol_list *protocols;
3758 // Objective-C 1.0 extensions
3759 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003760 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003761 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003762 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003763 */
Mike Stump1eb44332009-09-09 15:08:12 +00003764
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003765 static bool objc_category = false;
3766 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003767 Result += "\nstruct _objc_category {\n";
3768 Result += "\tchar *category_name;\n";
3769 Result += "\tchar *class_name;\n";
3770 Result += "\tstruct _objc_method_list *instance_methods;\n";
3771 Result += "\tstruct _objc_method_list *class_methods;\n";
3772 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003773 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003774 Result += "\tstruct _objc_property_list *instance_properties;\n";
3775 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003776 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003777 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003778 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3779 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003780 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003781 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003782 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003783 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003784 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003785
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003786 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003787 Result += "\t, (struct _objc_method_list *)"
3788 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3789 Result += FullCategoryName;
3790 Result += "\n";
3791 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003792 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003793 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003794 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003795 Result += "\t, (struct _objc_method_list *)"
3796 "&_OBJC_CATEGORY_CLASS_METHODS_";
3797 Result += FullCategoryName;
3798 Result += "\n";
3799 }
3800 else
3801 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003802
Chris Lattnercafeb352009-02-20 18:18:36 +00003803 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003804 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003805 Result += FullCategoryName;
3806 Result += "\n";
3807 }
3808 else
3809 Result += "\t, 0\n";
3810 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003811}
3812
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003813/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3814/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003815void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003816 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003817 if (ivar->isBitField()) {
3818 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3819 // place all bitfields at offset 0.
3820 Result += "0";
3821 } else {
3822 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003823 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003824 if (LangOpts.Microsoft)
3825 Result += "_IMPL";
3826 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003827 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003828 Result += ")";
3829 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003830}
3831
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003832//===----------------------------------------------------------------------===//
3833// Meta Data Emission
3834//===----------------------------------------------------------------------===//
3835
Steve Naroffb29b4272008-04-14 22:03:09 +00003836void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003837 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003838 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003839
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003840 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003841 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003842 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003843 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003844 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003845 }
Mike Stump1eb44332009-09-09 15:08:12 +00003846
Chris Lattnerbe6df082007-12-12 07:56:42 +00003847 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003848 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003849 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003850 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003851 if (NumIvars > 0) {
3852 static bool objc_ivar = false;
3853 if (!objc_ivar) {
3854 /* struct _objc_ivar {
3855 char *ivar_name;
3856 char *ivar_type;
3857 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003858 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003859 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003860 Result += "\nstruct _objc_ivar {\n";
3861 Result += "\tchar *ivar_name;\n";
3862 Result += "\tchar *ivar_type;\n";
3863 Result += "\tint ivar_offset;\n";
3864 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003865
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003866 objc_ivar = true;
3867 }
3868
Steve Naroff946a6932008-03-11 00:12:29 +00003869 /* struct {
3870 int ivar_count;
3871 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003872 };
Steve Naroff946a6932008-03-11 00:12:29 +00003873 */
Mike Stump1eb44332009-09-09 15:08:12 +00003874 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003875 Result += "\tint ivar_count;\n";
3876 Result += "\tstruct _objc_ivar ivar_list[";
3877 Result += utostr(NumIvars);
3878 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003879 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003880 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003881 "{\n\t";
3882 Result += utostr(NumIvars);
3883 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003884
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003885 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003886 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003887 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003888 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003889 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003890 IV != IVEnd; ++IV)
3891 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003892 IVI = IDecl->ivar_begin();
3893 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003894 } else {
3895 IVI = CDecl->ivar_begin();
3896 IVE = CDecl->ivar_end();
3897 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003898 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003899 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003900 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003901 std::string TmpString, StrEncoding;
3902 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3903 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003904 Result += StrEncoding;
3905 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003906 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003907 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003908 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003909 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003910 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003911 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003912 std::string TmpString, StrEncoding;
3913 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3914 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003915 Result += StrEncoding;
3916 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003917 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003918 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 }
Mike Stump1eb44332009-09-09 15:08:12 +00003920
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003921 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003922 }
Mike Stump1eb44332009-09-09 15:08:12 +00003923
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003924 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003925 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003926 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003927
3928 // If any of our property implementations have associated getters or
3929 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003930 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3931 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003932 Prop != PropEnd; ++Prop) {
3933 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3934 continue;
3935 if (!(*Prop)->getPropertyIvarDecl())
3936 continue;
3937 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3938 if (!PD)
3939 continue;
3940 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003941 if (!Getter->isDefined())
3942 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003943 if (PD->isReadOnly())
3944 continue;
3945 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003946 if (!Setter->isDefined())
3947 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003948 }
3949 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003950 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003951
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003952 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003953 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003954 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003955
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003956 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003957 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003958 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003959
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003960 // Declaration of class/meta-class metadata
3961 /* struct _objc_class {
3962 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003963 const char *super_class_name;
3964 char *name;
3965 long version;
3966 long info;
3967 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003968 struct _objc_ivar_list *ivars;
3969 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003970 struct objc_cache *cache;
3971 struct objc_protocol_list *protocols;
3972 const char *ivar_layout;
3973 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003974 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003975 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003976 static bool objc_class = false;
3977 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003978 Result += "\nstruct _objc_class {\n";
3979 Result += "\tstruct _objc_class *isa;\n";
3980 Result += "\tconst char *super_class_name;\n";
3981 Result += "\tchar *name;\n";
3982 Result += "\tlong version;\n";
3983 Result += "\tlong info;\n";
3984 Result += "\tlong instance_size;\n";
3985 Result += "\tstruct _objc_ivar_list *ivars;\n";
3986 Result += "\tstruct _objc_method_list *methods;\n";
3987 Result += "\tstruct objc_cache *cache;\n";
3988 Result += "\tstruct _objc_protocol_list *protocols;\n";
3989 Result += "\tconst char *ivar_layout;\n";
3990 Result += "\tstruct _objc_class_ext *ext;\n";
3991 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003992 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003993 }
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003995 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003996 ObjCInterfaceDecl *RootClass = 0;
3997 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003998 while (SuperClass) {
3999 RootClass = SuperClass;
4000 SuperClass = SuperClass->getSuperClass();
4001 }
4002 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00004003
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004004 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004005 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004006 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004007 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004008 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004009 Result += "\"";
4010
4011 if (SuperClass) {
4012 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004013 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004015 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004016 Result += "\"";
4017 }
4018 else {
4019 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004020 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004021 Result += "\"";
4022 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004023 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004024 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004025 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004026 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004027 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004028 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004029 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004030 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004031 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004032 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004033 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004034 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004035 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004036 Result += ",0,0\n";
4037 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004038 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004039 Result += "\t,0,0,0,0\n";
4040 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004041
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004042 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004043 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004044 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004045 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004046 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004047 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004048 if (SuperClass) {
4049 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004050 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004051 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004052 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004053 Result += "\"";
4054 }
4055 else {
4056 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004057 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 Result += "\"";
4059 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004060 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004061 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004062 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004063 Result += ",0";
4064 else {
4065 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004066 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004067 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004068 if (LangOpts.Microsoft)
4069 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004070 Result += ")";
4071 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004072 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004073 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004074 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004075 Result += "\n\t";
4076 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004077 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004078 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004079 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004080 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004081 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004082 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004083 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004084 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004085 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004086 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004087 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004088 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004089 Result += ", 0,0\n";
4090 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004091 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004092 Result += ",0,0,0\n";
4093 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004094}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004095
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004096/// RewriteImplementations - This routine rewrites all method implementations
4097/// and emits meta-data.
4098
Steve Narofface66252008-11-13 20:07:04 +00004099void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004100 int ClsDefCount = ClassImplementation.size();
4101 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004102
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004103 // Rewrite implemented methods
4104 for (int i = 0; i < ClsDefCount; i++)
4105 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004107 for (int i = 0; i < CatDefCount; i++)
4108 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004109}
Mike Stump1eb44332009-09-09 15:08:12 +00004110
Steve Narofface66252008-11-13 20:07:04 +00004111void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4112 int ClsDefCount = ClassImplementation.size();
4113 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004114
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004115 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004116 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004117 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004118
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004119 // For each implemented category, write out all its meta data.
4120 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004121 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004122
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004123 // Write objc_symtab metadata
4124 /*
4125 struct _objc_symtab
4126 {
4127 long sel_ref_cnt;
4128 SEL *refs;
4129 short cls_def_cnt;
4130 short cat_def_cnt;
4131 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004132 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004133 */
Mike Stump1eb44332009-09-09 15:08:12 +00004134
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004135 Result += "\nstruct _objc_symtab {\n";
4136 Result += "\tlong sel_ref_cnt;\n";
4137 Result += "\tSEL *refs;\n";
4138 Result += "\tshort cls_def_cnt;\n";
4139 Result += "\tshort cat_def_cnt;\n";
4140 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4141 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004142
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004143 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004144 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004145 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004146 + ", " + utostr(CatDefCount) + "\n";
4147 for (int i = 0; i < ClsDefCount; i++) {
4148 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004149 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004150 Result += "\n";
4151 }
Mike Stump1eb44332009-09-09 15:08:12 +00004152
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004153 for (int i = 0; i < CatDefCount; i++) {
4154 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004155 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004156 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004157 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004158 Result += "\n";
4159 }
Mike Stump1eb44332009-09-09 15:08:12 +00004160
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004161 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004163 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004164
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004165 /*
4166 struct _objc_module {
4167 long version;
4168 long size;
4169 const char *name;
4170 struct _objc_symtab *symtab;
4171 }
4172 */
Mike Stump1eb44332009-09-09 15:08:12 +00004173
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004174 Result += "\nstruct _objc_module {\n";
4175 Result += "\tlong version;\n";
4176 Result += "\tlong size;\n";
4177 Result += "\tconst char *name;\n";
4178 Result += "\tstruct _objc_symtab *symtab;\n";
4179 Result += "};\n\n";
4180 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004181 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004182 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004183 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004184 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004185
4186 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004187 if (ProtocolExprDecls.size()) {
4188 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4189 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004190 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004191 E = ProtocolExprDecls.end(); I != E; ++I) {
4192 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4193 Result += (*I)->getNameAsString();
4194 Result += " = &_OBJC_PROTOCOL_";
4195 Result += (*I)->getNameAsString();
4196 Result += ";\n";
4197 }
4198 Result += "#pragma data_seg(pop)\n\n";
4199 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004200 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004201 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004202 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4203 Result += "&_OBJC_MODULES;\n";
4204 Result += "#pragma data_seg(pop)\n\n";
4205 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004206}
Chris Lattner311ff022007-10-16 22:36:42 +00004207
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004208void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4209 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004210 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004211 assert(BlockByRefDeclNo.count(VD) &&
4212 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004213 if (def)
4214 ResultStr += "struct ";
4215 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004216 "_" + utostr(BlockByRefDeclNo[VD]) ;
4217}
4218
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004219static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4220 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4221 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4222 return false;
4223}
4224
Steve Naroff54055232008-10-27 17:20:55 +00004225std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004226 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004227 std::string Tag) {
4228 const FunctionType *AFT = CE->getFunctionType();
4229 QualType RT = AFT->getResultType();
4230 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004231 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004232 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004233
Steve Naroff54055232008-10-27 17:20:55 +00004234 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004235
Douglas Gregor72564e72009-02-26 23:50:07 +00004236 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004237 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004238 // block (to reference imported block decl refs).
4239 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004240 } else if (BD->param_empty()) {
4241 S += "(" + StructRef + " *__cself)";
4242 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004243 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004244 assert(FT && "SynthesizeBlockFunc: No function proto");
4245 S += '(';
4246 // first add the implicit argument.
4247 S += StructRef + " *__cself, ";
4248 std::string ParamStr;
4249 for (BlockDecl::param_iterator AI = BD->param_begin(),
4250 E = BD->param_end(); AI != E; ++AI) {
4251 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004252 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004253 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004254 if (convertBlockPointerToFunctionPointer(QT))
4255 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004256 else
4257 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004258 S += ParamStr;
4259 }
4260 if (FT->isVariadic()) {
4261 if (!BD->param_empty()) S += ", ";
4262 S += "...";
4263 }
4264 S += ')';
4265 }
4266 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004267
Steve Naroff54055232008-10-27 17:20:55 +00004268 // Create local declarations to avoid rewriting all closure decl ref exprs.
4269 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004270 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004271 E = BlockByRefDecls.end(); I != E; ++I) {
4272 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004273 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004274 std::string TypeString;
4275 RewriteByRefString(TypeString, Name, (*I));
4276 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004277 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004278 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004279 }
Steve Naroff54055232008-10-27 17:20:55 +00004280 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004281 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004282 E = BlockByCopyDecls.end(); I != E; ++I) {
4283 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004284 // Handle nested closure invocation. For example:
4285 //
4286 // void (^myImportedClosure)(void);
4287 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004288 //
Steve Naroff54055232008-10-27 17:20:55 +00004289 // void (^anotherClosure)(void);
4290 // anotherClosure = ^(void) {
4291 // myImportedClosure(); // import and invoke the closure
4292 // };
4293 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004294 if (isTopLevelBlockPointerType((*I)->getType())) {
4295 RewriteBlockPointerTypeVariable(S, (*I));
4296 S += " = (";
4297 RewriteBlockPointerType(S, (*I)->getType());
4298 S += ")";
4299 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4300 }
4301 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004302 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004303 QualType QT = (*I)->getType();
4304 if (HasLocalVariableExternalStorage(*I))
4305 QT = Context->getPointerType(QT);
4306 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004307 S += Name + " = __cself->" +
4308 (*I)->getNameAsString() + "; // bound by copy\n";
4309 }
Steve Naroff54055232008-10-27 17:20:55 +00004310 }
4311 std::string RewrittenStr = RewrittenBlockExprs[CE];
4312 const char *cstr = RewrittenStr.c_str();
4313 while (*cstr++ != '{') ;
4314 S += cstr;
4315 S += "\n";
4316 return S;
4317}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004318
Steve Naroff54055232008-10-27 17:20:55 +00004319std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004320 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004321 std::string Tag) {
4322 std::string StructRef = "struct " + Tag;
4323 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004324
Steve Naroff54055232008-10-27 17:20:55 +00004325 S += funcName;
4326 S += "_block_copy_" + utostr(i);
4327 S += "(" + StructRef;
4328 S += "*dst, " + StructRef;
4329 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004330 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004331 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004332 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004333 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004334 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004335 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004336 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004337 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004338 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004339 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004340 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004341 else
4342 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004343 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004344 S += "}\n";
4345
Steve Naroff54055232008-10-27 17:20:55 +00004346 S += "\nstatic void __";
4347 S += funcName;
4348 S += "_block_dispose_" + utostr(i);
4349 S += "(" + StructRef;
4350 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004351 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004352 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004353 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004354 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004355 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004356 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004357 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004358 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004359 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004360 else
4361 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004362 }
Mike Stump1eb44332009-09-09 15:08:12 +00004363 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004364 return S;
4365}
4366
Steve Naroff01aec112009-12-06 21:14:13 +00004367std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4368 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004369 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004370 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004371
Steve Naroff54055232008-10-27 17:20:55 +00004372 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004373 S += " struct " + Desc;
4374 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004375
Steve Naroff01aec112009-12-06 21:14:13 +00004376 Constructor += "(void *fp, "; // Invoke function pointer.
4377 Constructor += "struct " + Desc; // Descriptor pointer.
4378 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004379
Steve Naroff54055232008-10-27 17:20:55 +00004380 if (BlockDeclRefs.size()) {
4381 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004382 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004383 E = BlockByCopyDecls.end(); I != E; ++I) {
4384 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004385 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004386 std::string ArgName = "_" + FieldName;
4387 // Handle nested closure invocation. For example:
4388 //
4389 // void (^myImportedBlock)(void);
4390 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004391 //
Steve Naroff54055232008-10-27 17:20:55 +00004392 // void (^anotherBlock)(void);
4393 // anotherBlock = ^(void) {
4394 // myImportedBlock(); // import and invoke the closure
4395 // };
4396 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004397 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004398 S += "struct __block_impl *";
4399 Constructor += ", void *" + ArgName;
4400 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004401 QualType QT = (*I)->getType();
4402 if (HasLocalVariableExternalStorage(*I))
4403 QT = Context->getPointerType(QT);
4404 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4405 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004406 Constructor += ", " + ArgName;
4407 }
4408 S += FieldName + ";\n";
4409 }
4410 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004411 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004412 E = BlockByRefDecls.end(); I != E; ++I) {
4413 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004414 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004415 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004416 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004417 std::string TypeString;
4418 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004419 TypeString += " *";
4420 FieldName = TypeString + FieldName;
4421 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004422 Constructor += ", " + ArgName;
4423 }
4424 S += FieldName + "; // by ref\n";
4425 }
4426 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004427 Constructor += ", int flags=0)";
4428 // Initialize all "by copy" arguments.
4429 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004430 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004431 E = BlockByCopyDecls.end(); I != E; ++I) {
4432 std::string Name = (*I)->getNameAsString();
4433 if (firsTime) {
4434 Constructor += " : ";
4435 firsTime = false;
4436 }
4437 else
4438 Constructor += ", ";
4439 if (isTopLevelBlockPointerType((*I)->getType()))
4440 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4441 else
4442 Constructor += Name + "(_" + Name + ")";
4443 }
4444 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004445 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004446 E = BlockByRefDecls.end(); I != E; ++I) {
4447 std::string Name = (*I)->getNameAsString();
4448 if (firsTime) {
4449 Constructor += " : ";
4450 firsTime = false;
4451 }
4452 else
4453 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004454 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004455 }
4456
4457 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004458 if (GlobalVarDecl)
4459 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4460 else
4461 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004462 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004463
Steve Naroff01aec112009-12-06 21:14:13 +00004464 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004465 } else {
4466 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004467 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004468 if (GlobalVarDecl)
4469 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4470 else
4471 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004472 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4473 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004474 }
4475 Constructor += " ";
4476 Constructor += "}\n";
4477 S += Constructor;
4478 S += "};\n";
4479 return S;
4480}
4481
Steve Naroff01aec112009-12-06 21:14:13 +00004482std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4483 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004484 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004485 unsigned hasCopy) {
4486 std::string S = "\nstatic struct " + DescTag;
4487
4488 S += " {\n unsigned long reserved;\n";
4489 S += " unsigned long Block_size;\n";
4490 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004491 S += " void (*copy)(struct ";
4492 S += ImplTag; S += "*, struct ";
4493 S += ImplTag; S += "*);\n";
4494
4495 S += " void (*dispose)(struct ";
4496 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004497 }
4498 S += "} ";
4499
4500 S += DescTag + "_DATA = { 0, sizeof(struct ";
4501 S += ImplTag + ")";
4502 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004503 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4504 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004505 }
4506 S += "};\n";
4507 return S;
4508}
4509
Steve Naroff54055232008-10-27 17:20:55 +00004510void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004511 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004512 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004513 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004514 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004515 bool RewriteSC = (GlobalVarDecl &&
4516 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004517 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004518 GlobalVarDecl->getType().getCVRQualifiers());
4519 if (RewriteSC) {
4520 std::string SC(" void __");
4521 SC += GlobalVarDecl->getNameAsString();
4522 SC += "() {}";
4523 InsertText(FunLocStart, SC);
4524 }
4525
Steve Naroff54055232008-10-27 17:20:55 +00004526 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004527 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4528 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004529 // Need to copy-in the inner copied-in variables not actually used in this
4530 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004531 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4532 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4533 ValueDecl *VD = Exp->getDecl();
4534 BlockDeclRefs.push_back(Exp);
4535 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4536 BlockByCopyDeclsPtrSet.insert(VD);
4537 BlockByCopyDecls.push_back(VD);
4538 }
4539 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4540 BlockByRefDeclsPtrSet.insert(VD);
4541 BlockByRefDecls.push_back(VD);
4542 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004543 // imported objects in the inner blocks not used in the outer
4544 // blocks must be copied/disposed in the outer block as well.
4545 if (Exp->isByRef() ||
4546 VD->getType()->isObjCObjectPointerType() ||
4547 VD->getType()->isBlockPointerType())
4548 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004549 }
Steve Naroff54055232008-10-27 17:20:55 +00004550
Daniel Dunbar4087f272010-08-17 22:39:59 +00004551 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4552 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004553
Steve Naroff01aec112009-12-06 21:14:13 +00004554 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004555
Benjamin Kramerd999b372010-02-14 14:14:16 +00004556 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004557
Steve Naroff01aec112009-12-06 21:14:13 +00004558 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004559
Benjamin Kramerd999b372010-02-14 14:14:16 +00004560 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004561
4562 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004563 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004564 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004565 }
Steve Naroff01aec112009-12-06 21:14:13 +00004566 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4567 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004568 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004569
Steve Naroff54055232008-10-27 17:20:55 +00004570 BlockDeclRefs.clear();
4571 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004572 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004573 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004574 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004575 ImportedBlockDecls.clear();
4576 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004577 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004578 // Must insert any 'const/volatile/static here. Since it has been
4579 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004580 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004581 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004582 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004583 if (GlobalVarDecl->getType().isConstQualified())
4584 SC += "const ";
4585 if (GlobalVarDecl->getType().isVolatileQualified())
4586 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004587 if (GlobalVarDecl->getType().isRestrictQualified())
4588 SC += "restrict ";
4589 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004590 }
4591
Steve Naroff54055232008-10-27 17:20:55 +00004592 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004593 InnerDeclRefsCount.clear();
4594 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004595 RewrittenBlockExprs.clear();
4596}
4597
4598void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4599 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004600 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004601
Steve Naroff54055232008-10-27 17:20:55 +00004602 SynthesizeBlockLiterals(FunLocStart, FuncName);
4603}
4604
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004605static void BuildUniqueMethodName(std::string &Name,
4606 ObjCMethodDecl *MD) {
4607 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004608 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004609 Name += "__" + MD->getSelector().getAsString();
4610 // Convert colons to underscores.
4611 std::string::size_type loc = 0;
4612 while ((loc = Name.find(":", loc)) != std::string::npos)
4613 Name.replace(loc, 1, "_");
4614}
4615
Steve Naroff54055232008-10-27 17:20:55 +00004616void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004617 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4618 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004619 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004620 std::string FuncName;
4621 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004622 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004623}
4624
4625void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004626 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004627 if (*CI) {
4628 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4629 GetBlockDeclRefExprs(CBE->getBody());
4630 else
4631 GetBlockDeclRefExprs(*CI);
4632 }
4633 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004634 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004635 // FIXME: Handle enums.
4636 if (!isa<FunctionDecl>(CDRE->getDecl()))
4637 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004638 }
4639 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4640 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4641 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004642 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4643 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004644 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004645 BlockDeclRefs.push_back(BDRE);
4646 }
4647
Steve Naroff54055232008-10-27 17:20:55 +00004648 return;
4649}
4650
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004651void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004652 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004653 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004654 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004655 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004656 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4657 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004658 GetInnerBlockDeclRefExprs(CBE->getBody(),
4659 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004660 InnerContexts);
4661 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004662 else
4663 GetInnerBlockDeclRefExprs(*CI,
4664 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004665 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004666
4667 }
4668 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004669 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004670 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004671 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004672 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004673 }
4674 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4675 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4676 if (Var->isFunctionOrMethodVarDecl())
4677 ImportedLocalExternalDecls.insert(Var);
4678 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004679
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004680 return;
4681}
4682
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004683/// convertFunctionTypeOfBlocks - This routine converts a function type
4684/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004685/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004686/// all block pointers to function pointers.
4687QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4688 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4689 // FTP will be null for closures that don't take arguments.
4690 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004691 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004692 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004693 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004694
4695 if (FTP) {
4696 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4697 E = FTP->arg_type_end(); I && (I != E); ++I) {
4698 QualType t = *I;
4699 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004700 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004701 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004702 ArgTypes.push_back(t);
4703 }
4704 }
4705 QualType FuncType;
4706 // FIXME. Does this work if block takes no argument but has a return type
4707 // which is of block type?
4708 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004709 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004710 else FuncType = QualType(FT, 0);
4711 return FuncType;
4712}
4713
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004714Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004715 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004716 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004718 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004719 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004720 } else if (const BlockDeclRefExpr *CDRE =
4721 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004722 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004723 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004724 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004725 }
4726 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4727 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4728 }
4729 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4730 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4731 else if (const ConditionalOperator *CEXPR =
4732 dyn_cast<ConditionalOperator>(BlockExp)) {
4733 Expr *LHSExp = CEXPR->getLHS();
4734 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4735 Expr *RHSExp = CEXPR->getRHS();
4736 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4737 Expr *CONDExp = CEXPR->getCond();
4738 ConditionalOperator *CondExpr =
4739 new (Context) ConditionalOperator(CONDExp,
4740 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004741 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004742 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004743 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004744 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4745 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004746 } else {
4747 assert(1 && "RewriteBlockClass: Bad type");
4748 }
4749 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004750 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004751 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004752 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004753 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004754
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004755 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004756 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004757 &Context->Idents.get("__block_impl"));
4758 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004759
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004760 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004761 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004762
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004763 // Push the block argument type.
4764 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004765 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004766 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004767 E = FTP->arg_type_end(); I && (I != E); ++I) {
4768 QualType t = *I;
4769 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004770 if (!convertBlockPointerToFunctionPointer(t))
4771 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004772 ArgTypes.push_back(t);
4773 }
Steve Naroff54055232008-10-27 17:20:55 +00004774 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004775 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004776 QualType PtrToFuncCastType
4777 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004778
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004779 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004780
John McCall9d125032010-01-15 18:39:57 +00004781 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004782 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004783 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004784 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004785 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4786 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004787 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004788
Douglas Gregor44b43212008-12-11 16:49:14 +00004789 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004790 SourceLocation(),
4791 &Context->Idents.get("FuncPtr"),
4792 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004793 /*BitWidth=*/0, /*Mutable=*/true,
4794 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004795 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004796 FD->getType(), VK_LValue,
4797 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004799
John McCall9d125032010-01-15 18:39:57 +00004800 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004801 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004802 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004803
Chris Lattner5f9e2722011-07-23 10:55:15 +00004804 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004805 // Add the implicit argument.
4806 BlkExprs.push_back(BlkCast);
4807 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004808 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004809 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004810 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004811 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004812 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4813 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004814 Exp->getType(), VK_RValue,
4815 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004816 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004817}
4818
Steve Naroff621edce2009-04-29 16:37:50 +00004819// We need to return the rewritten expression to handle cases where the
4820// BlockDeclRefExpr is embedded in another expression being rewritten.
4821// For example:
4822//
4823// int main() {
4824// __block Foo *f;
4825// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004826//
Steve Naroff621edce2009-04-29 16:37:50 +00004827// void (^myblock)() = ^() {
4828// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4829// i = 77;
4830// };
4831//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004832Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004833 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004834 // for each DeclRefExp where BYREFVAR is name of the variable.
4835 ValueDecl *VD;
4836 bool isArrow = true;
4837 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4838 VD = BDRE->getDecl();
4839 else {
4840 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4841 isArrow = false;
4842 }
4843
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004844 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004845 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004846 &Context->Idents.get("__forwarding"),
4847 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004848 /*BitWidth=*/0, /*Mutable=*/true,
4849 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004850 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4851 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004852 FD->getType(), VK_LValue,
4853 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004854
Chris Lattner5f9e2722011-07-23 10:55:15 +00004855 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004856 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004857 &Context->Idents.get(Name),
4858 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004859 /*BitWidth=*/0, /*Mutable=*/true,
4860 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004861 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004862 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004863
4864
4865
Steve Naroffdf8570d2009-02-02 17:19:26 +00004866 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004867 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4868 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004869 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004870 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004871 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004872}
4873
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004874// Rewrites the imported local variable V with external storage
4875// (static, extern, etc.) as *V
4876//
4877Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4878 ValueDecl *VD = DRE->getDecl();
4879 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4880 if (!ImportedLocalExternalDecls.count(Var))
4881 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004882 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4883 VK_LValue, OK_Ordinary,
4884 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004885 // Need parens to enforce precedence.
4886 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4887 Exp);
4888 ReplaceStmt(DRE, PE);
4889 return PE;
4890}
4891
Steve Naroffb2f9e512008-11-03 23:29:32 +00004892void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4893 SourceLocation LocStart = CE->getLParenLoc();
4894 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004895
4896 // Need to avoid trying to rewrite synthesized casts.
4897 if (LocStart.isInvalid())
4898 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004899 // Need to avoid trying to rewrite casts contained in macros.
4900 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4901 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004902
Steve Naroff54055232008-10-27 17:20:55 +00004903 const char *startBuf = SM->getCharacterData(LocStart);
4904 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004905 QualType QT = CE->getType();
4906 const Type* TypePtr = QT->getAs<Type>();
4907 if (isa<TypeOfExprType>(TypePtr)) {
4908 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4909 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4910 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004911 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004912 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004913 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004914 return;
4915 }
Steve Naroff54055232008-10-27 17:20:55 +00004916 // advance the location to startArgList.
4917 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004918
Steve Naroff54055232008-10-27 17:20:55 +00004919 while (*argPtr++ && (argPtr < endBuf)) {
4920 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004921 case '^':
4922 // Replace the '^' with '*'.
4923 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004924 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004925 break;
Steve Naroff54055232008-10-27 17:20:55 +00004926 }
4927 }
4928 return;
4929}
4930
4931void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4932 SourceLocation DeclLoc = FD->getLocation();
4933 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004934
Steve Naroff54055232008-10-27 17:20:55 +00004935 // We have 1 or more arguments that have closure pointers.
4936 const char *startBuf = SM->getCharacterData(DeclLoc);
4937 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004938
Steve Naroff54055232008-10-27 17:20:55 +00004939 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004940
Steve Naroff54055232008-10-27 17:20:55 +00004941 parenCount++;
4942 // advance the location to startArgList.
4943 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4944 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004945
Steve Naroff54055232008-10-27 17:20:55 +00004946 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004947
Steve Naroff54055232008-10-27 17:20:55 +00004948 while (*argPtr++ && parenCount) {
4949 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004950 case '^':
4951 // Replace the '^' with '*'.
4952 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004953 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004954 break;
4955 case '(':
4956 parenCount++;
4957 break;
4958 case ')':
4959 parenCount--;
4960 break;
Steve Naroff54055232008-10-27 17:20:55 +00004961 }
4962 }
4963 return;
4964}
4965
4966bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004967 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004968 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004969 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004970 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004971 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004972 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004973 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004974 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004975 }
4976 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004977 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004978 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004979 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004980 return true;
4981 }
4982 return false;
4983}
4984
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004985bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4986 const FunctionProtoType *FTP;
4987 const PointerType *PT = QT->getAs<PointerType>();
4988 if (PT) {
4989 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4990 } else {
4991 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4992 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4993 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4994 }
4995 if (FTP) {
4996 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004997 E = FTP->arg_type_end(); I != E; ++I) {
4998 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004999 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005000 if ((*I)->isObjCObjectPointerType() &&
5001 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5002 return true;
5003 }
5004
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005005 }
5006 return false;
5007}
5008
Ted Kremenek8189cde2009-02-07 01:47:29 +00005009void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5010 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00005011 const char *argPtr = strchr(Name, '(');
5012 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00005013
Steve Naroff54055232008-10-27 17:20:55 +00005014 LParen = argPtr; // output the start.
5015 argPtr++; // skip past the left paren.
5016 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005017
Steve Naroff54055232008-10-27 17:20:55 +00005018 while (*argPtr && parenCount) {
5019 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005020 case '(': parenCount++; break;
5021 case ')': parenCount--; break;
5022 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005023 }
5024 if (parenCount) argPtr++;
5025 }
5026 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5027 RParen = argPtr; // output the end
5028}
5029
5030void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5031 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5032 RewriteBlockPointerFunctionArgs(FD);
5033 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005034 }
Steve Naroff54055232008-10-27 17:20:55 +00005035 // Handle Variables and Typedefs.
5036 SourceLocation DeclLoc = ND->getLocation();
5037 QualType DeclT;
5038 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5039 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005040 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005041 DeclT = TDD->getUnderlyingType();
5042 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5043 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005044 else
Steve Naroff54055232008-10-27 17:20:55 +00005045 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005046
Steve Naroff54055232008-10-27 17:20:55 +00005047 const char *startBuf = SM->getCharacterData(DeclLoc);
5048 const char *endBuf = startBuf;
5049 // scan backward (from the decl location) for the end of the previous decl.
5050 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5051 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005052 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
5053 std::string buf;
5054 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005055 // *startBuf != '^' if we are dealing with a pointer to function that
5056 // may take block argument types (which will be handled below).
5057 if (*startBuf == '^') {
5058 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005059 buf = '*';
5060 startBuf++;
5061 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005062 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005063 while (*startBuf != ')') {
5064 buf += *startBuf;
5065 startBuf++;
5066 OrigLength++;
5067 }
5068 buf += ')';
5069 OrigLength++;
5070
5071 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5072 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005073 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005074 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005075 DeclLoc = ND->getLocation();
5076 startBuf = SM->getCharacterData(DeclLoc);
5077 const char *argListBegin, *argListEnd;
5078 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5079 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005080 if (*argListBegin == '^')
5081 buf += '*';
5082 else if (*argListBegin == '<') {
5083 buf += "/*";
5084 buf += *argListBegin++;
5085 OrigLength++;;
5086 while (*argListBegin != '>') {
5087 buf += *argListBegin++;
5088 OrigLength++;
5089 }
5090 buf += *argListBegin;
5091 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005092 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005093 else
5094 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005095 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005096 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005097 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005098 buf += ')';
5099 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005100 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005101 ReplaceText(Start, OrigLength, buf);
5102
Steve Naroff54055232008-10-27 17:20:55 +00005103 return;
5104}
5105
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005106
5107/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5108/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5109/// struct Block_byref_id_object *src) {
5110/// _Block_object_assign (&_dest->object, _src->object,
5111/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5112/// [|BLOCK_FIELD_IS_WEAK]) // object
5113/// _Block_object_assign(&_dest->object, _src->object,
5114/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5115/// [|BLOCK_FIELD_IS_WEAK]) // block
5116/// }
5117/// And:
5118/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5119/// _Block_object_dispose(_src->object,
5120/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5121/// [|BLOCK_FIELD_IS_WEAK]) // object
5122/// _Block_object_dispose(_src->object,
5123/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5124/// [|BLOCK_FIELD_IS_WEAK]) // block
5125/// }
5126
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005127std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5128 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005129 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005130 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005131 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005132 CopyDestroyCache.insert(flag);
5133 S = "static void __Block_byref_id_object_copy_";
5134 S += utostr(flag);
5135 S += "(void *dst, void *src) {\n";
5136
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005137 // offset into the object pointer is computed as:
5138 // void * + void* + int + int + void* + void *
5139 unsigned IntSize =
5140 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5141 unsigned VoidPtrSize =
5142 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5143
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005144 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005145 S += " _Block_object_assign((char*)dst + ";
5146 S += utostr(offset);
5147 S += ", *(void * *) ((char*)src + ";
5148 S += utostr(offset);
5149 S += "), ";
5150 S += utostr(flag);
5151 S += ");\n}\n";
5152
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005153 S += "static void __Block_byref_id_object_dispose_";
5154 S += utostr(flag);
5155 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005156 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5157 S += utostr(offset);
5158 S += "), ";
5159 S += utostr(flag);
5160 S += ");\n}\n";
5161 return S;
5162}
5163
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005164/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5165/// the declaration into:
5166/// struct __Block_byref_ND {
5167/// void *__isa; // NULL for everything except __weak pointers
5168/// struct __Block_byref_ND *__forwarding;
5169/// int32_t __flags;
5170/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005171/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5172/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005173/// typex ND;
5174/// };
5175///
5176/// It then replaces declaration of ND variable with:
5177/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5178/// __size=sizeof(struct __Block_byref_ND),
5179/// ND=initializer-if-any};
5180///
5181///
5182void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005183 // Insert declaration for the function in which block literal is
5184 // used.
5185 if (CurFunctionDeclToDeclareForBlock)
5186 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005187 int flag = 0;
5188 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005189 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005190 if (DeclLoc.isInvalid())
5191 // If type location is missing, it is because of missing type (a warning).
5192 // Use variable's location which is good for this case.
5193 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005194 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005195 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005196 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005197 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005198 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005199 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005200 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005201 ByrefType += " {\n";
5202 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005203 RewriteByRefString(ByrefType, Name, ND);
5204 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005205 ByrefType += " int __flags;\n";
5206 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005207 // Add void *__Block_byref_id_object_copy;
5208 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005209 QualType Ty = ND->getType();
5210 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5211 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005212 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5213 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005214 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005215
5216 QualType T = Ty;
5217 (void)convertBlockPointerToFunctionPointer(T);
5218 T.getAsStringInternal(Name, Context->PrintingPolicy);
5219
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005220 ByrefType += " " + Name + ";\n";
5221 ByrefType += "};\n";
5222 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005223 SourceLocation FunLocStart;
5224 if (CurFunctionDef)
5225 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5226 else {
5227 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5228 FunLocStart = CurMethodDef->getLocStart();
5229 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005230 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005231 if (Ty.isObjCGCWeak()) {
5232 flag |= BLOCK_FIELD_IS_WEAK;
5233 isa = 1;
5234 }
5235
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005236 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005237 flag = BLOCK_BYREF_CALLER;
5238 QualType Ty = ND->getType();
5239 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5240 if (Ty->isBlockPointerType())
5241 flag |= BLOCK_FIELD_IS_BLOCK;
5242 else
5243 flag |= BLOCK_FIELD_IS_OBJECT;
5244 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005245 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005246 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005247 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005248
5249 // struct __Block_byref_ND ND =
5250 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5251 // initializer-if-any};
5252 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005253 unsigned flags = 0;
5254 if (HasCopyAndDispose)
5255 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005256 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005257 ByrefType.clear();
5258 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005259 std::string ForwardingCastType("(");
5260 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005261 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005262 ByrefType += " " + Name + " = {(void*)";
5263 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005264 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005265 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005266 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005267 ByrefType += "sizeof(";
5268 RewriteByRefString(ByrefType, Name, ND);
5269 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005270 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005271 ByrefType += ", __Block_byref_id_object_copy_";
5272 ByrefType += utostr(flag);
5273 ByrefType += ", __Block_byref_id_object_dispose_";
5274 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005275 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005276 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005277 unsigned nameSize = Name.size();
5278 // for block or function pointer declaration. Name is aleady
5279 // part of the declaration.
5280 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5281 nameSize = 1;
5282 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005283 }
5284 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005285 SourceLocation startLoc;
5286 Expr *E = ND->getInit();
5287 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5288 startLoc = ECE->getLParenLoc();
5289 else
5290 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005291 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005292 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005293 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005294 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005295 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005296 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005297 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005298 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005299 ByrefType += "sizeof(";
5300 RewriteByRefString(ByrefType, Name, ND);
5301 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005302 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005303 ByrefType += "__Block_byref_id_object_copy_";
5304 ByrefType += utostr(flag);
5305 ByrefType += ", __Block_byref_id_object_dispose_";
5306 ByrefType += utostr(flag);
5307 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005308 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005309 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005310
5311 // Complete the newly synthesized compound expression by inserting a right
5312 // curly brace before the end of the declaration.
5313 // FIXME: This approach avoids rewriting the initializer expression. It
5314 // also assumes there is only one declarator. For example, the following
5315 // isn't currently supported by this routine (in general):
5316 //
5317 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5318 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005319 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5320 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005321 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5322 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005323 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005324
Benjamin Kramerd999b372010-02-14 14:14:16 +00005325 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005326 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005327 return;
5328}
5329
Mike Stump1eb44332009-09-09 15:08:12 +00005330void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005331 // Add initializers for any closure decl refs.
5332 GetBlockDeclRefExprs(Exp->getBody());
5333 if (BlockDeclRefs.size()) {
5334 // Unique all "by copy" declarations.
5335 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005336 if (!BlockDeclRefs[i]->isByRef()) {
5337 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5338 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5339 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5340 }
5341 }
Steve Naroff54055232008-10-27 17:20:55 +00005342 // Unique all "by ref" declarations.
5343 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5344 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005345 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5346 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5347 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5348 }
Steve Naroff54055232008-10-27 17:20:55 +00005349 }
5350 // Find any imported blocks...they will need special attention.
5351 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005352 if (BlockDeclRefs[i]->isByRef() ||
5353 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005354 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005355 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005356 }
5357}
5358
Chris Lattner5f9e2722011-07-23 10:55:15 +00005359FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005360 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005361 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005362 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5363 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005364 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005365}
5366
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005367Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005368 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005369 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005370 Blocks.push_back(Exp);
5371
5372 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005373
5374 // Add inner imported variables now used in current block.
5375 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005376 if (!InnerBlockDeclRefs.empty()) {
5377 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5378 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5379 ValueDecl *VD = Exp->getDecl();
5380 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005381 // We need to save the copied-in variables in nested
5382 // blocks because it is needed at the end for some of the API generations.
5383 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005384 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5385 BlockDeclRefs.push_back(Exp);
5386 BlockByCopyDeclsPtrSet.insert(VD);
5387 BlockByCopyDecls.push_back(VD);
5388 }
5389 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5390 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5391 BlockDeclRefs.push_back(Exp);
5392 BlockByRefDeclsPtrSet.insert(VD);
5393 BlockByRefDecls.push_back(VD);
5394 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005395 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005396 // Find any imported blocks...they will need special attention.
5397 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5398 if (InnerBlockDeclRefs[i]->isByRef() ||
5399 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5400 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5401 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005402 }
5403 InnerDeclRefsCount.push_back(countOfInnerDecls);
5404
Steve Narofffa15fd92008-10-28 20:29:00 +00005405 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005406
Steve Narofffa15fd92008-10-28 20:29:00 +00005407 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005408 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005409 else if (CurMethodDef)
5410 BuildUniqueMethodName(FuncName, CurMethodDef);
5411 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005412 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Steve Narofffa15fd92008-10-28 20:29:00 +00005414 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005415
Steve Narofffa15fd92008-10-28 20:29:00 +00005416 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5417 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005418
Steve Narofffa15fd92008-10-28 20:29:00 +00005419 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005420 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5421 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005422
5423 FunctionDecl *FD;
5424 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005427 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005428 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5429 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005430
Chris Lattner5f9e2722011-07-23 10:55:15 +00005431 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005432
Steve Narofffdc03722008-10-29 21:23:59 +00005433 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005434 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005435 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005436 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005437 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005438 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005439 InitExprs.push_back(castExpr);
5440
Steve Naroff01aec112009-12-06 21:14:13 +00005441 // Initialize the block descriptor.
5442 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005443
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005444 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5445 SourceLocation(), SourceLocation(),
5446 &Context->Idents.get(DescData.c_str()),
5447 Context->VoidPtrTy, 0,
5448 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005449 UnaryOperator *DescRefExpr =
5450 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5451 Context->VoidPtrTy,
5452 VK_LValue,
5453 SourceLocation()),
5454 UO_AddrOf,
5455 Context->getPointerType(Context->VoidPtrTy),
5456 VK_RValue, OK_Ordinary,
5457 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005458 InitExprs.push_back(DescRefExpr);
5459
Steve Narofffa15fd92008-10-28 20:29:00 +00005460 // Add initializers for any closure decl refs.
5461 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005462 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005463 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005464 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005465 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005466 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005467 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005468 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005469 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5470 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005471 if (HasLocalVariableExternalStorage(*I)) {
5472 QualType QT = (*I)->getType();
5473 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005474 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5475 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005476 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005477 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005478 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005479 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5480 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005481 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005482 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005483 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005484 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005485 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5486 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005487 if (HasLocalVariableExternalStorage(*I)) {
5488 QualType QT = (*I)->getType();
5489 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005490 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5491 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005492 }
5493
Steve Narofffa15fd92008-10-28 20:29:00 +00005494 }
Mike Stump1eb44332009-09-09 15:08:12 +00005495 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005496 }
5497 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005498 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005499 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005500 ValueDecl *ND = (*I);
5501 std::string Name(ND->getNameAsString());
5502 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005503 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005504 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5505 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005506 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005507 SourceLocation(), SourceLocation(),
5508 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005509 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5510 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5511
Daniel Dunbar4087f272010-08-17 22:39:59 +00005512 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005513 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5514 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005515 bool isNestedCapturedVar = false;
5516 if (block)
5517 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5518 ce = block->capture_end(); ci != ce; ++ci) {
5519 const VarDecl *variable = ci->getVariable();
5520 if (variable == ND && ci->isNested()) {
5521 assert (ci->isByRef() &&
5522 "SynthBlockInitExpr - captured block variable is not byref");
5523 isNestedCapturedVar = true;
5524 break;
5525 }
5526 }
5527 // captured nested byref variable has its address passed. Do not take
5528 // its address again.
5529 if (!isNestedCapturedVar)
5530 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005531 Context->getPointerType(Exp->getType()),
5532 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005533 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005534 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005535 }
5536 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005537 if (ImportedBlockDecls.size()) {
5538 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5539 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005540 unsigned IntSize =
5541 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005542 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5543 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005544 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005545 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005546 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005547 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005548 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005549 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005550 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005551 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005552 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005553 BlockDeclRefs.clear();
5554 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005555 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005556 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005557 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005558 ImportedBlockDecls.clear();
5559 return NewRep;
5560}
5561
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005562bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5563 if (const ObjCForCollectionStmt * CS =
5564 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5565 return CS->getElement() == DS;
5566 return false;
5567}
5568
Steve Narofffa15fd92008-10-28 20:29:00 +00005569//===----------------------------------------------------------------------===//
5570// Function Body / Expression rewriting
5571//===----------------------------------------------------------------------===//
5572
Steve Naroffc77a6362008-12-04 16:24:46 +00005573// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5574// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5575// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5576// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5577// Since the rewriter isn't capable of rewriting rewritten code, it's important
5578// we get this right.
5579void RewriteObjC::CollectPropertySetters(Stmt *S) {
5580 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005581 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005582 if (*CI)
5583 CollectPropertySetters(*CI);
5584
5585 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5586 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005587 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5588 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005589 }
5590 }
5591}
5592
Steve Narofffa15fd92008-10-28 20:29:00 +00005593Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005594 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005595 isa<DoStmt>(S) || isa<ForStmt>(S))
5596 Stmts.push_back(S);
5597 else if (isa<ObjCForCollectionStmt>(S)) {
5598 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005599 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 }
Mike Stump1eb44332009-09-09 15:08:12 +00005601
Steve Narofffa15fd92008-10-28 20:29:00 +00005602 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005603
Steve Narofffa15fd92008-10-28 20:29:00 +00005604 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005605 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005606 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005607 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005608 Stmt *ChildStmt = (*CI);
5609 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005610 Expr *OldBase = IvarRefExpr->getBase();
5611 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005612 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005613 if (replaced) {
5614 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5615 ReplaceStmt(OldBase, IRE->getBase());
5616 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005617 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005618 }
5619 }
5620 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005621 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5622 if (newStmt) {
5623 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5624 if (PropSetters[PropOrImplicitRefExpr] == S) {
5625 S = newStmt;
5626 newStmt = 0;
5627 }
5628 if (newStmt)
5629 *CI = newStmt;
5630 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005631 // If dealing with an assignment with LHS being a property reference
5632 // expression, the entire assignment tree is rewritten into a property
5633 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5634 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005635 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005636 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005637 if (PropSetters[Exp]) {
5638 ++CI;
5639 continue;
5640 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005641 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005642 }
Mike Stump1eb44332009-09-09 15:08:12 +00005643
Steve Narofffa15fd92008-10-28 20:29:00 +00005644 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005645 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005646 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5647 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005648 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005649 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005650 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005651 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005652 Stmt *SaveCurrentBody = CurrentBody;
5653 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005654 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005655 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005656 // block literal on rhs of a property-dot-sytax assignment
5657 // must be replaced by its synthesize ast so getRewrittenText
5658 // works as expected. In this case, what actually ends up on RHS
5659 // is the blockTranscribed which is the helper function for the
5660 // block literal; as in: self.c = ^() {[ace ARR];};
5661 bool saveDisableReplaceStmt = DisableReplaceStmt;
5662 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005663 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005664 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005665 CurrentBody = SaveCurrentBody;
5666 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005667 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005668 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005669 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005670 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005671
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005672 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5673
Steve Narofffa15fd92008-10-28 20:29:00 +00005674 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005675 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005676 return blockTranscribed;
5677 }
5678 // Handle specific things.
5679 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5680 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005681
John McCall12f78a62010-12-02 01:19:52 +00005682 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005683 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5684 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5685
5686 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005687 if (BinOp) {
5688 // Because the rewriter doesn't allow us to rewrite rewritten code,
5689 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005690 DisableReplaceStmt = true;
5691 // Save the source range. Even if we disable the replacement, the
5692 // rewritten node will have been inserted into the tree. If the synthesized
5693 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005694 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005695 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5696 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005697 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005698 // Need to rewrite the ivar access expression if need be.
5699 if (isa<ObjCIvarRefExpr>(newStmt)) {
5700 bool replaced = false;
5701 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5702 }
5703
Steve Naroffb619d952008-12-09 12:56:34 +00005704 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005705 //
5706 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5707 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5708 // to see the original expression). Consider this example:
5709 //
5710 // Foo *obj1, *obj2;
5711 //
5712 // obj1.i = [obj2 rrrr];
5713 //
5714 // 'BinOp' for the previous expression looks like:
5715 //
5716 // (BinaryOperator 0x231ccf0 'int' '='
5717 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5718 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5719 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5720 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5721 //
5722 // 'newStmt' represents the rewritten message expression. For example:
5723 //
5724 // (CallExpr 0x231d300 'id':'struct objc_object *'
5725 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5726 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5727 // (CStyleCastExpr 0x231d220 'void *'
5728 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5729 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005730 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005731 // can be used as the setter argument. ReplaceStmt() will still 'see'
5732 // the original RHS (since we haven't altered BinOp).
5733 //
Mike Stump1eb44332009-09-09 15:08:12 +00005734 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005735 // node. As a result, we now leak the original AST nodes.
5736 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005737 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005738 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005739 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005740 }
5741 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005742
Steve Narofffa15fd92008-10-28 20:29:00 +00005743 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5744 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005745
Steve Narofffa15fd92008-10-28 20:29:00 +00005746 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5747 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005748
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005750#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005751 // Before we rewrite it, put the original message expression in a comment.
5752 SourceLocation startLoc = MessExpr->getLocStart();
5753 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005754
Steve Narofffa15fd92008-10-28 20:29:00 +00005755 const char *startBuf = SM->getCharacterData(startLoc);
5756 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005757
Steve Narofffa15fd92008-10-28 20:29:00 +00005758 std::string messString;
5759 messString += "// ";
5760 messString.append(startBuf, endBuf-startBuf+1);
5761 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005762
5763 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005764 // InsertText(clang::SourceLocation, char const*, unsigned int).
5765 // InsertText(startLoc, messString.c_str(), messString.size());
5766 // Tried this, but it didn't work either...
5767 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005768#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005769 return RewriteMessageExpr(MessExpr);
5770 }
Mike Stump1eb44332009-09-09 15:08:12 +00005771
Steve Narofffa15fd92008-10-28 20:29:00 +00005772 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5773 return RewriteObjCTryStmt(StmtTry);
5774
5775 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5776 return RewriteObjCSynchronizedStmt(StmtTry);
5777
5778 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5779 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005780
Steve Narofffa15fd92008-10-28 20:29:00 +00005781 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5782 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005783
5784 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005785 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005786 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005787 OrigStmtRange.getEnd());
5788 if (BreakStmt *StmtBreakStmt =
5789 dyn_cast<BreakStmt>(S))
5790 return RewriteBreakStmt(StmtBreakStmt);
5791 if (ContinueStmt *StmtContinueStmt =
5792 dyn_cast<ContinueStmt>(S))
5793 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005794
5795 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005796 // and cast exprs.
5797 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5798 // FIXME: What we're doing here is modifying the type-specifier that
5799 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005800 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005801 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5802 // the context of an ObjCForCollectionStmt. For example:
5803 // NSArray *someArray;
5804 // for (id <FooProtocol> index in someArray) ;
5805 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5806 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005807 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005808 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005809
Steve Narofffa15fd92008-10-28 20:29:00 +00005810 // Blocks rewrite rules.
5811 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5812 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005813 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005814 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005815 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005816 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005817 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005818 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005819 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005820 if (VD->hasAttr<BlocksAttr>()) {
5821 static unsigned uniqueByrefDeclCount = 0;
5822 assert(!BlockByRefDeclNo.count(ND) &&
5823 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5824 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005825 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005826 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005827 else
5828 RewriteTypeOfDecl(VD);
5829 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005830 }
Richard Smith162e1c12011-04-15 14:24:37 +00005831 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005832 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005833 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005834 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005835 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5836 }
5837 }
5838 }
Mike Stump1eb44332009-09-09 15:08:12 +00005839
Steve Narofffa15fd92008-10-28 20:29:00 +00005840 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5841 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005842
5843 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005844 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5845 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005846 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5847 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005848 && "Statement stack mismatch");
5849 Stmts.pop_back();
5850 }
5851 // Handle blocks rewriting.
5852 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5853 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005854 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005855 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005856 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5857 ValueDecl *VD = DRE->getDecl();
5858 if (VD->hasAttr<BlocksAttr>())
5859 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005860 if (HasLocalVariableExternalStorage(VD))
5861 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005862 }
5863
Steve Narofffa15fd92008-10-28 20:29:00 +00005864 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005865 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005866 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005867 ReplaceStmt(S, BlockCall);
5868 return BlockCall;
5869 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005870 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005871 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005872 RewriteCastExpr(CE);
5873 }
5874#if 0
5875 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005876 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5877 ICE->getSubExpr(),
5878 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005879 // Get the new text.
5880 std::string SStr;
5881 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005882 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005883 const std::string &Str = Buf.str();
5884
5885 printf("CAST = %s\n", &Str[0]);
5886 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5887 delete S;
5888 return Replacement;
5889 }
5890#endif
5891 // Return this stmt unmodified.
5892 return S;
5893}
5894
Steve Naroff3d7e7862009-12-05 15:55:59 +00005895void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5896 for (RecordDecl::field_iterator i = RD->field_begin(),
5897 e = RD->field_end(); i != e; ++i) {
5898 FieldDecl *FD = *i;
5899 if (isTopLevelBlockPointerType(FD->getType()))
5900 RewriteBlockPointerDecl(FD);
5901 if (FD->getType()->isObjCQualifiedIdType() ||
5902 FD->getType()->isObjCQualifiedInterfaceType())
5903 RewriteObjCQualifiedInterfaceTypes(FD);
5904 }
5905}
5906
Steve Narofffa15fd92008-10-28 20:29:00 +00005907/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5908/// main file of the input.
5909void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5910 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005911 if (FD->isOverloadedOperator())
5912 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005913
Steve Narofffa15fd92008-10-28 20:29:00 +00005914 // Since function prototypes don't have ParmDecl's, we check the function
5915 // prototype. This enables us to rewrite function declarations and
5916 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005917 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005918
Sebastian Redld3a413d2009-04-26 20:35:05 +00005919 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005920 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005921 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005922 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005923 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005924 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005925 Body =
5926 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5927 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005928 CurrentBody = 0;
5929 if (PropParentMap) {
5930 delete PropParentMap;
5931 PropParentMap = 0;
5932 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005933 // This synthesizes and inserts the block "impl" struct, invoke function,
5934 // and any copy/dispose helper functions.
5935 InsertBlockLiteralsWithinFunction(FD);
5936 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005937 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005938 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005939 return;
5940 }
5941 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005942 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005943 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005944 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005945 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005946 Body =
5947 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5948 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005949 CurrentBody = 0;
5950 if (PropParentMap) {
5951 delete PropParentMap;
5952 PropParentMap = 0;
5953 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005954 InsertBlockLiteralsWithinMethod(MD);
5955 CurMethodDef = 0;
5956 }
5957 }
5958 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5959 ClassImplementation.push_back(CI);
5960 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5961 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005962 else if (isa<ObjCClassDecl>(D))
5963 assert(false && "RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005964 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5965 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005966 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005967 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005968 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005969 CheckFunctionPointerDecl(VD->getType(), VD);
5970 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005971 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005972 RewriteCastExpr(CE);
5973 }
5974 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005975 } else if (VD->getType()->isRecordType()) {
5976 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5977 if (RD->isDefinition())
5978 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005979 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005980 if (VD->getInit()) {
5981 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005982 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005983 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005984 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005985 CurrentBody = 0;
5986 if (PropParentMap) {
5987 delete PropParentMap;
5988 PropParentMap = 0;
5989 }
Mike Stump1eb44332009-09-09 15:08:12 +00005990 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005991 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005992 GlobalVarDecl = 0;
5993
5994 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005995 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005996 RewriteCastExpr(CE);
5997 }
5998 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005999 return;
6000 }
Richard Smith162e1c12011-04-15 14:24:37 +00006001 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00006002 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00006003 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00006004 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00006005 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6006 return;
6007 }
6008 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00006009 if (RD->isDefinition())
6010 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00006011 return;
6012 }
6013 // Nothing yet.
6014}
6015
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00006016void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00006017 if (Diags.hasErrorOccurred())
6018 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006019
Steve Narofffa15fd92008-10-28 20:29:00 +00006020 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00006021
Steve Naroff621edce2009-04-29 16:37:50 +00006022 // Here's a great place to add any extra declarations that may be needed.
6023 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00006024 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00006025 E = ProtocolExprDecls.end(); I != E; ++I)
6026 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
6027
Benjamin Kramerd999b372010-02-14 14:14:16 +00006028 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00006029 if (ClassImplementation.size() || CategoryImplementation.size())
6030 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00006031
Steve Narofffa15fd92008-10-28 20:29:00 +00006032 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6033 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00006034 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00006035 Rewrite.getRewriteBufferFor(MainFileID)) {
6036 //printf("Changed:\n");
6037 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6038 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00006039 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00006040 }
Steve Narofface66252008-11-13 20:07:04 +00006041
Steve Naroff621edce2009-04-29 16:37:50 +00006042 if (ClassImplementation.size() || CategoryImplementation.size() ||
6043 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00006044 // Rewrite Objective-c meta data*
6045 std::string ResultStr;
6046 SynthesizeMetaDataIntoBuffer(ResultStr);
6047 // Emit metadata.
6048 *OutFile << ResultStr;
6049 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006050 OutFile->flush();
6051}