blob: 83eba54c9db360d70b8452985c33c43f11331909 [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) {
468 FunctionProtoType::ExtProtoInfo fpi;
469 fpi.Variadic = variadic;
470 return Context->getFunctionType(result, args, numArgs, fpi);
471 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000472 };
John McCall9d125032010-01-15 18:39:57 +0000473
474 // Helper function: create a CStyleCastExpr with trivial type source info.
475 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000476 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000477 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000478 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000479 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000480 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000481}
482
Mike Stump1eb44332009-09-09 15:08:12 +0000483void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
484 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000485 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000486 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000487 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000488 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000489 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000490 // All the args are checked/rewritten. Don't call twice!
491 RewriteBlockPointerDecl(D);
492 break;
493 }
494 }
495}
496
497void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000498 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000499 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000500 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000501}
502
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000503static bool IsHeaderFile(const std::string &Filename) {
504 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000505
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000506 if (DotPos == std::string::npos) {
507 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000508 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000509 }
Mike Stump1eb44332009-09-09 15:08:12 +0000510
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000511 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
512 // C header: .h
513 // C++ header: .hh or .H;
514 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000515}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000516
Chris Lattner5f9e2722011-07-23 10:55:15 +0000517RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000518 Diagnostic &D, const LangOptions &LOpts,
519 bool silenceMacroWarn)
520 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
521 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000522 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000523 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000524 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000525 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000526 "rewriter doesn't support user-specified control flow semantics "
527 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000528}
529
Eli Friedmanbce831b2009-05-18 22:29:17 +0000530ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000531 raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000533 const LangOptions &LOpts,
534 bool SilenceRewriteMacroWarning) {
535 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000536}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000537
Steve Naroffb29b4272008-04-14 22:03:09 +0000538void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000539 Context = &context;
540 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000541 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000542 MsgSendFunctionDecl = 0;
543 MsgSendSuperFunctionDecl = 0;
544 MsgSendStretFunctionDecl = 0;
545 MsgSendSuperStretFunctionDecl = 0;
546 MsgSendFpretFunctionDecl = 0;
547 GetClassFunctionDecl = 0;
548 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000549 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000550 SelGetUidFunctionDecl = 0;
551 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000552 ConstantStringClassReference = 0;
553 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000554 CurMethodDef = 0;
555 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000556 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000557 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000558 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000559 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000560 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000561 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000562 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000563 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000564 PropParentMap = 0;
565 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000566 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000567 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000568
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000569 // Get the ID and start/end of the main file.
570 MainFileID = SM->getMainFileID();
571 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
572 MainFileStart = MainBuf->getBufferStart();
573 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000574
Chris Lattner2c78b872009-04-14 23:22:57 +0000575 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000576
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000577 // declaring objc_selector outside the parameter list removes a silly
578 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000579 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000580 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000582 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000583 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000584 if (LangOpts.Microsoft) {
585 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000586 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
587 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000588 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000589 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000591 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
592 Preamble += "typedef struct objc_object Protocol;\n";
593 Preamble += "#define _REWRITER_typedef_Protocol\n";
594 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000595 if (LangOpts.Microsoft) {
596 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
597 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
598 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000599 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000600 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000601 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000602 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000603 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000604 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000605 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000606 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000607 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000608 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000609 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000610 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000611 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000612 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
613 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000614 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000615 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000616 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
617 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
618 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
619 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
620 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000621 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000622 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
624 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
625 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000626 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
627 Preamble += "struct __objcFastEnumerationState {\n\t";
628 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000629 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000630 Preamble += "unsigned long *mutationsPtr;\n\t";
631 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000632 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000633 Preamble += "#define __FASTENUMERATIONSTATE\n";
634 Preamble += "#endif\n";
635 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
636 Preamble += "struct __NSConstantStringImpl {\n";
637 Preamble += " int *isa;\n";
638 Preamble += " int flags;\n";
639 Preamble += " char *str;\n";
640 Preamble += " long length;\n";
641 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000642 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
643 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
644 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000645 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000646 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000647 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
648 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000649 // Blocks preamble.
650 Preamble += "#ifndef BLOCK_IMPL\n";
651 Preamble += "#define BLOCK_IMPL\n";
652 Preamble += "struct __block_impl {\n";
653 Preamble += " void *isa;\n";
654 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000655 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000656 Preamble += " void *FuncPtr;\n";
657 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000658 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000659 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000660 Preamble += "extern \"C\" __declspec(dllexport) "
661 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000662 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
663 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
664 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
665 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000666 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
667 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000668 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
669 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
670 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000671 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000672 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000673 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
674 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000675 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000676 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000677 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000678 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000679 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000680 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000681 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000682 Preamble += "#define __weak\n";
683 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000684 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
685 // as this avoids warning in any 64bit/32bit compilation model.
686 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000687}
688
689
Chris Lattnerf04da132007-10-24 17:06:59 +0000690//===----------------------------------------------------------------------===//
691// Top Level Driver Code
692//===----------------------------------------------------------------------===//
693
Chris Lattner682bf922009-03-29 16:50:03 +0000694void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000695 if (Diags.hasErrorOccurred())
696 return;
697
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000698 // Two cases: either the decl could be in the main file, or it could be in a
699 // #included file. If the former, rewrite it now. If the later, check to see
700 // if we rewrote the #include/#import.
701 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000702 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000703
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000704 // If this is for a builtin, ignore it.
705 if (Loc.isInvalid()) return;
706
Steve Naroffebf2b562007-10-23 23:50:29 +0000707 // Look for built-in declarations that we need to refer during the rewrite.
708 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000709 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000710 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000711 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000712 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000713 ConstantStringClassReference = FVD;
714 return;
715 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000716 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000717 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000718 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000719 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000720 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000721 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000722 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000723 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000724 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000725 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
726 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000727 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
728 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000729 DI != DIEnd; ) {
730 if (isa<ObjCClassDecl>((*DI))) {
731 SmallVector<Decl *, 8> DG;
732 Decl *D = (*DI);
733 SourceLocation Loc = D->getLocation();
734 while (DI != DIEnd &&
735 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
736 DG.push_back(D);
737 ++DI;
738 D = (*DI);
739 }
740 RewriteForwardClassDecl(DG);
741 continue;
742 }
Chris Lattner682bf922009-03-29 16:50:03 +0000743 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000744 ++DI;
745 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000746 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000747 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000748 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000749 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000750}
751
Chris Lattnerf04da132007-10-24 17:06:59 +0000752//===----------------------------------------------------------------------===//
753// Syntactic (non-AST) Rewriting Code
754//===----------------------------------------------------------------------===//
755
Steve Naroffb29b4272008-04-14 22:03:09 +0000756void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000757 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000758 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000759 const char *MainBufStart = MainBuf.begin();
760 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000761 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000762
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000763 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000764 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
765 if (*BufPtr == '#') {
766 if (++BufPtr == MainBufEnd)
767 return;
768 while (*BufPtr == ' ' || *BufPtr == '\t')
769 if (++BufPtr == MainBufEnd)
770 return;
771 if (!strncmp(BufPtr, "import", ImportLen)) {
772 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000773 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000774 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000775 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000776 BufPtr += ImportLen;
777 }
778 }
779 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000780}
781
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000782static std::string getIvarAccessString(ObjCIvarDecl *OID) {
783 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000784 std::string S;
785 S = "((struct ";
786 S += ClassDecl->getIdentifier()->getName();
787 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000788 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000789 return S;
790}
791
Steve Naroffa0876e82008-12-02 17:36:43 +0000792void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
793 ObjCImplementationDecl *IMD,
794 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000795 static bool objcGetPropertyDefined = false;
796 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000797 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000798 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000799 const char *startBuf = SM->getCharacterData(startLoc);
800 assert((*startBuf == '@') && "bogus @synthesize location");
801 const char *semiBuf = strchr(startBuf, ';');
802 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000803 SourceLocation onePastSemiLoc =
804 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000805
806 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
807 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000808
Steve Naroffeb0646c2008-12-02 15:48:25 +0000809 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000810 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000811 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000812
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000813 if (!OID)
814 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000815 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000816 if (!PD->getGetterMethodDecl()->isDefined()) {
817 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
818 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
819 ObjCPropertyDecl::OBJC_PR_copy));
820 std::string Getr;
821 if (GenGetProperty && !objcGetPropertyDefined) {
822 objcGetPropertyDefined = true;
823 // FIXME. Is this attribute correct in all cases?
824 Getr = "\nextern \"C\" __declspec(dllimport) "
825 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000826 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000827 RewriteObjCMethodDecl(OID->getContainingInterface(),
828 PD->getGetterMethodDecl(), Getr);
829 Getr += "{ ";
830 // Synthesize an explicit cast to gain access to the ivar.
831 // See objc-act.c:objc_synthesize_new_getter() for details.
832 if (GenGetProperty) {
833 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
834 Getr += "typedef ";
835 const FunctionType *FPRetType = 0;
836 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
837 FPRetType);
838 Getr += " _TYPE";
839 if (FPRetType) {
840 Getr += ")"; // close the precedence "scope" for "*".
841
842 // Now, emit the argument types (if any).
843 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
844 Getr += "(";
845 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
846 if (i) Getr += ", ";
847 std::string ParamStr = FT->getArgType(i).getAsString(
848 Context->PrintingPolicy);
849 Getr += ParamStr;
850 }
851 if (FT->isVariadic()) {
852 if (FT->getNumArgs()) Getr += ", ";
853 Getr += "...";
854 }
855 Getr += ")";
856 } else
857 Getr += "()";
858 }
859 Getr += ";\n";
860 Getr += "return (_TYPE)";
861 Getr += "objc_getProperty(self, _cmd, ";
862 SynthesizeIvarOffsetComputation(OID, Getr);
863 Getr += ", 1)";
864 }
865 else
866 Getr += "return " + getIvarAccessString(OID);
867 Getr += "; }";
868 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000869 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000870
871 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000872 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Steve Naroffeb0646c2008-12-02 15:48:25 +0000874 // Generate the 'setter' function.
875 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000876 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
877 ObjCPropertyDecl::OBJC_PR_copy);
878 if (GenSetProperty && !objcSetPropertyDefined) {
879 objcSetPropertyDefined = true;
880 // FIXME. Is this attribute correct in all cases?
881 Setr = "\nextern \"C\" __declspec(dllimport) "
882 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
883 }
884
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000885 RewriteObjCMethodDecl(OID->getContainingInterface(),
886 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000887 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000888 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000889 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000890 if (GenSetProperty) {
891 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000892 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000893 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000894 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000895 Setr += ", ";
896 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
897 Setr += "0, ";
898 else
899 Setr += "1, ";
900 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
901 Setr += "1)";
902 else
903 Setr += "0)";
904 }
905 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000906 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000907 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000908 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000909 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000910 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000911}
Chris Lattner8a12c272007-10-11 18:38:32 +0000912
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000913static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
914 std::string &typedefString) {
915 typedefString += "#ifndef _REWRITER_typedef_";
916 typedefString += ForwardDecl->getNameAsString();
917 typedefString += "\n";
918 typedefString += "#define _REWRITER_typedef_";
919 typedefString += ForwardDecl->getNameAsString();
920 typedefString += "\n";
921 typedefString += "typedef struct objc_object ";
922 typedefString += ForwardDecl->getNameAsString();
923 typedefString += ";\n#endif\n";
924}
925
926void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
927 const std::string &typedefString) {
928 SourceLocation startLoc = ClassDecl->getLocation();
929 const char *startBuf = SM->getCharacterData(startLoc);
930 const char *semiPtr = strchr(startBuf, ';');
931 // Replace the @class with typedefs corresponding to the classes.
932 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
933}
934
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000935void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000936 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000937 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
938 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
939 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
940 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000941 // Translate to typedef's that forward reference structs with the same name
942 // as the class. As a convenience, we include the original declaration
943 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000944 typedefString += "// @class ";
945 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000946 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000947 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000948 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000949 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000950 DeclGroupRef::iterator I = D.begin();
951 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
952}
Mike Stump1eb44332009-09-09 15:08:12 +0000953
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000954void RewriteObjC::RewriteForwardClassDecl(
955 const llvm::SmallVector<Decl*, 8> &D) {
956 std::string typedefString;
957 for (unsigned i = 0; i < D.size(); i++) {
958 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
959 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
960 if (i == 0) {
961 typedefString += "// @class ";
962 typedefString += ForwardDecl->getNameAsString();
963 typedefString += ";\n";
964 }
965 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
966 }
967 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000968}
969
Steve Naroffb29b4272008-04-14 22:03:09 +0000970void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000971 // When method is a synthesized one, such as a getter/setter there is
972 // nothing to rewrite.
973 if (Method->isSynthesized())
974 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000975 SourceLocation LocStart = Method->getLocStart();
976 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000977
Chandler Carruth64211622011-07-25 21:09:52 +0000978 if (SM->getExpansionLineNumber(LocEnd) >
979 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000980 InsertText(LocStart, "#if 0\n");
981 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000982 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000983 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000984 }
985}
986
Mike Stump1eb44332009-09-09 15:08:12 +0000987void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000988 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000989
Benjamin Kramerd999b372010-02-14 14:14:16 +0000990 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000991 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000992}
993
Steve Naroffb29b4272008-04-14 22:03:09 +0000994void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000995 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000996
Steve Naroff423cb562007-10-30 13:30:57 +0000997 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000998 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000999
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001000 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1001 E = CatDecl->prop_end(); I != E; ++I)
1002 RewriteProperty(*I);
1003
Mike Stump1eb44332009-09-09 15:08:12 +00001004 for (ObjCCategoryDecl::instmeth_iterator
1005 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001006 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001007 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001008 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001009 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001010 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001011 RewriteMethodDeclaration(*I);
1012
Steve Naroff423cb562007-10-30 13:30:57 +00001013 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001014 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1015 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001016}
1017
Steve Naroffb29b4272008-04-14 22:03:09 +00001018void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001019 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001020
Steve Naroff752d6ef2007-10-30 16:42:30 +00001021 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001022 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001023
1024 for (ObjCProtocolDecl::instmeth_iterator
1025 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001026 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001027 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001028 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001029 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001030 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001031 RewriteMethodDeclaration(*I);
1032
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001033 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1034 E = PDecl->prop_end(); I != E; ++I)
1035 RewriteProperty(*I);
1036
Steve Naroff752d6ef2007-10-30 16:42:30 +00001037 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001038 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001039 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001040
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001041 // Must comment out @optional/@required
1042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
1044 for (const char *p = startBuf; p < endBuf; p++) {
1045 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001046 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001047 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001048
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001049 }
1050 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Steve Naroff8cc764c2007-11-14 15:03:57 +00001051 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001052 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001053
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001054 }
1055 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001056}
1057
Steve Naroffb29b4272008-04-14 22:03:09 +00001058void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001059 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001060 if (LocStart.isInvalid())
1061 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001062 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001063 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001064}
1065
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001066void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1067 const FunctionType *&FPRetType) {
1068 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001069 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001070 else if (T->isFunctionPointerType() ||
1071 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001072 // needs special handling, since pointer-to-functions have special
1073 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001074 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001075 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001076 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001077 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001078 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001079 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001080 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001081 ResultStr += FPRetType->getResultType().getAsString(
1082 Context->PrintingPolicy);
Steve Narofff4312dc2008-12-11 19:29:16 +00001083 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001084 }
1085 } else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001086 ResultStr += T.getAsString(Context->PrintingPolicy);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001087}
1088
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001089void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1090 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001091 std::string &ResultStr) {
1092 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1093 const FunctionType *FPRetType = 0;
1094 ResultStr += "\nstatic ";
1095 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001096 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001097
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001098 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001099 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001100
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001101 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001102 NameStr += "_I_";
1103 else
1104 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001105
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001106 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001107 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001108
1109 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001110 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001111 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001112 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001113 }
Mike Stump1eb44332009-09-09 15:08:12 +00001114 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001115 {
1116 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001117 int len = selString.size();
1118 for (int i = 0; i < len; i++)
1119 if (selString[i] == ':')
1120 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001121 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001122 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001123 // Remember this name for metadata emission
1124 MethodInternalNames[OMD] = NameStr;
1125 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001126
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001127 // Rewrite arguments
1128 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001129
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001130 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001131 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001132 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001133 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +00001134 if (!LangOpts.Microsoft) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001135 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001136 ResultStr += "struct ";
1137 }
1138 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001139 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001140 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001141 }
1142 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001143 ResultStr += Context->getObjCClassType().getAsString(
1144 Context->PrintingPolicy);
Mike Stump1eb44332009-09-09 15:08:12 +00001145
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001146 ResultStr += " self, ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001147 ResultStr += Context->getObjCSelType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001148 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001149
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001151 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1152 E = OMD->param_end(); PI != E; ++PI) {
1153 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001154 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001155 if (PDecl->getType()->isObjCQualifiedIdType()) {
1156 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001157 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001158 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001159 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001160 QualType QT = PDecl->getType();
1161 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1162 if (convertBlockPointerToFunctionPointer(QT))
1163 QT.getAsStringInternal(Name, Context->PrintingPolicy);
1164 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001165 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001166 ResultStr += Name;
1167 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001168 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001169 if (OMD->isVariadic())
1170 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001171 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001172
Steve Naroff76e429d2008-07-16 14:40:40 +00001173 if (FPRetType) {
1174 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Steve Naroff76e429d2008-07-16 14:40:40 +00001176 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001177 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001178 ResultStr += "(";
1179 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1180 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001181 std::string ParamStr = FT->getArgType(i).getAsString(
1182 Context->PrintingPolicy);
Steve Naroff76e429d2008-07-16 14:40:40 +00001183 ResultStr += ParamStr;
1184 }
1185 if (FT->isVariadic()) {
1186 if (FT->getNumArgs()) ResultStr += ", ";
1187 ResultStr += "...";
1188 }
1189 ResultStr += ")";
1190 } else {
1191 ResultStr += "()";
1192 }
1193 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001194}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001195void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001196 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1197 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001198
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001199 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001200
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001201 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001202 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1203 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001204 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001205 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001206 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001207 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001208 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001209 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001210
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001211 const char *startBuf = SM->getCharacterData(LocStart);
1212 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001213 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001214 }
Mike Stump1eb44332009-09-09 15:08:12 +00001215
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001216 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001217 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1218 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001219 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001221 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001222 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001223 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001224 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001225
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001226 const char *startBuf = SM->getCharacterData(LocStart);
1227 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001228 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001229 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001230 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001231 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001232 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001233 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001234 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001235 }
1236
Benjamin Kramerd999b372010-02-14 14:14:16 +00001237 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001238}
1239
Steve Naroffb29b4272008-04-14 22:03:09 +00001240void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001241 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001242 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001243 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001244 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001245 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001246 ResultStr += "\n";
1247 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001248 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001249 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001250 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001251 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001252 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001253 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001254 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001255 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001256 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001257
1258 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001259 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001260 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001261 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001262 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001263 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001264 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001265 for (ObjCInterfaceDecl::classmeth_iterator
1266 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001267 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001268 RewriteMethodDeclaration(*I);
1269
Steve Naroff2feac5e2007-10-30 03:43:13 +00001270 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001271 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1272 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001273}
1274
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001275Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001276 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001277 ObjCMethodDecl *OMD = 0;
1278 QualType Ty;
1279 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001280 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001281 bool Super = false;
1282 QualType SuperTy;
1283 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001284 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001285 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001286 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001287 if (ObjCPropertyRefExpr *PropRefExpr =
1288 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001289 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001290 if (PropRefExpr->isExplicitProperty()) {
1291 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1292 OMD = PDecl->getSetterMethodDecl();
1293 Ty = PDecl->getType();
1294 Sel = PDecl->getSetterName();
1295 } else {
1296 OMD = PropRefExpr->getImplicitPropertySetter();
1297 Sel = OMD->getSelector();
1298 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001299 }
John McCall12f78a62010-12-02 01:19:52 +00001300 Super = PropRefExpr->isSuperReceiver();
1301 if (!Super) {
1302 Receiver = PropRefExpr->getBase();
1303 } else {
1304 SuperTy = PropRefExpr->getSuperReceiverType();
1305 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001306 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001307 }
1308
1309 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Chris Lattner5f9e2722011-07-23 10:55:15 +00001310 SmallVector<Expr *, 1> ExprVec;
Steve Naroffc77a6362008-12-04 16:24:46 +00001311 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001312
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001313 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001314 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001315 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001317 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001318 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001319 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001320 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001321 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001322 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001323 &ExprVec[0], 1,
1324 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001325 else {
1326 // FIXME. Refactor this into common code with that in
1327 // RewritePropertyOrImplicitGetter
1328 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1329 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1330 if (PropGetters[Exp])
1331 // This allows us to handle chain/nested property/implicit getters.
1332 Receiver = PropGetters[Exp];
1333
Douglas Gregor04badcf2010-04-21 00:45:42 +00001334 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001335 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001336 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001337 /*FIXME: */SourceLocation(),
1338 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001339 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001340 &ExprVec[0], 1,
1341 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001342 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001343 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001344
Steve Naroffc77a6362008-12-04 16:24:46 +00001345 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001346 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001347 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001348 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1349 // to things that stay around.
1350 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001351 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001352}
1353
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001354Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1355 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001356 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001357 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001358 ObjCMethodDecl *OMD = 0;
1359 QualType Ty;
1360 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001361 bool Super = false;
1362 QualType SuperTy;
1363 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001364 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001365 if (ObjCPropertyRefExpr *PropRefExpr =
1366 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001367 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001368 if (PropRefExpr->isExplicitProperty()) {
1369 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1370 OMD = PDecl->getGetterMethodDecl();
1371 Ty = PDecl->getType();
1372 Sel = PDecl->getGetterName();
1373 } else {
1374 OMD = PropRefExpr->getImplicitPropertyGetter();
1375 Sel = OMD->getSelector();
1376 Ty = PropRefExpr->getType();
1377 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001378 Super = PropRefExpr->isSuperReceiver();
1379 if (!Super)
1380 Receiver = PropRefExpr->getBase();
1381 else {
John McCall12f78a62010-12-02 01:19:52 +00001382 SuperTy = PropRefExpr->getSuperReceiverType();
1383 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001384 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001385 }
1386
1387 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1388
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001389 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001390 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001391 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001392 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001393 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001394 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001395 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001396 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001397 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001398 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001399 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001400 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001401 else {
1402 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1403 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1404 if (PropGetters[Exp])
1405 // This allows us to handle chain/nested property/implicit getters.
1406 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001407 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001408 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001409 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001410 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001411 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001412 Sel, SelectorLoc, OMD,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001413 0, 0,
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001414 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001415 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001416
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001417 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1418 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001419
1420 if (!PropParentMap)
1421 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001422 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001423 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001424 ImplicitCastExpr*ICE=0;
1425 if (Parent)
1426 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1427 assert((ICE->getCastKind() == CK_GetObjCProperty)
1428 && "RewritePropertyOrImplicitGetter");
1429 Parent = PropParentMap->getParent(Parent);
1430 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1431 }
1432 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001433 // We stash away the ReplacingStmt since actually doing the
1434 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001435 PropGetters[ICE] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001436 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1437 // to things that stay around.
1438 Context->Deallocate(MsgExpr);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001439 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001440 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001441 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001442 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001443 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1444 // to things that stay around.
1445 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001446 return ReplacingStmt;
1447 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001448}
1449
Mike Stump1eb44332009-09-09 15:08:12 +00001450Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001451 SourceLocation OrigStart,
1452 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001453 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001454 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001455 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001456 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001457 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001458 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001459 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001460 // lookup which class implements the instance variable.
1461 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001462 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001463 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001464 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001465
Steve Narofff0757612008-05-08 17:52:16 +00001466 // Synthesize an explicit cast to gain access to the ivar.
1467 std::string RecName = clsDeclared->getIdentifier()->getName();
1468 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001469 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001470 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001471 SourceLocation(), SourceLocation(),
1472 II);
Steve Narofff0757612008-05-08 17:52:16 +00001473 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1474 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001475 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001476 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001477 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001478 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001479 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001480 IV->getBase()->getLocEnd(),
1481 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001482 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001483 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001484 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001485 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001486 IV->getLocation(),
1487 D->getType(),
1488 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001489 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001490 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001491 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001492 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001493 // Cannot delete IV->getBase(), since PE points to it.
1494 // Replace the old base with the cast. This is important when doing
1495 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001496 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001497 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001498 }
Steve Naroff84472a82008-04-18 21:55:08 +00001499 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001500 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001501
Steve Naroff9f525972008-05-06 23:20:07 +00001502 // Explicit ivar refs need to have a cast inserted.
1503 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001504 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001505 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001506 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001507 // lookup which class implements the instance variable.
1508 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001509 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001510 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001511 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Steve Naroff9f525972008-05-06 23:20:07 +00001513 // Synthesize an explicit cast to gain access to the ivar.
1514 std::string RecName = clsDeclared->getIdentifier()->getName();
1515 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001516 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001517 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001518 SourceLocation(), SourceLocation(),
1519 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001520 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1521 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001522 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001523 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001524 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001525 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001526 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001527 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001528 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001529 // Cannot delete IV->getBase(), since PE points to it.
1530 // Replace the old base with the cast. This is important when doing
1531 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001532 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001533 return IV;
1534 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001535 }
Steve Naroff84472a82008-04-18 21:55:08 +00001536 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001537}
1538
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001539Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001540 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001541 if (*CI) {
1542 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1543 if (newStmt)
1544 *CI = newStmt;
1545 }
1546 }
1547 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1548 SourceRange OrigStmtRange = S->getSourceRange();
1549 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1550 replaced);
1551 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001552 }
1553 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1554 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1555 return newStmt;
1556 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001557 return S;
1558}
1559
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001560/// SynthCountByEnumWithState - To print:
1561/// ((unsigned int (*)
1562/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001563/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001564/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001565/// "countByEnumeratingWithState:objects:count:"),
1566/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567/// (id *)items, (unsigned int)16)
1568///
Steve Naroffb29b4272008-04-14 22:03:09 +00001569void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001570 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1571 "id *, unsigned int))(void *)objc_msgSend)";
1572 buf += "\n\t\t";
1573 buf += "((id)l_collection,\n\t\t";
1574 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1575 buf += "\n\t\t";
1576 buf += "&enumState, "
1577 "(id *)items, (unsigned int)16)";
1578}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001579
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001580/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1581/// statement to exit to its outer synthesized loop.
1582///
Steve Naroffb29b4272008-04-14 22:03:09 +00001583Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001584 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1585 return S;
1586 // replace break with goto __break_label
1587 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001588
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001589 SourceLocation startLoc = S->getLocStart();
1590 buf = "goto __break_label_";
1591 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001592 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001593
1594 return 0;
1595}
1596
1597/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1598/// statement to continue with its inner synthesized loop.
1599///
Steve Naroffb29b4272008-04-14 22:03:09 +00001600Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001601 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1602 return S;
1603 // replace continue with goto __continue_label
1604 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001605
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001606 SourceLocation startLoc = S->getLocStart();
1607 buf = "goto __continue_label_";
1608 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001609 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001610
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001611 return 0;
1612}
1613
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001614/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001615/// It rewrites:
1616/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001618/// Into:
1619/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001620/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001621/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001622/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001623/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001624/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001625/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001626/// if (limit) {
1627/// unsigned long startMutations = *enumState.mutationsPtr;
1628/// do {
1629/// unsigned long counter = 0;
1630/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001631/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001633/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001634/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001635/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001636/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001637/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001638/// objects:items count:16]);
1639/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001640/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001641/// }
1642/// else
1643/// elem = nil;
1644/// }
1645///
Steve Naroffb29b4272008-04-14 22:03:09 +00001646Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001647 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001648 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001649 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001650 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001651 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001652 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001653
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001654 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001655 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001656 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001657 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001658 std::string buf;
1659 buf = "\n{\n\t";
1660 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1661 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001662 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001663 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001664 if (ElementType->isObjCQualifiedIdType() ||
1665 ElementType->isObjCQualifiedInterfaceType())
1666 // Simply use 'id' for all qualified types.
1667 elementTypeAsString = "id";
1668 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001669 elementTypeAsString = ElementType.getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001670 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001671 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001672 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001673 buf += elementName;
1674 buf += ";\n\t";
1675 }
Chris Lattner06767512008-04-08 05:52:18 +00001676 else {
1677 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001678 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001679 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1680 if (VD->getType()->isObjCQualifiedIdType() ||
1681 VD->getType()->isObjCQualifiedInterfaceType())
1682 // Simply use 'id' for all qualified types.
1683 elementTypeAsString = "id";
1684 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001685 elementTypeAsString = VD->getType().getAsString(Context->PrintingPolicy);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001686 }
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001688 // struct __objcFastEnumerationState enumState = { 0 };
1689 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1690 // id items[16];
1691 buf += "id items[16];\n\t";
1692 // id l_collection = (id)
1693 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001694 // Find start location of 'collection' the hard way!
1695 const char *startCollectionBuf = startBuf;
1696 startCollectionBuf += 3; // skip 'for'
1697 startCollectionBuf = strchr(startCollectionBuf, '(');
1698 startCollectionBuf++; // skip '('
1699 // find 'in' and skip it.
1700 while (*startCollectionBuf != ' ' ||
1701 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1702 (*(startCollectionBuf+3) != ' ' &&
1703 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1704 startCollectionBuf++;
1705 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001706
1707 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001708 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001709 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001710 SourceLocation rightParenLoc = S->getRParenLoc();
1711 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1712 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001713 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001714
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001715 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1716 // objects:items count:16];
1717 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001718 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001719 // ((unsigned int (*)
1720 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001721 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001722 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001723 // "countByEnumeratingWithState:objects:count:"),
1724 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001725 // (id *)items, (unsigned int)16);
1726 buf += "unsigned long limit =\n\t\t";
1727 SynthCountByEnumWithState(buf);
1728 buf += ";\n\t";
1729 /// if (limit) {
1730 /// unsigned long startMutations = *enumState.mutationsPtr;
1731 /// do {
1732 /// unsigned long counter = 0;
1733 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001734 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001735 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001736 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001737 buf += "if (limit) {\n\t";
1738 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1739 buf += "do {\n\t\t";
1740 buf += "unsigned long counter = 0;\n\t\t";
1741 buf += "do {\n\t\t\t";
1742 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1743 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1744 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001745 buf += " = (";
1746 buf += elementTypeAsString;
1747 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001748 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001749 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001750
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001751 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001752 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001753 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001754 /// objects:items count:16]);
1755 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001756 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001757 /// }
1758 /// else
1759 /// elem = nil;
1760 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001761 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001762 buf = ";\n\t";
1763 buf += "__continue_label_";
1764 buf += utostr(ObjCBcLabelNo.back());
1765 buf += ": ;";
1766 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001767 buf += "} while (counter < limit);\n\t";
1768 buf += "} while (limit = ";
1769 SynthCountByEnumWithState(buf);
1770 buf += ");\n\t";
1771 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001772 buf += " = ((";
1773 buf += elementTypeAsString;
1774 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001775 buf += "__break_label_";
1776 buf += utostr(ObjCBcLabelNo.back());
1777 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001778 buf += "}\n\t";
1779 buf += "else\n\t\t";
1780 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001781 buf += " = ((";
1782 buf += elementTypeAsString;
1783 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001784 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001785
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001786 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001787 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001788 if (isa<CompoundStmt>(S->getBody())) {
1789 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001790 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001791 } else {
1792 /* Need to treat single statements specially. For example:
1793 *
1794 * for (A *a in b) if (stuff()) break;
1795 * for (A *a in b) xxxyy;
1796 *
1797 * The following code simply scans ahead to the semi to find the actual end.
1798 */
1799 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1800 const char *semiBuf = strchr(stmtBuf, ';');
1801 assert(semiBuf && "Can't find ';'");
1802 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001803 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001804 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001805 Stmts.pop_back();
1806 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001807 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001808}
1809
Mike Stump1eb44332009-09-09 15:08:12 +00001810/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001811/// This routine rewrites @synchronized(expr) stmt;
1812/// into:
1813/// objc_sync_enter(expr);
1814/// @try stmt @finally { objc_sync_exit(expr); }
1815///
Steve Naroffb29b4272008-04-14 22:03:09 +00001816Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001817 // Get the start location and compute the semi location.
1818 SourceLocation startLoc = S->getLocStart();
1819 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001820
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001821 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001822
1823 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001824 buf = "objc_sync_enter((id)";
1825 const char *lparenBuf = startBuf;
1826 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001827 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001828 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1829 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001830 // been rewritten! (which implies the SourceLocation's are invalid).
1831 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001832 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001833 while (*endBuf != ')') endBuf--;
1834 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001835 buf = ");\n";
1836 // declare a new scope with two variables, _stack and _rethrow.
1837 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1838 buf += "int buf[18/*32-bit i386*/];\n";
1839 buf += "char *pointers[4];} _stack;\n";
1840 buf += "id volatile _rethrow = 0;\n";
1841 buf += "objc_exception_try_enter(&_stack);\n";
1842 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001843 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001844 startLoc = S->getSynchBody()->getLocEnd();
1845 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001846
Steve Naroffc7089f12008-08-19 13:04:19 +00001847 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001848 SourceLocation lastCurlyLoc = startLoc;
1849 buf = "}\nelse {\n";
1850 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001851 buf += "}\n";
1852 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001853 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001854
1855 std::string syncBuf;
1856 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001857
1858 Expr *syncExpr = S->getSynchExpr();
1859 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1860 ? CK_BitCast :
1861 syncExpr->getType()->isBlockPointerType()
1862 ? CK_BlockPointerToObjCPointerCast
1863 : CK_CPointerToObjCPointerCast;
1864 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1865 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001866 std::string syncExprBufS;
1867 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001868 syncExpr->printPretty(syncExprBuf, *Context, 0,
1869 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001870 syncBuf += syncExprBuf.str();
1871 syncBuf += ");";
1872
1873 buf += syncBuf;
1874 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001875 buf += "}\n";
1876 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001877
Benjamin Kramerd999b372010-02-14 14:14:16 +00001878 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001879
1880 bool hasReturns = false;
1881 HasReturnStmts(S->getSynchBody(), hasReturns);
1882 if (hasReturns)
1883 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1884
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001885 return 0;
1886}
1887
Steve Naroffb85e77a2009-12-05 21:43:12 +00001888void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1889{
Steve Naroff8c565152008-12-05 17:03:39 +00001890 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001891 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001892 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001893 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001894
Steve Naroffb85e77a2009-12-05 21:43:12 +00001895 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001896 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001897 TryFinallyContainsReturnDiag);
1898 }
1899 return;
1900}
1901
Steve Naroffb85e77a2009-12-05 21:43:12 +00001902void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1903{
1904 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001905 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001906 if (*CI)
1907 HasReturnStmts(*CI, hasReturns);
1908
1909 if (isa<ReturnStmt>(S))
1910 hasReturns = true;
1911 return;
1912}
1913
1914void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1915 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001916 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001917 if (*CI) {
1918 RewriteTryReturnStmts(*CI);
1919 }
1920 if (isa<ReturnStmt>(S)) {
1921 SourceLocation startLoc = S->getLocStart();
1922 const char *startBuf = SM->getCharacterData(startLoc);
1923
1924 const char *semiBuf = strchr(startBuf, ';');
1925 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1926 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1927
1928 std::string buf;
1929 buf = "{ objc_exception_try_exit(&_stack); return";
1930
Benjamin Kramerd999b372010-02-14 14:14:16 +00001931 ReplaceText(startLoc, 6, buf);
1932 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001933 }
1934 return;
1935}
1936
1937void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1938 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001939 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001940 if (*CI) {
1941 RewriteSyncReturnStmts(*CI, syncExitBuf);
1942 }
1943 if (isa<ReturnStmt>(S)) {
1944 SourceLocation startLoc = S->getLocStart();
1945 const char *startBuf = SM->getCharacterData(startLoc);
1946
1947 const char *semiBuf = strchr(startBuf, ';');
1948 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1949 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1950
1951 std::string buf;
1952 buf = "{ objc_exception_try_exit(&_stack);";
1953 buf += syncExitBuf;
1954 buf += " return";
1955
Benjamin Kramerd999b372010-02-14 14:14:16 +00001956 ReplaceText(startLoc, 6, buf);
1957 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001958 }
1959 return;
1960}
1961
Steve Naroffb29b4272008-04-14 22:03:09 +00001962Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001963 // Get the start location and compute the semi location.
1964 SourceLocation startLoc = S->getLocStart();
1965 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001966
Steve Naroff75730982007-11-07 04:08:17 +00001967 assert((*startBuf == '@') && "bogus @try location");
1968
1969 std::string buf;
1970 // declare a new scope with two variables, _stack and _rethrow.
1971 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1972 buf += "int buf[18/*32-bit i386*/];\n";
1973 buf += "char *pointers[4];} _stack;\n";
1974 buf += "id volatile _rethrow = 0;\n";
1975 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001976 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001977
Benjamin Kramerd999b372010-02-14 14:14:16 +00001978 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Steve Naroff75730982007-11-07 04:08:17 +00001980 startLoc = S->getTryBody()->getLocEnd();
1981 startBuf = SM->getCharacterData(startLoc);
1982
1983 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001984
Steve Naroff75730982007-11-07 04:08:17 +00001985 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001986 if (S->getNumCatchStmts()) {
Steve Naroffc9ba1722008-07-16 15:31:30 +00001987 startLoc = startLoc.getFileLocWithOffset(1);
1988 buf = " /* @catch begin */ else {\n";
1989 buf += " id _caught = objc_exception_extract(&_stack);\n";
1990 buf += " objc_exception_try_enter (&_stack);\n";
1991 buf += " if (_setjmp(_stack.buf))\n";
1992 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1993 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001994
Benjamin Kramerd999b372010-02-14 14:14:16 +00001995 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001996 } else { /* no catch list */
1997 buf = "}\nelse {\n";
1998 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1999 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002000 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00002001 }
Steve Naroff75730982007-11-07 04:08:17 +00002002 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002003 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2004 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00002005 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00002006
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002007 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00002008 buf = "if ("; // we are generating code for the first catch clause
2009 else
2010 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002011 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00002012 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002013
Steve Naroff75730982007-11-07 04:08:17 +00002014 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00002015
Steve Naroff75730982007-11-07 04:08:17 +00002016 const char *lParenLoc = strchr(startBuf, '(');
2017
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002018 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00002019 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002020 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002021 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2022 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002023 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002024 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002025 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002026
Steve Naroffe12e6922008-02-01 20:02:07 +00002027 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002028 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002029 } else if (catchDecl) {
2030 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002031 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002032 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002033 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002034 } else if (const ObjCObjectPointerType *Ptr =
2035 t->getAs<ObjCObjectPointerType>()) {
2036 // Should be a pointer to a class.
2037 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2038 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002039 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002040 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002041 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002042 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002043 }
2044 }
2045 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002046 lastCatchBody = Catch->getCatchBody();
2047 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002048 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2049 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2050 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2051 assert((*rParenBuf == ')') && "bogus @catch paren location");
2052 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002053
Mike Stump1eb44332009-09-09 15:08:12 +00002054 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002055 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002056 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002057 } else {
Steve Naroff75730982007-11-07 04:08:17 +00002058 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002059 }
Steve Naroff75730982007-11-07 04:08:17 +00002060 }
2061 // Complete the catch list...
2062 if (lastCatchBody) {
2063 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002064 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2065 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002066
Steve Naroff378f47a2008-09-11 15:29:03 +00002067 // Insert the last (implicit) else clause *before* the right curly brace.
2068 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
2069 buf = "} /* last catch end */\n";
2070 buf += "else {\n";
2071 buf += " _rethrow = _caught;\n";
2072 buf += " objc_exception_try_exit(&_stack);\n";
2073 buf += "} } /* @catch end */\n";
2074 if (!S->getFinallyStmt())
2075 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002076 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002077
Steve Naroff75730982007-11-07 04:08:17 +00002078 // Set lastCurlyLoc
2079 lastCurlyLoc = lastCatchBody->getLocEnd();
2080 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002081 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002082 startLoc = finalStmt->getLocStart();
2083 startBuf = SM->getCharacterData(startLoc);
2084 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002085
Benjamin Kramerd999b372010-02-14 14:14:16 +00002086 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002087
Steve Naroff75730982007-11-07 04:08:17 +00002088 Stmt *body = finalStmt->getFinallyBody();
2089 SourceLocation startLoc = body->getLocStart();
2090 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002091 assert(*SM->getCharacterData(startLoc) == '{' &&
2092 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002093 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002094 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Steve Naroff75730982007-11-07 04:08:17 +00002096 startLoc = startLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002097 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Steve Naroff75730982007-11-07 04:08:17 +00002098 endLoc = endLoc.getFileLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002099 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002100
Steve Naroff75730982007-11-07 04:08:17 +00002101 // Set lastCurlyLoc
2102 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Steve Naroff8c565152008-12-05 17:03:39 +00002104 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002105 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002106 } else { /* no finally clause - make sure we synthesize an implicit one */
2107 buf = "{ /* implicit finally clause */\n";
2108 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2109 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2110 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002111 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002112
2113 // Now check for any return/continue/go statements within the @try.
2114 // The implicit finally clause won't called if the @try contains any
2115 // jump statements.
2116 bool hasReturns = false;
2117 HasReturnStmts(S->getTryBody(), hasReturns);
2118 if (hasReturns)
2119 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002120 }
2121 // Now emit the final closing curly brace...
2122 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002123 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002124 return 0;
2125}
2126
Mike Stump1eb44332009-09-09 15:08:12 +00002127// This can't be done with ReplaceStmt(S, ThrowExpr), since
2128// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002129// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002130Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002131 // Get the start location and compute the semi location.
2132 SourceLocation startLoc = S->getLocStart();
2133 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002134
Steve Naroff2bd03922007-11-07 15:32:26 +00002135 assert((*startBuf == '@') && "bogus @throw location");
2136
2137 std::string buf;
2138 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002139 if (S->getThrowExpr())
2140 buf = "objc_exception_throw(";
2141 else // add an implicit argument
2142 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002143
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002144 // handle "@ throw" correctly.
2145 const char *wBuf = strchr(startBuf, 'w');
2146 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002147 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002148
Steve Naroff2bd03922007-11-07 15:32:26 +00002149 const char *semiBuf = strchr(startBuf, ';');
2150 assert((*semiBuf == ';') && "@throw: can't find ';'");
2151 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002152 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002153 return 0;
2154}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002155
Steve Naroffb29b4272008-04-14 22:03:09 +00002156Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002157 // Create a new string expression.
2158 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002159 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002160 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002161 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002162 StringLiteral::Ascii, false,
2163 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002164 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002165
Chris Lattner07506182007-11-30 22:53:43 +00002166 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002167 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002168 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002169}
2170
Steve Naroffb29b4272008-04-14 22:03:09 +00002171Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002172 if (!SelGetUidFunctionDecl)
2173 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002174 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2175 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002176 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002177 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002178 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002179 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002180 StringLiteral::Ascii, false,
2181 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002182 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2183 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002184 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002185 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002186 return SelExp;
2187}
2188
Steve Naroffb29b4272008-04-14 22:03:09 +00002189CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002190 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2191 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002192 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002193 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Steve Naroffebf2b562007-10-23 23:50:29 +00002195 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002196 DeclRefExpr *DRE =
2197 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002198
Steve Naroffebf2b562007-10-23 23:50:29 +00002199 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002200 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002201 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002202 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002203 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002204
John McCall183700f2009-09-21 23:43:11 +00002205 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002206
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002207 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002208 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002209 FT->getCallResultType(*Context),
2210 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002211 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002212}
2213
Steve Naroffd5255f52007-11-01 13:24:47 +00002214static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2215 const char *&startRef, const char *&endRef) {
2216 while (startBuf < endBuf) {
2217 if (*startBuf == '<')
2218 startRef = startBuf; // mark the start.
2219 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002220 if (startRef && *startRef == '<') {
2221 endRef = startBuf; // mark the end.
2222 return true;
2223 }
2224 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002225 }
2226 startBuf++;
2227 }
2228 return false;
2229}
2230
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002231static void scanToNextArgument(const char *&argRef) {
2232 int angle = 0;
2233 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2234 if (*argRef == '<')
2235 angle++;
2236 else if (*argRef == '>')
2237 angle--;
2238 argRef++;
2239 }
2240 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2241}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002242
Steve Naroffb29b4272008-04-14 22:03:09 +00002243bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002244 if (T->isObjCQualifiedIdType())
2245 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002246 if (const PointerType *PT = T->getAs<PointerType>()) {
2247 if (PT->getPointeeType()->isObjCQualifiedIdType())
2248 return true;
2249 }
2250 if (T->isObjCObjectPointerType()) {
2251 T = T->getPointeeType();
2252 return T->isObjCQualifiedInterfaceType();
2253 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002254 if (T->isArrayType()) {
2255 QualType ElemTy = Context->getBaseElementType(T);
2256 return needToScanForQualifiers(ElemTy);
2257 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002258 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002259}
2260
Steve Naroff4f95b752008-07-29 18:15:38 +00002261void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2262 QualType Type = E->getType();
2263 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002264 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002265
Steve Naroffcda658e2008-11-19 21:15:47 +00002266 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2267 Loc = ECE->getLParenLoc();
2268 EndLoc = ECE->getRParenLoc();
2269 } else {
2270 Loc = E->getLocStart();
2271 EndLoc = E->getLocEnd();
2272 }
2273 // This will defend against trying to rewrite synthesized expressions.
2274 if (Loc.isInvalid() || EndLoc.isInvalid())
2275 return;
2276
Steve Naroff4f95b752008-07-29 18:15:38 +00002277 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002278 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002279 const char *startRef = 0, *endRef = 0;
2280 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2281 // Get the locations of the startRef, endRef.
2282 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2283 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2284 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002285 InsertText(LessLoc, "/*");
2286 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002287 }
2288 }
2289}
2290
Steve Naroffb29b4272008-04-14 22:03:09 +00002291void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002292 SourceLocation Loc;
2293 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002294 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002295 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2296 Loc = VD->getLocation();
2297 Type = VD->getType();
2298 }
2299 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2300 Loc = FD->getLocation();
2301 // Check for ObjC 'id' and class types that have been adorned with protocol
2302 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002303 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002304 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002305 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002306 if (!proto)
2307 return;
2308 Type = proto->getResultType();
2309 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002310 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2311 Loc = FD->getLocation();
2312 Type = FD->getType();
2313 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002314 else
2315 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002316
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002317 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002318 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002319
Steve Naroffd5255f52007-11-01 13:24:47 +00002320 const char *endBuf = SM->getCharacterData(Loc);
2321 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002322 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002323 startBuf--; // scan backward (from the decl location) for return type.
2324 const char *startRef = 0, *endRef = 0;
2325 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2326 // Get the locations of the startRef, endRef.
2327 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2328 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2329 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002330 InsertText(LessLoc, "/*");
2331 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002332 }
2333 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002334 if (!proto)
2335 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002336 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002337 const char *startBuf = SM->getCharacterData(Loc);
2338 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002339 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2340 if (needToScanForQualifiers(proto->getArgType(i))) {
2341 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Steve Naroffd5255f52007-11-01 13:24:47 +00002343 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002344 // scan forward (from the decl location) for argument types.
2345 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002346 const char *startRef = 0, *endRef = 0;
2347 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2348 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002349 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002350 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002351 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002352 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002353 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002354 InsertText(LessLoc, "/*");
2355 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002356 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002357 startBuf = ++endBuf;
2358 }
2359 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002360 // If the function name is derived from a macro expansion, then the
2361 // argument buffer will not follow the name. Need to speak with Chris.
2362 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002363 startBuf++; // scan forward (from the decl location) for argument types.
2364 startBuf++;
2365 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002366 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002367}
2368
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002369void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2370 QualType QT = ND->getType();
2371 const Type* TypePtr = QT->getAs<Type>();
2372 if (!isa<TypeOfExprType>(TypePtr))
2373 return;
2374 while (isa<TypeOfExprType>(TypePtr)) {
2375 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2376 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2377 TypePtr = QT->getAs<Type>();
2378 }
2379 // FIXME. This will not work for multiple declarators; as in:
2380 // __typeof__(a) b,c,d;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002381 std::string TypeAsString(QT.getAsString(Context->PrintingPolicy));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002382 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2383 const char *startBuf = SM->getCharacterData(DeclLoc);
2384 if (ND->getInit()) {
2385 std::string Name(ND->getNameAsString());
2386 TypeAsString += " " + Name + " = ";
2387 Expr *E = ND->getInit();
2388 SourceLocation startLoc;
2389 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2390 startLoc = ECE->getLParenLoc();
2391 else
2392 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002393 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002394 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002395 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002396 }
2397 else {
2398 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002399 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002400 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002401 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002402 }
2403}
2404
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002405// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002406void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002407 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002408 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002409 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002410 QualType getFuncType =
2411 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002412 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002413 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002414 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002415 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002416 SC_Extern,
2417 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002418}
2419
Steve Naroffb29b4272008-04-14 22:03:09 +00002420void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002421 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002422 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002423 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002424 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002425 return;
2426 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002427 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002428}
2429
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002430void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2431 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002432 const char *argPtr = TypeString.c_str();
2433 if (!strchr(argPtr, '^')) {
2434 Str += TypeString;
2435 return;
2436 }
2437 while (*argPtr) {
2438 Str += (*argPtr == '^' ? '*' : *argPtr);
2439 argPtr++;
2440 }
2441}
2442
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002443// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002444void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2445 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002446 QualType Type = VD->getType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002447 std::string TypeString(Type.getAsString(Context->PrintingPolicy));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002448 const char *argPtr = TypeString.c_str();
2449 int paren = 0;
2450 while (*argPtr) {
2451 switch (*argPtr) {
2452 case '(':
2453 Str += *argPtr;
2454 paren++;
2455 break;
2456 case ')':
2457 Str += *argPtr;
2458 paren--;
2459 break;
2460 case '^':
2461 Str += '*';
2462 if (paren == 1)
2463 Str += VD->getNameAsString();
2464 break;
2465 default:
2466 Str += *argPtr;
2467 break;
2468 }
2469 argPtr++;
2470 }
2471}
2472
2473
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002474void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2475 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2476 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2477 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2478 if (!proto)
2479 return;
2480 QualType Type = proto->getResultType();
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002481 std::string FdStr = Type.getAsString(Context->PrintingPolicy);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002482 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002483 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002484 FdStr += "(";
2485 unsigned numArgs = proto->getNumArgs();
2486 for (unsigned i = 0; i < numArgs; i++) {
2487 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002488 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002489 if (i+1 < numArgs)
2490 FdStr += ", ";
2491 }
2492 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002493 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002494 CurFunctionDeclToDeclareForBlock = 0;
2495}
2496
Steve Naroffc0a123c2008-03-11 17:37:02 +00002497// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002498void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002499 if (SuperContructorFunctionDecl)
2500 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002501 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002502 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002503 QualType argT = Context->getObjCIdType();
2504 assert(!argT.isNull() && "Can't find 'id' type");
2505 ArgTys.push_back(argT);
2506 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002507 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2508 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002509 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002510 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002511 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002512 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002513 SC_Extern,
2514 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002515}
2516
Steve Naroff09b266e2007-10-30 23:14:51 +00002517// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002518void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002519 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002520 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002521 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002522 assert(!argT.isNull() && "Can't find 'id' type");
2523 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002524 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002525 assert(!argT.isNull() && "Can't find 'SEL' type");
2526 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002527 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2528 &ArgTys[0], ArgTys.size(),
2529 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002530 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002531 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002532 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002533 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002534 SC_Extern,
2535 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002536}
2537
Steve Naroff874e2322007-11-15 10:28:18 +00002538// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002539void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002540 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002541 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002542 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002543 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002544 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002545 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2546 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2547 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002548 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002549 assert(!argT.isNull() && "Can't find 'SEL' type");
2550 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002551 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2552 &ArgTys[0], ArgTys.size(),
2553 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002554 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002555 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002556 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002557 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002558 SC_Extern,
2559 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002560}
2561
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002562// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002563void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002564 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002565 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002566 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002567 assert(!argT.isNull() && "Can't find 'id' type");
2568 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002569 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002570 assert(!argT.isNull() && "Can't find 'SEL' type");
2571 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002572 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2573 &ArgTys[0], ArgTys.size(),
2574 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002575 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002576 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002577 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002578 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002579 SC_Extern,
2580 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002581}
2582
Mike Stump1eb44332009-09-09 15:08:12 +00002583// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002584// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002585void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002586 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002587 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002588 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002589 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002590 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002591 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002592 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2593 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2594 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002595 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002596 assert(!argT.isNull() && "Can't find 'SEL' type");
2597 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002598 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2599 &ArgTys[0], ArgTys.size(),
2600 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002601 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002602 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002603 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002604 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002605 SC_Extern,
2606 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002607}
2608
Steve Naroff1284db82008-05-08 22:02:18 +00002609// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002610void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002611 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002612 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002613 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002614 assert(!argT.isNull() && "Can't find 'id' type");
2615 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002616 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002617 assert(!argT.isNull() && "Can't find 'SEL' type");
2618 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002619 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2620 &ArgTys[0], ArgTys.size(),
2621 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002622 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002623 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002624 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002625 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002626 SC_Extern,
2627 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002628}
2629
Steve Naroff09b266e2007-10-30 23:14:51 +00002630// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002631void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002632 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002633 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002634 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002635 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2636 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002637 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002638 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002639 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002640 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002641 SC_Extern,
2642 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002643}
2644
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002645// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2646void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2647 IdentifierInfo *getSuperClassIdent =
2648 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002649 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002650 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002651 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2652 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002653 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002654 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002655 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002656 getSuperClassIdent,
2657 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002658 SC_Extern,
2659 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002660 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002661}
2662
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002663// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002664void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002665 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002666 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002667 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002668 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2669 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002670 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002671 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002672 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002673 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002674 SC_Extern,
2675 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002676}
2677
Steve Naroffb29b4272008-04-14 22:03:09 +00002678Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002679 QualType strType = getConstantStringStructType();
2680
2681 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002682
2683 std::string tmpName = InFileName;
2684 unsigned i;
2685 for (i=0; i < tmpName.length(); i++) {
2686 char c = tmpName.at(i);
2687 // replace any non alphanumeric characters with '_'.
2688 if (!isalpha(c) && (c < '0' || c > '9'))
2689 tmpName[i] = '_';
2690 }
2691 S += tmpName;
2692 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002693 S += utostr(NumObjCStringLiterals++);
2694
Steve Naroffba92b2e2008-03-27 22:29:16 +00002695 Preamble += "static __NSConstantStringImpl " + S;
2696 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2697 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002698 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002699 std::string prettyBufS;
2700 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002701 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2702 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002703 Preamble += prettyBuf.str();
2704 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002705 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002706
2707 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002708 SourceLocation(), &Context->Idents.get(S),
2709 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002710 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2711 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002712 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002713 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002714 VK_RValue, OK_Ordinary,
2715 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002716 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002717 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002718 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002719 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002720 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002721 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002722}
2723
Steve Naroff874e2322007-11-15 10:28:18 +00002724// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002725QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002726 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002727 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002728 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002729 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002730 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002731
Steve Naroff874e2322007-11-15 10:28:18 +00002732 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002733 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002734 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002735 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002736
Steve Naroff874e2322007-11-15 10:28:18 +00002737 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002738 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002739 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002740 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002741 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002742 FieldTypes[i], 0,
2743 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002744 /*Mutable=*/false,
2745 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002746 }
Mike Stump1eb44332009-09-09 15:08:12 +00002747
Douglas Gregor838db382010-02-11 01:19:42 +00002748 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002749 }
2750 return Context->getTagDeclType(SuperStructDecl);
2751}
2752
Steve Naroffb29b4272008-04-14 22:03:09 +00002753QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002754 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002755 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002756 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002757 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002758 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002759
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002760 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002761 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002762 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002763 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002764 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002765 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002766 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002767 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002768
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002769 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002770 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002771 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2772 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002773 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002774 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002775 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002776 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002777 /*Mutable=*/true,
2778 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002779 }
2780
Douglas Gregor838db382010-02-11 01:19:42 +00002781 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002782 }
2783 return Context->getTagDeclType(ConstantStringDecl);
2784}
2785
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002786Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2787 SourceLocation StartLoc,
2788 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002789 if (!SelGetUidFunctionDecl)
2790 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002791 if (!MsgSendFunctionDecl)
2792 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002793 if (!MsgSendSuperFunctionDecl)
2794 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002795 if (!MsgSendStretFunctionDecl)
2796 SynthMsgSendStretFunctionDecl();
2797 if (!MsgSendSuperStretFunctionDecl)
2798 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002799 if (!MsgSendFpretFunctionDecl)
2800 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002801 if (!GetClassFunctionDecl)
2802 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002803 if (!GetSuperClassFunctionDecl)
2804 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002805 if (!GetMetaClassFunctionDecl)
2806 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002807
Steve Naroff874e2322007-11-15 10:28:18 +00002808 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002809 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2810 // May need to use objc_msgSend_stret() as well.
2811 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002812 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2813 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002814 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002815 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002816 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002817 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002818 }
Mike Stump1eb44332009-09-09 15:08:12 +00002819
Steve Naroff934f2762007-10-24 22:48:43 +00002820 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002821 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002822 switch (Exp->getReceiverKind()) {
2823 case ObjCMessageExpr::SuperClass: {
2824 MsgSendFlavor = MsgSendSuperFunctionDecl;
2825 if (MsgSendStretFlavor)
2826 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2827 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002828
Douglas Gregor04badcf2010-04-21 00:45:42 +00002829 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002830
Chris Lattner5f9e2722011-07-23 10:55:15 +00002831 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002832
Douglas Gregor04badcf2010-04-21 00:45:42 +00002833 // set the receiver to self, the first argument to all methods.
2834 InitExprs.push_back(
2835 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002836 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002837 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002838 Context->getObjCIdType(),
2839 VK_RValue,
2840 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002841 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002842
Douglas Gregor04badcf2010-04-21 00:45:42 +00002843 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002844 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002845 QualType argType = Context->getPointerType(Context->CharTy);
2846 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002847 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002848 StringLiteral::Ascii, false,
2849 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2851 &ClsExprs[0],
2852 ClsExprs.size(),
2853 StartLoc,
2854 EndLoc);
2855 // (Class)objc_getClass("CurrentClass")
2856 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2857 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002858 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002859 ClsExprs.clear();
2860 ClsExprs.push_back(ArgExpr);
2861 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2862 &ClsExprs[0], ClsExprs.size(),
2863 StartLoc, EndLoc);
2864
2865 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2866 // To turn off a warning, type-cast to 'id'
2867 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2868 NoTypeInfoCStyleCastExpr(Context,
2869 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002870 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002871 // struct objc_super
2872 QualType superType = getSuperStructType();
2873 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002874
Douglas Gregor04badcf2010-04-21 00:45:42 +00002875 if (LangOpts.Microsoft) {
2876 SynthSuperContructorFunctionDecl();
2877 // Simulate a contructor call...
2878 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002879 superType, VK_LValue,
2880 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002881 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2882 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002883 superType, VK_LValue,
2884 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002885 // The code for super is a little tricky to prevent collision with
2886 // the structure definition in the header. The rewriter has it's own
2887 // internal definition (__rw_objc_super) that is uses. This is why
2888 // we need the cast below. For example:
2889 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2890 //
John McCall2de56d12010-08-25 11:45:40 +00002891 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002892 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002893 VK_RValue, OK_Ordinary,
2894 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002895 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2896 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002897 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002898 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002899 // (struct objc_super) { <exprs from above> }
2900 InitListExpr *ILE =
2901 new (Context) InitListExpr(*Context, SourceLocation(),
2902 &InitExprs[0], InitExprs.size(),
2903 SourceLocation());
2904 TypeSourceInfo *superTInfo
2905 = Context->getTrivialTypeSourceInfo(superType);
2906 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002907 superType, VK_LValue,
2908 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002909 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002910 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002911 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002912 VK_RValue, OK_Ordinary,
2913 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002914 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002915 MsgExprs.push_back(SuperRep);
2916 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002917 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002918
2919 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002920 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002921 QualType argType = Context->getPointerType(Context->CharTy);
2922 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002923 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002924 IdentifierInfo *clsName = Class->getIdentifier();
2925 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002926 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002927 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002928 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002929 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2930 &ClsExprs[0],
2931 ClsExprs.size(),
2932 StartLoc, EndLoc);
2933 MsgExprs.push_back(Cls);
2934 break;
2935 }
2936
2937 case ObjCMessageExpr::SuperInstance:{
2938 MsgSendFlavor = MsgSendSuperFunctionDecl;
2939 if (MsgSendStretFlavor)
2940 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2941 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2942 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002943 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002944
2945 InitExprs.push_back(
2946 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002947 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002948 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002949 Context->getObjCIdType(),
2950 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002951 ); // set the 'receiver'.
2952
2953 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002954 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 QualType argType = Context->getPointerType(Context->CharTy);
2956 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002957 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002958 StringLiteral::Ascii, false, argType,
2959 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002960 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2961 &ClsExprs[0],
2962 ClsExprs.size(),
2963 StartLoc, EndLoc);
2964 // (Class)objc_getClass("CurrentClass")
2965 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2966 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002967 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002968 ClsExprs.clear();
2969 ClsExprs.push_back(ArgExpr);
2970 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2971 &ClsExprs[0], ClsExprs.size(),
2972 StartLoc, EndLoc);
2973
2974 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2975 // To turn off a warning, type-cast to 'id'
2976 InitExprs.push_back(
2977 // set 'super class', using class_getSuperclass().
2978 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002979 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002980 // struct objc_super
2981 QualType superType = getSuperStructType();
2982 Expr *SuperRep;
2983
2984 if (LangOpts.Microsoft) {
2985 SynthSuperContructorFunctionDecl();
2986 // Simulate a contructor call...
2987 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002988 superType, VK_LValue,
2989 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002990 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2991 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002992 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002993 // The code for super is a little tricky to prevent collision with
2994 // the structure definition in the header. The rewriter has it's own
2995 // internal definition (__rw_objc_super) that is uses. This is why
2996 // we need the cast below. For example:
2997 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2998 //
John McCall2de56d12010-08-25 11:45:40 +00002999 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003000 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003001 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003002 SourceLocation());
3003 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3004 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00003005 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003006 } else {
3007 // (struct objc_super) { <exprs from above> }
3008 InitListExpr *ILE =
3009 new (Context) InitListExpr(*Context, SourceLocation(),
3010 &InitExprs[0], InitExprs.size(),
3011 SourceLocation());
3012 TypeSourceInfo *superTInfo
3013 = Context->getTrivialTypeSourceInfo(superType);
3014 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003015 superType, VK_RValue, ILE,
3016 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003017 }
3018 MsgExprs.push_back(SuperRep);
3019 break;
3020 }
3021
3022 case ObjCMessageExpr::Instance: {
3023 // Remove all type-casts because it may contain objc-style types; e.g.
3024 // Foo<Proto> *.
3025 Expr *recExpr = Exp->getInstanceReceiver();
3026 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3027 recExpr = CE->getSubExpr();
3028 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00003029 CK_BitCast, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003030 MsgExprs.push_back(recExpr);
3031 break;
3032 }
3033 }
3034
Steve Naroffbeaf2992007-11-03 11:27:19 +00003035 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003036 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003037 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003038 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003039 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003040 StringLiteral::Ascii, false,
3041 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003042 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003043 &SelExprs[0], SelExprs.size(),
3044 StartLoc,
3045 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003046 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003047
Steve Naroff934f2762007-10-24 22:48:43 +00003048 // Now push any user supplied arguments.
3049 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003050 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003051 // Make all implicit casts explicit...ICE comes in handy:-)
3052 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3053 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003054 QualType type = ICE->getType();
3055 if (needToScanForQualifiers(type))
3056 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003057 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003058 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003059 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003060 CastKind CK;
3061 if (SubExpr->getType()->isIntegralType(*Context) &&
3062 type->isBooleanType()) {
3063 CK = CK_IntegralToBoolean;
3064 } else if (type->isObjCObjectPointerType()) {
3065 if (SubExpr->getType()->isBlockPointerType()) {
3066 CK = CK_BlockPointerToObjCPointerCast;
3067 } else if (SubExpr->getType()->isPointerType()) {
3068 CK = CK_CPointerToObjCPointerCast;
3069 } else {
3070 CK = CK_BitCast;
3071 }
3072 } else {
3073 CK = CK_BitCast;
3074 }
3075
3076 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003077 }
3078 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003079 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003080 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003081 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003082 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003083 CastKind CK;
3084 if (userExpr->getType()->isIntegralType(*Context)) {
3085 CK = CK_IntegralToPointer;
3086 } else if (userExpr->getType()->isBlockPointerType()) {
3087 CK = CK_BlockPointerToObjCPointerCast;
3088 } else if (userExpr->getType()->isPointerType()) {
3089 CK = CK_CPointerToObjCPointerCast;
3090 } else {
3091 CK = CK_BitCast;
3092 }
John McCall9d125032010-01-15 18:39:57 +00003093 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003094 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003095 }
Mike Stump1eb44332009-09-09 15:08:12 +00003096 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003097 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003098 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3099 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003100 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003101 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003102 }
Steve Naroffab972d32007-11-04 22:37:50 +00003103 // Generate the funky cast.
3104 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003105 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003106 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003107
Steve Naroffab972d32007-11-04 22:37:50 +00003108 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003109 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3110 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3111 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003112 ArgTypes.push_back(Context->getObjCIdType());
3113 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003114 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003115 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003116 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3117 E = OMD->param_end(); PI != E; ++PI) {
3118 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003119 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003120 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003121 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003122 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003123 ArgTypes.push_back(t);
3124 }
Chris Lattner89951a82009-02-20 18:43:26 +00003125 returnType = OMD->getResultType()->isObjCQualifiedIdType()
3126 ? Context->getObjCIdType() : OMD->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003127 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003128 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003129 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003130 }
3131 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003132 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003133
Steve Naroffab972d32007-11-04 22:37:50 +00003134 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003135 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003136 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003137
Mike Stump1eb44332009-09-09 15:08:12 +00003138 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003139 // If we don't do this cast, we get the following bizarre warning/note:
3140 // xx.m:13: warning: function called through a non-compatible type
3141 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003142 cast = NoTypeInfoCStyleCastExpr(Context,
3143 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003144 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Steve Naroffab972d32007-11-04 22:37:50 +00003146 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003147 QualType castType =
3148 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3149 // If we don't have a method decl, force a variadic cast.
3150 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003151 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003152 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003153 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003154
3155 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003156 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003157
John McCall183700f2009-09-21 23:43:11 +00003158 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003159 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003160 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003161 FT->getResultType(), VK_RValue,
3162 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003163 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003164 if (MsgSendStretFlavor) {
3165 // We have the method which returns a struct/union. Must also generate
3166 // call to objc_msgSend_stret and hang both varieties on a conditional
3167 // expression which dictate which one to envoke depending on size of
3168 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003170 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003171 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003172 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003173 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003174 cast = NoTypeInfoCStyleCastExpr(Context,
3175 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003176 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003177 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003178 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3179 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003180 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003181 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003182 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003183
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003184 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003185 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003186
John McCall183700f2009-09-21 23:43:11 +00003187 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003188 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003189 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003190 FT->getResultType(), VK_RValue,
3191 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003192
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003193 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003194 UnaryExprOrTypeTraitExpr *sizeofExpr =
3195 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3196 Context->getTrivialTypeSourceInfo(returnType),
3197 Context->getSizeType(), SourceLocation(),
3198 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003199 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3200 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3201 // For X86 it is more complicated and some kind of target specific routine
3202 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003203 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003204 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003205 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3206 llvm::APInt(IntSize, 8),
3207 Context->IntTy,
3208 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003209 BinaryOperator *lessThanExpr =
3210 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3211 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003212 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003213 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003214 new (Context) ConditionalOperator(lessThanExpr,
3215 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003216 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003217 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003218 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3219 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003220 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003221 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003222 return ReplacingStmt;
3223}
3224
Steve Naroffb29b4272008-04-14 22:03:09 +00003225Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003226 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3227 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003228
Steve Naroff934f2762007-10-24 22:48:43 +00003229 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003230 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003231
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003232 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003233 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003234}
3235
Steve Naroff621edce2009-04-29 16:37:50 +00003236// typedef struct objc_object Protocol;
3237QualType RewriteObjC::getProtocolType() {
3238 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003239 TypeSourceInfo *TInfo
3240 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003241 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003242 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003243 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003244 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003245 }
3246 return Context->getTypeDeclType(ProtocolTypeDecl);
3247}
3248
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003249/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003250/// a synthesized/forward data reference (to the protocol's metadata).
3251/// The forward references (and metadata) are generated in
3252/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003253Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003254 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3255 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003256 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003257 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003258 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003259 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3260 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003261 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003262 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003263 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003264 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003265 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003266 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003267 ReplaceStmt(Exp, castExpr);
3268 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003269 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003270 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003271
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003272}
3273
Mike Stump1eb44332009-09-09 15:08:12 +00003274bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003275 const char *endBuf) {
3276 while (startBuf < endBuf) {
3277 if (*startBuf == '#') {
3278 // Skip whitespace.
3279 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3280 ;
3281 if (!strncmp(startBuf, "if", strlen("if")) ||
3282 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3283 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3284 !strncmp(startBuf, "define", strlen("define")) ||
3285 !strncmp(startBuf, "undef", strlen("undef")) ||
3286 !strncmp(startBuf, "else", strlen("else")) ||
3287 !strncmp(startBuf, "elif", strlen("elif")) ||
3288 !strncmp(startBuf, "endif", strlen("endif")) ||
3289 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3290 !strncmp(startBuf, "include", strlen("include")) ||
3291 !strncmp(startBuf, "import", strlen("import")) ||
3292 !strncmp(startBuf, "include_next", strlen("include_next")))
3293 return true;
3294 }
3295 startBuf++;
3296 }
3297 return false;
3298}
3299
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003300/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003301/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003302void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003303 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003304 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003305 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003306 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003307 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003308 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003309 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003310 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003311 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003312 SourceLocation LocStart = CDecl->getLocStart();
3313 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003314
Steve Narofffea763e82007-11-14 19:25:57 +00003315 const char *startBuf = SM->getCharacterData(LocStart);
3316 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003317
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003318 // If no ivars and no root or if its root, directly or indirectly,
3319 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003320 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3321 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003322 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003323 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003324 return;
3325 }
Mike Stump1eb44332009-09-09 15:08:12 +00003326
3327 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003328 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003329 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003330 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003331 if (LangOpts.Microsoft)
3332 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003333
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003334 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003335 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003336 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003337 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003338 // If the buffer contains preprocessor directives, we do more fine-grained
3339 // rewrites. This is intended to fix code that looks like (which occurs in
3340 // NSURL.h, for example):
3341 //
3342 // #ifdef XYZ
3343 // @interface Foo : NSObject
3344 // #else
3345 // @interface FooBar : NSObject
3346 // #endif
3347 // {
3348 // int i;
3349 // }
3350 // @end
3351 //
3352 // This clause is segregated to avoid breaking the common case.
3353 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003354 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00003355 CDecl->getClassLoc();
3356 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003357 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003358
Chris Lattnercafeb352009-02-20 18:18:36 +00003359 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003360 // advance to the end of the referenced protocols.
3361 while (endHeader < cursor && *endHeader != '>') endHeader++;
3362 endHeader++;
3363 }
3364 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003365 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003366 } else {
3367 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003368 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003369 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003370 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003371 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003372 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003373 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003374 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003375 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003376
Steve Narofffea763e82007-11-14 19:25:57 +00003377 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003378 SourceLocation OnePastCurly =
3379 LocStart.getFileLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003380 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003381 }
3382 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003383
Steve Narofffea763e82007-11-14 19:25:57 +00003384 // Now comment out any visibility specifiers.
3385 while (cursor < endBuf) {
3386 if (*cursor == '@') {
3387 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003388 // Skip whitespace.
3389 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3390 /*scan*/;
3391
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003392 // FIXME: presence of @public, etc. inside comment results in
3393 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003394 if (!strncmp(cursor, "public", strlen("public")) ||
3395 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003396 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003397 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003398 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003399 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003400 // FIXME: If there are cases where '<' is used in ivar declaration part
3401 // of user code, then scan the ivar list and use needToScanForQualifiers
3402 // for type checking.
3403 else if (*cursor == '<') {
3404 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003405 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003406 cursor = strchr(cursor, '>');
3407 cursor++;
3408 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003409 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003410 } else if (*cursor == '^') { // rewrite block specifier.
3411 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003412 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003413 }
Steve Narofffea763e82007-11-14 19:25:57 +00003414 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003415 }
Steve Narofffea763e82007-11-14 19:25:57 +00003416 // Don't forget to add a ';'!!
Benjamin Kramerd999b372010-02-14 14:14:16 +00003417 InsertText(LocEnd.getFileLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003418 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003419 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003420 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003421 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003422 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003423 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003424 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003425 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003426 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003427 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003428 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003429 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003430}
3431
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003432// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003433/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003434template<typename MethodIterator>
3435void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3436 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003437 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003438 StringRef prefix,
3439 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003440 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003441 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003442
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003443 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003444 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003445 SEL _cmd;
3446 char *method_types;
3447 void *_imp;
3448 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003449 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003450 Result += "\nstruct _objc_method {\n";
3451 Result += "\tSEL _cmd;\n";
3452 Result += "\tchar *method_types;\n";
3453 Result += "\tvoid *_imp;\n";
3454 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003455
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003456 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003457 }
Mike Stump1eb44332009-09-09 15:08:12 +00003458
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003459 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003460
Steve Naroff946a6932008-03-11 00:12:29 +00003461 /* struct {
3462 struct _objc_method_list *next_method;
3463 int method_count;
3464 struct _objc_method method_list[];
3465 }
3466 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003467 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003468 Result += "\nstatic struct {\n";
3469 Result += "\tstruct _objc_method_list *next_method;\n";
3470 Result += "\tint method_count;\n";
3471 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003472 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003473 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003474 Result += prefix;
3475 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3476 Result += "_METHODS_";
3477 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003478 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003479 Result += IsInstanceMethod ? "inst" : "cls";
3480 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003481 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003482
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003483 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003484 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003485 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003486 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003487 Result += "\", \"";
3488 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003489 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003490 Result += MethodInternalNames[*MethodBegin];
3491 Result += "}\n";
3492 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3493 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003494 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003495 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003496 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003497 Result += "\", \"";
3498 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003499 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003500 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003501 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003502 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003503 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003504}
3505
Steve Naroff621edce2009-04-29 16:37:50 +00003506/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003507void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003508RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3509 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003510 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003511
3512 // Output struct protocol_methods holder of method selector and type.
3513 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3514 /* struct protocol_methods {
3515 SEL _cmd;
3516 char *method_types;
3517 }
3518 */
3519 Result += "\nstruct _protocol_methods {\n";
3520 Result += "\tstruct objc_selector *_cmd;\n";
3521 Result += "\tchar *method_types;\n";
3522 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003523
Steve Naroff621edce2009-04-29 16:37:50 +00003524 objc_protocol_methods = true;
3525 }
3526 // Do not synthesize the protocol more than once.
3527 if (ObjCSynthesizedProtocols.count(PDecl))
3528 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003529
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003530 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3531 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3532 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003533 /* struct _objc_protocol_method_list {
3534 int protocol_method_count;
3535 struct protocol_methods protocols[];
3536 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003537 */
Steve Naroff621edce2009-04-29 16:37:50 +00003538 Result += "\nstatic struct {\n";
3539 Result += "\tint protocol_method_count;\n";
3540 Result += "\tstruct _protocol_methods protocol_methods[";
3541 Result += utostr(NumMethods);
3542 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3543 Result += PDecl->getNameAsString();
3544 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3545 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003546
Steve Naroff621edce2009-04-29 16:37:50 +00003547 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003548 for (ObjCProtocolDecl::instmeth_iterator
3549 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003550 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003551 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003552 Result += "\t ,{{(struct objc_selector *)\"";
3553 else
3554 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003555 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003556 std::string MethodTypeString;
3557 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3558 Result += "\", \"";
3559 Result += MethodTypeString;
3560 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003561 }
Steve Naroff621edce2009-04-29 16:37:50 +00003562 Result += "\t }\n};\n";
3563 }
Mike Stump1eb44332009-09-09 15:08:12 +00003564
Steve Naroff621edce2009-04-29 16:37:50 +00003565 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003566 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3567 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003568 if (NumMethods > 0) {
3569 /* struct _objc_protocol_method_list {
3570 int protocol_method_count;
3571 struct protocol_methods protocols[];
3572 }
3573 */
3574 Result += "\nstatic struct {\n";
3575 Result += "\tint protocol_method_count;\n";
3576 Result += "\tstruct _protocol_methods protocol_methods[";
3577 Result += utostr(NumMethods);
3578 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3579 Result += PDecl->getNameAsString();
3580 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3581 "{\n\t";
3582 Result += utostr(NumMethods);
3583 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003584
Steve Naroff621edce2009-04-29 16:37:50 +00003585 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003586 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003587 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003588 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003589 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003590 Result += "\t ,{{(struct objc_selector *)\"";
3591 else
3592 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003593 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003594 std::string MethodTypeString;
3595 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3596 Result += "\", \"";
3597 Result += MethodTypeString;
3598 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003599 }
Steve Naroff621edce2009-04-29 16:37:50 +00003600 Result += "\t }\n};\n";
3601 }
3602
3603 // Output:
3604 /* struct _objc_protocol {
3605 // Objective-C 1.0 extensions
3606 struct _objc_protocol_extension *isa;
3607 char *protocol_name;
3608 struct _objc_protocol **protocol_list;
3609 struct _objc_protocol_method_list *instance_methods;
3610 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003611 };
Steve Naroff621edce2009-04-29 16:37:50 +00003612 */
3613 static bool objc_protocol = false;
3614 if (!objc_protocol) {
3615 Result += "\nstruct _objc_protocol {\n";
3616 Result += "\tstruct _objc_protocol_extension *isa;\n";
3617 Result += "\tchar *protocol_name;\n";
3618 Result += "\tstruct _objc_protocol **protocol_list;\n";
3619 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3620 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003621 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003622
Steve Naroff621edce2009-04-29 16:37:50 +00003623 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003624 }
Mike Stump1eb44332009-09-09 15:08:12 +00003625
Steve Naroff621edce2009-04-29 16:37:50 +00003626 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3627 Result += PDecl->getNameAsString();
3628 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3629 "{\n\t0, \"";
3630 Result += PDecl->getNameAsString();
3631 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003632 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003633 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3634 Result += PDecl->getNameAsString();
3635 Result += ", ";
3636 }
3637 else
3638 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003639 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003640 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3641 Result += PDecl->getNameAsString();
3642 Result += "\n";
3643 }
3644 else
3645 Result += "0\n";
3646 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003647
Steve Naroff621edce2009-04-29 16:37:50 +00003648 // Mark this protocol as having been generated.
3649 if (!ObjCSynthesizedProtocols.insert(PDecl))
3650 assert(false && "protocol already synthesized");
3651
3652}
3653
3654void RewriteObjC::
3655RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003656 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003657 std::string &Result) {
3658 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Steve Naroff621edce2009-04-29 16:37:50 +00003660 for (unsigned i = 0; i != Protocols.size(); i++)
3661 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3662
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003663 // Output the top lovel protocol meta-data for the class.
3664 /* struct _objc_protocol_list {
3665 struct _objc_protocol_list *next;
3666 int protocol_count;
3667 struct _objc_protocol *class_protocols[];
3668 }
3669 */
3670 Result += "\nstatic struct {\n";
3671 Result += "\tstruct _objc_protocol_list *next;\n";
3672 Result += "\tint protocol_count;\n";
3673 Result += "\tstruct _objc_protocol *class_protocols[";
3674 Result += utostr(Protocols.size());
3675 Result += "];\n} _OBJC_";
3676 Result += prefix;
3677 Result += "_PROTOCOLS_";
3678 Result += ClassName;
3679 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3680 "{\n\t0, ";
3681 Result += utostr(Protocols.size());
3682 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003683
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003684 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003685 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003686 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003687
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003688 for (unsigned i = 1; i != Protocols.size(); i++) {
3689 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003690 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003691 Result += "\n";
3692 }
3693 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003694}
3695
Steve Naroff621edce2009-04-29 16:37:50 +00003696
Mike Stump1eb44332009-09-09 15:08:12 +00003697/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003698/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003699void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003700 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003701 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003702 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003703 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003704 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003705 CDecl = CDecl->getNextClassCategory())
3706 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3707 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003708
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003709 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003710 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003711 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003712
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003713 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003714 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003715 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003716
3717 // If any of our property implementations have associated getters or
3718 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003719 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3720 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003721 Prop != PropEnd; ++Prop) {
3722 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3723 continue;
3724 if (!(*Prop)->getPropertyIvarDecl())
3725 continue;
3726 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3727 if (!PD)
3728 continue;
3729 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3730 InstanceMethods.push_back(Getter);
3731 if (PD->isReadOnly())
3732 continue;
3733 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3734 InstanceMethods.push_back(Setter);
3735 }
3736 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003737 true, "CATEGORY_", FullCategoryName.c_str(),
3738 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003739
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003740 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003741 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003742 false, "CATEGORY_", FullCategoryName.c_str(),
3743 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003745 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003746 // Null CDecl is case of a category implementation with no category interface
3747 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003748 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003749 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003750 /* struct _objc_category {
3751 char *category_name;
3752 char *class_name;
3753 struct _objc_method_list *instance_methods;
3754 struct _objc_method_list *class_methods;
3755 struct _objc_protocol_list *protocols;
3756 // Objective-C 1.0 extensions
3757 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003758 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003759 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003760 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003761 */
Mike Stump1eb44332009-09-09 15:08:12 +00003762
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003763 static bool objc_category = false;
3764 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003765 Result += "\nstruct _objc_category {\n";
3766 Result += "\tchar *category_name;\n";
3767 Result += "\tchar *class_name;\n";
3768 Result += "\tstruct _objc_method_list *instance_methods;\n";
3769 Result += "\tstruct _objc_method_list *class_methods;\n";
3770 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003771 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003772 Result += "\tstruct _objc_property_list *instance_properties;\n";
3773 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003774 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003775 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003776 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3777 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003778 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003779 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003780 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003781 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003782 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003783
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003784 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003785 Result += "\t, (struct _objc_method_list *)"
3786 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3787 Result += FullCategoryName;
3788 Result += "\n";
3789 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003790 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003791 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003792 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003793 Result += "\t, (struct _objc_method_list *)"
3794 "&_OBJC_CATEGORY_CLASS_METHODS_";
3795 Result += FullCategoryName;
3796 Result += "\n";
3797 }
3798 else
3799 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003800
Chris Lattnercafeb352009-02-20 18:18:36 +00003801 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003802 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003803 Result += FullCategoryName;
3804 Result += "\n";
3805 }
3806 else
3807 Result += "\t, 0\n";
3808 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003809}
3810
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003811/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3812/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003813void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003814 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003815 if (ivar->isBitField()) {
3816 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3817 // place all bitfields at offset 0.
3818 Result += "0";
3819 } else {
3820 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003821 Result += ivar->getContainingInterface()->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003822 if (LangOpts.Microsoft)
3823 Result += "_IMPL";
3824 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003825 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003826 Result += ")";
3827 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003828}
3829
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003830//===----------------------------------------------------------------------===//
3831// Meta Data Emission
3832//===----------------------------------------------------------------------===//
3833
Steve Naroffb29b4272008-04-14 22:03:09 +00003834void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003835 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003836 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003837
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003838 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003839 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003840 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003841 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003842 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003843 }
Mike Stump1eb44332009-09-09 15:08:12 +00003844
Chris Lattnerbe6df082007-12-12 07:56:42 +00003845 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003846 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003847 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003848 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003849 if (NumIvars > 0) {
3850 static bool objc_ivar = false;
3851 if (!objc_ivar) {
3852 /* struct _objc_ivar {
3853 char *ivar_name;
3854 char *ivar_type;
3855 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003856 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003857 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003858 Result += "\nstruct _objc_ivar {\n";
3859 Result += "\tchar *ivar_name;\n";
3860 Result += "\tchar *ivar_type;\n";
3861 Result += "\tint ivar_offset;\n";
3862 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003864 objc_ivar = true;
3865 }
3866
Steve Naroff946a6932008-03-11 00:12:29 +00003867 /* struct {
3868 int ivar_count;
3869 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003870 };
Steve Naroff946a6932008-03-11 00:12:29 +00003871 */
Mike Stump1eb44332009-09-09 15:08:12 +00003872 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003873 Result += "\tint ivar_count;\n";
3874 Result += "\tstruct _objc_ivar ivar_list[";
3875 Result += utostr(NumIvars);
3876 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003877 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003878 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003879 "{\n\t";
3880 Result += utostr(NumIvars);
3881 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003882
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003883 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003884 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003885 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003886 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003887 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003888 IV != IVEnd; ++IV)
3889 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003890 IVI = IDecl->ivar_begin();
3891 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003892 } else {
3893 IVI = CDecl->ivar_begin();
3894 IVE = CDecl->ivar_end();
3895 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003896 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003897 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003898 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003899 std::string TmpString, StrEncoding;
3900 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3901 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003902 Result += StrEncoding;
3903 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003904 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003905 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003906 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003907 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003908 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003909 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003910 std::string TmpString, StrEncoding;
3911 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3912 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003913 Result += StrEncoding;
3914 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003915 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003916 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003917 }
Mike Stump1eb44332009-09-09 15:08:12 +00003918
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003920 }
Mike Stump1eb44332009-09-09 15:08:12 +00003921
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003922 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003923 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003924 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003925
3926 // If any of our property implementations have associated getters or
3927 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003928 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3929 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003930 Prop != PropEnd; ++Prop) {
3931 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3932 continue;
3933 if (!(*Prop)->getPropertyIvarDecl())
3934 continue;
3935 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3936 if (!PD)
3937 continue;
3938 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003939 if (!Getter->isDefined())
3940 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003941 if (PD->isReadOnly())
3942 continue;
3943 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003944 if (!Setter->isDefined())
3945 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003946 }
3947 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003948 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003949
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003950 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003951 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003952 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003953
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003954 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003955 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003956 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003957
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003958 // Declaration of class/meta-class metadata
3959 /* struct _objc_class {
3960 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003961 const char *super_class_name;
3962 char *name;
3963 long version;
3964 long info;
3965 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003966 struct _objc_ivar_list *ivars;
3967 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003968 struct objc_cache *cache;
3969 struct objc_protocol_list *protocols;
3970 const char *ivar_layout;
3971 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003972 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003973 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003974 static bool objc_class = false;
3975 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003976 Result += "\nstruct _objc_class {\n";
3977 Result += "\tstruct _objc_class *isa;\n";
3978 Result += "\tconst char *super_class_name;\n";
3979 Result += "\tchar *name;\n";
3980 Result += "\tlong version;\n";
3981 Result += "\tlong info;\n";
3982 Result += "\tlong instance_size;\n";
3983 Result += "\tstruct _objc_ivar_list *ivars;\n";
3984 Result += "\tstruct _objc_method_list *methods;\n";
3985 Result += "\tstruct objc_cache *cache;\n";
3986 Result += "\tstruct _objc_protocol_list *protocols;\n";
3987 Result += "\tconst char *ivar_layout;\n";
3988 Result += "\tstruct _objc_class_ext *ext;\n";
3989 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003990 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003991 }
Mike Stump1eb44332009-09-09 15:08:12 +00003992
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003993 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003994 ObjCInterfaceDecl *RootClass = 0;
3995 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003996 while (SuperClass) {
3997 RootClass = SuperClass;
3998 SuperClass = SuperClass->getSuperClass();
3999 }
4000 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004002 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004003 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004004 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004005 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004006 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004007 Result += "\"";
4008
4009 if (SuperClass) {
4010 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004011 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004012 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004013 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 Result += "\"";
4015 }
4016 else {
4017 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004018 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004019 Result += "\"";
4020 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004021 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004022 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004023 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004024 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004025 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004026 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004027 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004028 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004029 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004030 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004031 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004032 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004033 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004034 Result += ",0,0\n";
4035 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004036 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004037 Result += "\t,0,0,0,0\n";
4038 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004039
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004040 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004041 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004042 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004043 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004044 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004045 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004046 if (SuperClass) {
4047 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004048 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004049 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004050 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004051 Result += "\"";
4052 }
4053 else {
4054 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004055 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004056 Result += "\"";
4057 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004058 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004059 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004060 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004061 Result += ",0";
4062 else {
4063 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004064 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004065 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004066 if (LangOpts.Microsoft)
4067 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004068 Result += ")";
4069 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004070 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004071 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004072 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004073 Result += "\n\t";
4074 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004075 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004076 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004077 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004078 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004079 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004080 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004081 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004082 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004083 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004084 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004085 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004086 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004087 Result += ", 0,0\n";
4088 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004089 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004090 Result += ",0,0,0\n";
4091 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004092}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004093
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004094/// RewriteImplementations - This routine rewrites all method implementations
4095/// and emits meta-data.
4096
Steve Narofface66252008-11-13 20:07:04 +00004097void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004098 int ClsDefCount = ClassImplementation.size();
4099 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004100
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004101 // Rewrite implemented methods
4102 for (int i = 0; i < ClsDefCount; i++)
4103 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004104
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004105 for (int i = 0; i < CatDefCount; i++)
4106 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004107}
Mike Stump1eb44332009-09-09 15:08:12 +00004108
Steve Narofface66252008-11-13 20:07:04 +00004109void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4110 int ClsDefCount = ClassImplementation.size();
4111 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004112
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004113 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004114 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004115 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004117 // For each implemented category, write out all its meta data.
4118 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004119 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004120
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004121 // Write objc_symtab metadata
4122 /*
4123 struct _objc_symtab
4124 {
4125 long sel_ref_cnt;
4126 SEL *refs;
4127 short cls_def_cnt;
4128 short cat_def_cnt;
4129 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004130 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004131 */
Mike Stump1eb44332009-09-09 15:08:12 +00004132
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004133 Result += "\nstruct _objc_symtab {\n";
4134 Result += "\tlong sel_ref_cnt;\n";
4135 Result += "\tSEL *refs;\n";
4136 Result += "\tshort cls_def_cnt;\n";
4137 Result += "\tshort cat_def_cnt;\n";
4138 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4139 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004140
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004141 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004142 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004143 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004144 + ", " + utostr(CatDefCount) + "\n";
4145 for (int i = 0; i < ClsDefCount; i++) {
4146 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004147 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004148 Result += "\n";
4149 }
Mike Stump1eb44332009-09-09 15:08:12 +00004150
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004151 for (int i = 0; i < CatDefCount; i++) {
4152 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004153 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004154 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004155 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004156 Result += "\n";
4157 }
Mike Stump1eb44332009-09-09 15:08:12 +00004158
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004159 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004160
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004161 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004163 /*
4164 struct _objc_module {
4165 long version;
4166 long size;
4167 const char *name;
4168 struct _objc_symtab *symtab;
4169 }
4170 */
Mike Stump1eb44332009-09-09 15:08:12 +00004171
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004172 Result += "\nstruct _objc_module {\n";
4173 Result += "\tlong version;\n";
4174 Result += "\tlong size;\n";
4175 Result += "\tconst char *name;\n";
4176 Result += "\tstruct _objc_symtab *symtab;\n";
4177 Result += "};\n\n";
4178 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004179 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004180 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004181 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004182 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004183
4184 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00004185 if (ProtocolExprDecls.size()) {
4186 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4187 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004188 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004189 E = ProtocolExprDecls.end(); I != E; ++I) {
4190 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4191 Result += (*I)->getNameAsString();
4192 Result += " = &_OBJC_PROTOCOL_";
4193 Result += (*I)->getNameAsString();
4194 Result += ";\n";
4195 }
4196 Result += "#pragma data_seg(pop)\n\n";
4197 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004198 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004199 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004200 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4201 Result += "&_OBJC_MODULES;\n";
4202 Result += "#pragma data_seg(pop)\n\n";
4203 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004204}
Chris Lattner311ff022007-10-16 22:36:42 +00004205
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004206void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4207 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004208 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004209 assert(BlockByRefDeclNo.count(VD) &&
4210 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004211 if (def)
4212 ResultStr += "struct ";
4213 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004214 "_" + utostr(BlockByRefDeclNo[VD]) ;
4215}
4216
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004217static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4218 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4219 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4220 return false;
4221}
4222
Steve Naroff54055232008-10-27 17:20:55 +00004223std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004224 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004225 std::string Tag) {
4226 const FunctionType *AFT = CE->getFunctionType();
4227 QualType RT = AFT->getResultType();
4228 std::string StructRef = "struct " + Tag;
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00004229 std::string S = "static " + RT.getAsString(Context->PrintingPolicy) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004230 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004231
Steve Naroff54055232008-10-27 17:20:55 +00004232 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004233
Douglas Gregor72564e72009-02-26 23:50:07 +00004234 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004235 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004236 // block (to reference imported block decl refs).
4237 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004238 } else if (BD->param_empty()) {
4239 S += "(" + StructRef + " *__cself)";
4240 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004241 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004242 assert(FT && "SynthesizeBlockFunc: No function proto");
4243 S += '(';
4244 // first add the implicit argument.
4245 S += StructRef + " *__cself, ";
4246 std::string ParamStr;
4247 for (BlockDecl::param_iterator AI = BD->param_begin(),
4248 E = BD->param_end(); AI != E; ++AI) {
4249 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004250 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004251 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004252 if (convertBlockPointerToFunctionPointer(QT))
4253 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004254 else
4255 QT.getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004256 S += ParamStr;
4257 }
4258 if (FT->isVariadic()) {
4259 if (!BD->param_empty()) S += ", ";
4260 S += "...";
4261 }
4262 S += ')';
4263 }
4264 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004265
Steve Naroff54055232008-10-27 17:20:55 +00004266 // Create local declarations to avoid rewriting all closure decl ref exprs.
4267 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004268 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004269 E = BlockByRefDecls.end(); I != E; ++I) {
4270 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004271 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004272 std::string TypeString;
4273 RewriteByRefString(TypeString, Name, (*I));
4274 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004275 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004276 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004277 }
Steve Naroff54055232008-10-27 17:20:55 +00004278 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004279 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004280 E = BlockByCopyDecls.end(); I != E; ++I) {
4281 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004282 // Handle nested closure invocation. For example:
4283 //
4284 // void (^myImportedClosure)(void);
4285 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004286 //
Steve Naroff54055232008-10-27 17:20:55 +00004287 // void (^anotherClosure)(void);
4288 // anotherClosure = ^(void) {
4289 // myImportedClosure(); // import and invoke the closure
4290 // };
4291 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004292 if (isTopLevelBlockPointerType((*I)->getType())) {
4293 RewriteBlockPointerTypeVariable(S, (*I));
4294 S += " = (";
4295 RewriteBlockPointerType(S, (*I)->getType());
4296 S += ")";
4297 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4298 }
4299 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004300 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004301 QualType QT = (*I)->getType();
4302 if (HasLocalVariableExternalStorage(*I))
4303 QT = Context->getPointerType(QT);
4304 QT.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004305 S += Name + " = __cself->" +
4306 (*I)->getNameAsString() + "; // bound by copy\n";
4307 }
Steve Naroff54055232008-10-27 17:20:55 +00004308 }
4309 std::string RewrittenStr = RewrittenBlockExprs[CE];
4310 const char *cstr = RewrittenStr.c_str();
4311 while (*cstr++ != '{') ;
4312 S += cstr;
4313 S += "\n";
4314 return S;
4315}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004316
Steve Naroff54055232008-10-27 17:20:55 +00004317std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004318 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004319 std::string Tag) {
4320 std::string StructRef = "struct " + Tag;
4321 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004322
Steve Naroff54055232008-10-27 17:20:55 +00004323 S += funcName;
4324 S += "_block_copy_" + utostr(i);
4325 S += "(" + StructRef;
4326 S += "*dst, " + StructRef;
4327 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004328 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004329 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004330 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004331 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004332 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004333 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004334 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004335 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004336 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004337 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004338 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004339 else
4340 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004341 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004342 S += "}\n";
4343
Steve Naroff54055232008-10-27 17:20:55 +00004344 S += "\nstatic void __";
4345 S += funcName;
4346 S += "_block_dispose_" + utostr(i);
4347 S += "(" + StructRef;
4348 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004349 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004350 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004351 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004352 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004353 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004354 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004355 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004356 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004357 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004358 else
4359 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004360 }
Mike Stump1eb44332009-09-09 15:08:12 +00004361 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004362 return S;
4363}
4364
Steve Naroff01aec112009-12-06 21:14:13 +00004365std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4366 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004367 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004368 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004369
Steve Naroff54055232008-10-27 17:20:55 +00004370 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004371 S += " struct " + Desc;
4372 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004373
Steve Naroff01aec112009-12-06 21:14:13 +00004374 Constructor += "(void *fp, "; // Invoke function pointer.
4375 Constructor += "struct " + Desc; // Descriptor pointer.
4376 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004377
Steve Naroff54055232008-10-27 17:20:55 +00004378 if (BlockDeclRefs.size()) {
4379 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004380 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004381 E = BlockByCopyDecls.end(); I != E; ++I) {
4382 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004383 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004384 std::string ArgName = "_" + FieldName;
4385 // Handle nested closure invocation. For example:
4386 //
4387 // void (^myImportedBlock)(void);
4388 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004389 //
Steve Naroff54055232008-10-27 17:20:55 +00004390 // void (^anotherBlock)(void);
4391 // anotherBlock = ^(void) {
4392 // myImportedBlock(); // import and invoke the closure
4393 // };
4394 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004395 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004396 S += "struct __block_impl *";
4397 Constructor += ", void *" + ArgName;
4398 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004399 QualType QT = (*I)->getType();
4400 if (HasLocalVariableExternalStorage(*I))
4401 QT = Context->getPointerType(QT);
4402 QT.getAsStringInternal(FieldName, Context->PrintingPolicy);
4403 QT.getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00004404 Constructor += ", " + ArgName;
4405 }
4406 S += FieldName + ";\n";
4407 }
4408 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004409 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004410 E = BlockByRefDecls.end(); I != E; ++I) {
4411 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004412 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004413 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004414 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004415 std::string TypeString;
4416 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004417 TypeString += " *";
4418 FieldName = TypeString + FieldName;
4419 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004420 Constructor += ", " + ArgName;
4421 }
4422 S += FieldName + "; // by ref\n";
4423 }
4424 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004425 Constructor += ", int flags=0)";
4426 // Initialize all "by copy" arguments.
4427 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004428 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004429 E = BlockByCopyDecls.end(); I != E; ++I) {
4430 std::string Name = (*I)->getNameAsString();
4431 if (firsTime) {
4432 Constructor += " : ";
4433 firsTime = false;
4434 }
4435 else
4436 Constructor += ", ";
4437 if (isTopLevelBlockPointerType((*I)->getType()))
4438 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4439 else
4440 Constructor += Name + "(_" + Name + ")";
4441 }
4442 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004443 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004444 E = BlockByRefDecls.end(); I != E; ++I) {
4445 std::string Name = (*I)->getNameAsString();
4446 if (firsTime) {
4447 Constructor += " : ";
4448 firsTime = false;
4449 }
4450 else
4451 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004452 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004453 }
4454
4455 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004456 if (GlobalVarDecl)
4457 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4458 else
4459 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004460 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004461
Steve Naroff01aec112009-12-06 21:14:13 +00004462 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004463 } else {
4464 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004465 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004466 if (GlobalVarDecl)
4467 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4468 else
4469 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004470 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4471 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004472 }
4473 Constructor += " ";
4474 Constructor += "}\n";
4475 S += Constructor;
4476 S += "};\n";
4477 return S;
4478}
4479
Steve Naroff01aec112009-12-06 21:14:13 +00004480std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4481 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004482 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004483 unsigned hasCopy) {
4484 std::string S = "\nstatic struct " + DescTag;
4485
4486 S += " {\n unsigned long reserved;\n";
4487 S += " unsigned long Block_size;\n";
4488 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004489 S += " void (*copy)(struct ";
4490 S += ImplTag; S += "*, struct ";
4491 S += ImplTag; S += "*);\n";
4492
4493 S += " void (*dispose)(struct ";
4494 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004495 }
4496 S += "} ";
4497
4498 S += DescTag + "_DATA = { 0, sizeof(struct ";
4499 S += ImplTag + ")";
4500 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004501 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4502 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004503 }
4504 S += "};\n";
4505 return S;
4506}
4507
Steve Naroff54055232008-10-27 17:20:55 +00004508void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004509 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004510 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004511 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004512 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004513 bool RewriteSC = (GlobalVarDecl &&
4514 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004515 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004516 GlobalVarDecl->getType().getCVRQualifiers());
4517 if (RewriteSC) {
4518 std::string SC(" void __");
4519 SC += GlobalVarDecl->getNameAsString();
4520 SC += "() {}";
4521 InsertText(FunLocStart, SC);
4522 }
4523
Steve Naroff54055232008-10-27 17:20:55 +00004524 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004525 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4526 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004527 // Need to copy-in the inner copied-in variables not actually used in this
4528 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004529 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4530 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4531 ValueDecl *VD = Exp->getDecl();
4532 BlockDeclRefs.push_back(Exp);
4533 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4534 BlockByCopyDeclsPtrSet.insert(VD);
4535 BlockByCopyDecls.push_back(VD);
4536 }
4537 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4538 BlockByRefDeclsPtrSet.insert(VD);
4539 BlockByRefDecls.push_back(VD);
4540 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004541 // imported objects in the inner blocks not used in the outer
4542 // blocks must be copied/disposed in the outer block as well.
4543 if (Exp->isByRef() ||
4544 VD->getType()->isObjCObjectPointerType() ||
4545 VD->getType()->isBlockPointerType())
4546 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004547 }
Steve Naroff54055232008-10-27 17:20:55 +00004548
Daniel Dunbar4087f272010-08-17 22:39:59 +00004549 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4550 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004551
Steve Naroff01aec112009-12-06 21:14:13 +00004552 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004553
Benjamin Kramerd999b372010-02-14 14:14:16 +00004554 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004555
Steve Naroff01aec112009-12-06 21:14:13 +00004556 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004557
Benjamin Kramerd999b372010-02-14 14:14:16 +00004558 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004559
4560 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004561 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004562 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004563 }
Steve Naroff01aec112009-12-06 21:14:13 +00004564 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4565 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004566 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004567
Steve Naroff54055232008-10-27 17:20:55 +00004568 BlockDeclRefs.clear();
4569 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004570 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004571 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004572 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004573 ImportedBlockDecls.clear();
4574 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004575 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004576 // Must insert any 'const/volatile/static here. Since it has been
4577 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004578 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004579 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004580 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004581 if (GlobalVarDecl->getType().isConstQualified())
4582 SC += "const ";
4583 if (GlobalVarDecl->getType().isVolatileQualified())
4584 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004585 if (GlobalVarDecl->getType().isRestrictQualified())
4586 SC += "restrict ";
4587 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004588 }
4589
Steve Naroff54055232008-10-27 17:20:55 +00004590 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004591 InnerDeclRefsCount.clear();
4592 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004593 RewrittenBlockExprs.clear();
4594}
4595
4596void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4597 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004598 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004599
Steve Naroff54055232008-10-27 17:20:55 +00004600 SynthesizeBlockLiterals(FunLocStart, FuncName);
4601}
4602
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004603static void BuildUniqueMethodName(std::string &Name,
4604 ObjCMethodDecl *MD) {
4605 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004606 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004607 Name += "__" + MD->getSelector().getAsString();
4608 // Convert colons to underscores.
4609 std::string::size_type loc = 0;
4610 while ((loc = Name.find(":", loc)) != std::string::npos)
4611 Name.replace(loc, 1, "_");
4612}
4613
Steve Naroff54055232008-10-27 17:20:55 +00004614void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004615 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4616 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004617 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004618 std::string FuncName;
4619 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004620 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004621}
4622
4623void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004624 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004625 if (*CI) {
4626 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4627 GetBlockDeclRefExprs(CBE->getBody());
4628 else
4629 GetBlockDeclRefExprs(*CI);
4630 }
4631 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004632 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004633 // FIXME: Handle enums.
4634 if (!isa<FunctionDecl>(CDRE->getDecl()))
4635 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004636 }
4637 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4638 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4639 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004640 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4641 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004642 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004643 BlockDeclRefs.push_back(BDRE);
4644 }
4645
Steve Naroff54055232008-10-27 17:20:55 +00004646 return;
4647}
4648
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004649void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004650 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004651 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004652 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004653 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004654 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4655 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004656 GetInnerBlockDeclRefExprs(CBE->getBody(),
4657 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004658 InnerContexts);
4659 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004660 else
4661 GetInnerBlockDeclRefExprs(*CI,
4662 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004663 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004664
4665 }
4666 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004667 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004668 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004669 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004670 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004671 }
4672 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4673 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4674 if (Var->isFunctionOrMethodVarDecl())
4675 ImportedLocalExternalDecls.insert(Var);
4676 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004677
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004678 return;
4679}
4680
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004681/// convertFunctionTypeOfBlocks - This routine converts a function type
4682/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004683/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004684/// all block pointers to function pointers.
4685QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4686 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4687 // FTP will be null for closures that don't take arguments.
4688 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004689 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004690 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004691 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004692
4693 if (FTP) {
4694 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4695 E = FTP->arg_type_end(); I && (I != E); ++I) {
4696 QualType t = *I;
4697 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004698 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004699 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004700 ArgTypes.push_back(t);
4701 }
4702 }
4703 QualType FuncType;
4704 // FIXME. Does this work if block takes no argument but has a return type
4705 // which is of block type?
4706 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004707 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004708 else FuncType = QualType(FT, 0);
4709 return FuncType;
4710}
4711
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004712Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004713 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004714 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004715
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004716 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004717 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004718 } else if (const BlockDeclRefExpr *CDRE =
4719 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004720 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004721 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004722 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004723 }
4724 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4725 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4726 }
4727 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4728 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4729 else if (const ConditionalOperator *CEXPR =
4730 dyn_cast<ConditionalOperator>(BlockExp)) {
4731 Expr *LHSExp = CEXPR->getLHS();
4732 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4733 Expr *RHSExp = CEXPR->getRHS();
4734 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4735 Expr *CONDExp = CEXPR->getCond();
4736 ConditionalOperator *CondExpr =
4737 new (Context) ConditionalOperator(CONDExp,
4738 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004739 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004740 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004741 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004742 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4743 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004744 } else {
4745 assert(1 && "RewriteBlockClass: Bad type");
4746 }
4747 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004748 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004749 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004750 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004751 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004752
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004753 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004754 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004755 &Context->Idents.get("__block_impl"));
4756 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004757
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004758 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004759 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004760
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004761 // Push the block argument type.
4762 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004763 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004764 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004765 E = FTP->arg_type_end(); I && (I != E); ++I) {
4766 QualType t = *I;
4767 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004768 if (!convertBlockPointerToFunctionPointer(t))
4769 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004770 ArgTypes.push_back(t);
4771 }
Steve Naroff54055232008-10-27 17:20:55 +00004772 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004773 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004774 QualType PtrToFuncCastType
4775 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004776
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004777 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004778
John McCall9d125032010-01-15 18:39:57 +00004779 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004780 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004781 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004782 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004783 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4784 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004785 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004786
Douglas Gregor44b43212008-12-11 16:49:14 +00004787 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004788 SourceLocation(),
4789 &Context->Idents.get("FuncPtr"),
4790 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004791 /*BitWidth=*/0, /*Mutable=*/true,
4792 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004793 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004794 FD->getType(), VK_LValue,
4795 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004796
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004797
John McCall9d125032010-01-15 18:39:57 +00004798 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004799 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004800 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004801
Chris Lattner5f9e2722011-07-23 10:55:15 +00004802 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004803 // Add the implicit argument.
4804 BlkExprs.push_back(BlkCast);
4805 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004806 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004807 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004808 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004809 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004810 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4811 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004812 Exp->getType(), VK_RValue,
4813 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004814 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004815}
4816
Steve Naroff621edce2009-04-29 16:37:50 +00004817// We need to return the rewritten expression to handle cases where the
4818// BlockDeclRefExpr is embedded in another expression being rewritten.
4819// For example:
4820//
4821// int main() {
4822// __block Foo *f;
4823// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004824//
Steve Naroff621edce2009-04-29 16:37:50 +00004825// void (^myblock)() = ^() {
4826// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4827// i = 77;
4828// };
4829//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004830Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004831 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004832 // for each DeclRefExp where BYREFVAR is name of the variable.
4833 ValueDecl *VD;
4834 bool isArrow = true;
4835 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4836 VD = BDRE->getDecl();
4837 else {
4838 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4839 isArrow = false;
4840 }
4841
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004842 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004843 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004844 &Context->Idents.get("__forwarding"),
4845 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004846 /*BitWidth=*/0, /*Mutable=*/true,
4847 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004848 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4849 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004850 FD->getType(), VK_LValue,
4851 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004852
Chris Lattner5f9e2722011-07-23 10:55:15 +00004853 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004854 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004855 &Context->Idents.get(Name),
4856 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004857 /*BitWidth=*/0, /*Mutable=*/true,
4858 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004859 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004860 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004861
4862
4863
Steve Naroffdf8570d2009-02-02 17:19:26 +00004864 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004865 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4866 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004867 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004868 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004869 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004870}
4871
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004872// Rewrites the imported local variable V with external storage
4873// (static, extern, etc.) as *V
4874//
4875Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4876 ValueDecl *VD = DRE->getDecl();
4877 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4878 if (!ImportedLocalExternalDecls.count(Var))
4879 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004880 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4881 VK_LValue, OK_Ordinary,
4882 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004883 // Need parens to enforce precedence.
4884 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4885 Exp);
4886 ReplaceStmt(DRE, PE);
4887 return PE;
4888}
4889
Steve Naroffb2f9e512008-11-03 23:29:32 +00004890void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4891 SourceLocation LocStart = CE->getLParenLoc();
4892 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004893
4894 // Need to avoid trying to rewrite synthesized casts.
4895 if (LocStart.isInvalid())
4896 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004897 // Need to avoid trying to rewrite casts contained in macros.
4898 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4899 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004900
Steve Naroff54055232008-10-27 17:20:55 +00004901 const char *startBuf = SM->getCharacterData(LocStart);
4902 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004903 QualType QT = CE->getType();
4904 const Type* TypePtr = QT->getAs<Type>();
4905 if (isa<TypeOfExprType>(TypePtr)) {
4906 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4907 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4908 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004909 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004910 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004911 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004912 return;
4913 }
Steve Naroff54055232008-10-27 17:20:55 +00004914 // advance the location to startArgList.
4915 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004916
Steve Naroff54055232008-10-27 17:20:55 +00004917 while (*argPtr++ && (argPtr < endBuf)) {
4918 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004919 case '^':
4920 // Replace the '^' with '*'.
4921 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004922 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004923 break;
Steve Naroff54055232008-10-27 17:20:55 +00004924 }
4925 }
4926 return;
4927}
4928
4929void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4930 SourceLocation DeclLoc = FD->getLocation();
4931 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004932
Steve Naroff54055232008-10-27 17:20:55 +00004933 // We have 1 or more arguments that have closure pointers.
4934 const char *startBuf = SM->getCharacterData(DeclLoc);
4935 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004936
Steve Naroff54055232008-10-27 17:20:55 +00004937 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004938
Steve Naroff54055232008-10-27 17:20:55 +00004939 parenCount++;
4940 // advance the location to startArgList.
4941 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4942 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004943
Steve Naroff54055232008-10-27 17:20:55 +00004944 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004945
Steve Naroff54055232008-10-27 17:20:55 +00004946 while (*argPtr++ && parenCount) {
4947 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004948 case '^':
4949 // Replace the '^' with '*'.
4950 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004951 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004952 break;
4953 case '(':
4954 parenCount++;
4955 break;
4956 case ')':
4957 parenCount--;
4958 break;
Steve Naroff54055232008-10-27 17:20:55 +00004959 }
4960 }
4961 return;
4962}
4963
4964bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004965 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004966 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004967 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004968 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004969 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004970 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004971 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004972 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004973 }
4974 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004975 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004976 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004977 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004978 return true;
4979 }
4980 return false;
4981}
4982
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004983bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4984 const FunctionProtoType *FTP;
4985 const PointerType *PT = QT->getAs<PointerType>();
4986 if (PT) {
4987 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4988 } else {
4989 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4990 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4991 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4992 }
4993 if (FTP) {
4994 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004995 E = FTP->arg_type_end(); I != E; ++I) {
4996 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004997 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004998 if ((*I)->isObjCObjectPointerType() &&
4999 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5000 return true;
5001 }
5002
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005003 }
5004 return false;
5005}
5006
Ted Kremenek8189cde2009-02-07 01:47:29 +00005007void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5008 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00005009 const char *argPtr = strchr(Name, '(');
5010 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00005011
Steve Naroff54055232008-10-27 17:20:55 +00005012 LParen = argPtr; // output the start.
5013 argPtr++; // skip past the left paren.
5014 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005015
Steve Naroff54055232008-10-27 17:20:55 +00005016 while (*argPtr && parenCount) {
5017 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005018 case '(': parenCount++; break;
5019 case ')': parenCount--; break;
5020 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005021 }
5022 if (parenCount) argPtr++;
5023 }
5024 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5025 RParen = argPtr; // output the end
5026}
5027
5028void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5029 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5030 RewriteBlockPointerFunctionArgs(FD);
5031 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005032 }
Steve Naroff54055232008-10-27 17:20:55 +00005033 // Handle Variables and Typedefs.
5034 SourceLocation DeclLoc = ND->getLocation();
5035 QualType DeclT;
5036 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5037 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005038 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005039 DeclT = TDD->getUnderlyingType();
5040 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5041 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005042 else
Steve Naroff54055232008-10-27 17:20:55 +00005043 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005044
Steve Naroff54055232008-10-27 17:20:55 +00005045 const char *startBuf = SM->getCharacterData(DeclLoc);
5046 const char *endBuf = startBuf;
5047 // scan backward (from the decl location) for the end of the previous decl.
5048 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5049 startBuf--;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005050 SourceLocation Start = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
5051 std::string buf;
5052 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005053 // *startBuf != '^' if we are dealing with a pointer to function that
5054 // may take block argument types (which will be handled below).
5055 if (*startBuf == '^') {
5056 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005057 buf = '*';
5058 startBuf++;
5059 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005060 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005061 while (*startBuf != ')') {
5062 buf += *startBuf;
5063 startBuf++;
5064 OrigLength++;
5065 }
5066 buf += ')';
5067 OrigLength++;
5068
5069 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5070 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005071 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005072 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005073 DeclLoc = ND->getLocation();
5074 startBuf = SM->getCharacterData(DeclLoc);
5075 const char *argListBegin, *argListEnd;
5076 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5077 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005078 if (*argListBegin == '^')
5079 buf += '*';
5080 else if (*argListBegin == '<') {
5081 buf += "/*";
5082 buf += *argListBegin++;
5083 OrigLength++;;
5084 while (*argListBegin != '>') {
5085 buf += *argListBegin++;
5086 OrigLength++;
5087 }
5088 buf += *argListBegin;
5089 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005090 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005091 else
5092 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005093 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005094 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005095 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005096 buf += ')';
5097 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005098 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005099 ReplaceText(Start, OrigLength, buf);
5100
Steve Naroff54055232008-10-27 17:20:55 +00005101 return;
5102}
5103
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005104
5105/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5106/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5107/// struct Block_byref_id_object *src) {
5108/// _Block_object_assign (&_dest->object, _src->object,
5109/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5110/// [|BLOCK_FIELD_IS_WEAK]) // object
5111/// _Block_object_assign(&_dest->object, _src->object,
5112/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5113/// [|BLOCK_FIELD_IS_WEAK]) // block
5114/// }
5115/// And:
5116/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5117/// _Block_object_dispose(_src->object,
5118/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5119/// [|BLOCK_FIELD_IS_WEAK]) // object
5120/// _Block_object_dispose(_src->object,
5121/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5122/// [|BLOCK_FIELD_IS_WEAK]) // block
5123/// }
5124
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005125std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5126 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005127 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005128 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005129 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005130 CopyDestroyCache.insert(flag);
5131 S = "static void __Block_byref_id_object_copy_";
5132 S += utostr(flag);
5133 S += "(void *dst, void *src) {\n";
5134
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005135 // offset into the object pointer is computed as:
5136 // void * + void* + int + int + void* + void *
5137 unsigned IntSize =
5138 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5139 unsigned VoidPtrSize =
5140 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5141
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005142 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005143 S += " _Block_object_assign((char*)dst + ";
5144 S += utostr(offset);
5145 S += ", *(void * *) ((char*)src + ";
5146 S += utostr(offset);
5147 S += "), ";
5148 S += utostr(flag);
5149 S += ");\n}\n";
5150
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005151 S += "static void __Block_byref_id_object_dispose_";
5152 S += utostr(flag);
5153 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005154 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5155 S += utostr(offset);
5156 S += "), ";
5157 S += utostr(flag);
5158 S += ");\n}\n";
5159 return S;
5160}
5161
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005162/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5163/// the declaration into:
5164/// struct __Block_byref_ND {
5165/// void *__isa; // NULL for everything except __weak pointers
5166/// struct __Block_byref_ND *__forwarding;
5167/// int32_t __flags;
5168/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005169/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5170/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005171/// typex ND;
5172/// };
5173///
5174/// It then replaces declaration of ND variable with:
5175/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5176/// __size=sizeof(struct __Block_byref_ND),
5177/// ND=initializer-if-any};
5178///
5179///
5180void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005181 // Insert declaration for the function in which block literal is
5182 // used.
5183 if (CurFunctionDeclToDeclareForBlock)
5184 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005185 int flag = 0;
5186 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005187 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005188 if (DeclLoc.isInvalid())
5189 // If type location is missing, it is because of missing type (a warning).
5190 // Use variable's location which is good for this case.
5191 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005192 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005193 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005194 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005195 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005196 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005197 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005198 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005199 ByrefType += " {\n";
5200 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005201 RewriteByRefString(ByrefType, Name, ND);
5202 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005203 ByrefType += " int __flags;\n";
5204 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005205 // Add void *__Block_byref_id_object_copy;
5206 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005207 QualType Ty = ND->getType();
5208 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5209 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005210 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5211 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005212 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005213
5214 QualType T = Ty;
5215 (void)convertBlockPointerToFunctionPointer(T);
5216 T.getAsStringInternal(Name, Context->PrintingPolicy);
5217
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005218 ByrefType += " " + Name + ";\n";
5219 ByrefType += "};\n";
5220 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005221 SourceLocation FunLocStart;
5222 if (CurFunctionDef)
5223 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5224 else {
5225 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5226 FunLocStart = CurMethodDef->getLocStart();
5227 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005228 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005229 if (Ty.isObjCGCWeak()) {
5230 flag |= BLOCK_FIELD_IS_WEAK;
5231 isa = 1;
5232 }
5233
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005234 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005235 flag = BLOCK_BYREF_CALLER;
5236 QualType Ty = ND->getType();
5237 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5238 if (Ty->isBlockPointerType())
5239 flag |= BLOCK_FIELD_IS_BLOCK;
5240 else
5241 flag |= BLOCK_FIELD_IS_OBJECT;
5242 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005243 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005244 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005245 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005246
5247 // struct __Block_byref_ND ND =
5248 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5249 // initializer-if-any};
5250 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005251 unsigned flags = 0;
5252 if (HasCopyAndDispose)
5253 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005254 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005255 ByrefType.clear();
5256 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005257 std::string ForwardingCastType("(");
5258 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005259 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005260 ByrefType += " " + Name + " = {(void*)";
5261 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005262 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005263 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005264 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005265 ByrefType += "sizeof(";
5266 RewriteByRefString(ByrefType, Name, ND);
5267 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005268 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005269 ByrefType += ", __Block_byref_id_object_copy_";
5270 ByrefType += utostr(flag);
5271 ByrefType += ", __Block_byref_id_object_dispose_";
5272 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005273 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005274 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005275 unsigned nameSize = Name.size();
5276 // for block or function pointer declaration. Name is aleady
5277 // part of the declaration.
5278 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5279 nameSize = 1;
5280 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005281 }
5282 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005283 SourceLocation startLoc;
5284 Expr *E = ND->getInit();
5285 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5286 startLoc = ECE->getLParenLoc();
5287 else
5288 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005289 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005290 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005291 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005292 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005293 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005294 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005295 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005296 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005297 ByrefType += "sizeof(";
5298 RewriteByRefString(ByrefType, Name, ND);
5299 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005300 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005301 ByrefType += "__Block_byref_id_object_copy_";
5302 ByrefType += utostr(flag);
5303 ByrefType += ", __Block_byref_id_object_dispose_";
5304 ByrefType += utostr(flag);
5305 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005306 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005307 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005308
5309 // Complete the newly synthesized compound expression by inserting a right
5310 // curly brace before the end of the declaration.
5311 // FIXME: This approach avoids rewriting the initializer expression. It
5312 // also assumes there is only one declarator. For example, the following
5313 // isn't currently supported by this routine (in general):
5314 //
5315 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5316 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005317 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5318 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005319 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5320 SourceLocation semiLoc =
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005321 startLoc.getFileLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005322
Benjamin Kramerd999b372010-02-14 14:14:16 +00005323 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005324 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005325 return;
5326}
5327
Mike Stump1eb44332009-09-09 15:08:12 +00005328void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005329 // Add initializers for any closure decl refs.
5330 GetBlockDeclRefExprs(Exp->getBody());
5331 if (BlockDeclRefs.size()) {
5332 // Unique all "by copy" declarations.
5333 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005334 if (!BlockDeclRefs[i]->isByRef()) {
5335 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5336 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5337 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5338 }
5339 }
Steve Naroff54055232008-10-27 17:20:55 +00005340 // Unique all "by ref" declarations.
5341 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5342 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005343 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5344 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5345 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5346 }
Steve Naroff54055232008-10-27 17:20:55 +00005347 }
5348 // Find any imported blocks...they will need special attention.
5349 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005350 if (BlockDeclRefs[i]->isByRef() ||
5351 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005352 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005353 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005354 }
5355}
5356
Chris Lattner5f9e2722011-07-23 10:55:15 +00005357FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005358 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005359 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005360 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5361 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005362 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005363}
5364
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005365Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005366 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005367 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005368 Blocks.push_back(Exp);
5369
5370 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005371
5372 // Add inner imported variables now used in current block.
5373 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005374 if (!InnerBlockDeclRefs.empty()) {
5375 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5376 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5377 ValueDecl *VD = Exp->getDecl();
5378 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005379 // We need to save the copied-in variables in nested
5380 // blocks because it is needed at the end for some of the API generations.
5381 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005382 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5383 BlockDeclRefs.push_back(Exp);
5384 BlockByCopyDeclsPtrSet.insert(VD);
5385 BlockByCopyDecls.push_back(VD);
5386 }
5387 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5388 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5389 BlockDeclRefs.push_back(Exp);
5390 BlockByRefDeclsPtrSet.insert(VD);
5391 BlockByRefDecls.push_back(VD);
5392 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005393 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005394 // Find any imported blocks...they will need special attention.
5395 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5396 if (InnerBlockDeclRefs[i]->isByRef() ||
5397 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5398 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5399 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005400 }
5401 InnerDeclRefsCount.push_back(countOfInnerDecls);
5402
Steve Narofffa15fd92008-10-28 20:29:00 +00005403 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005404
Steve Narofffa15fd92008-10-28 20:29:00 +00005405 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005406 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005407 else if (CurMethodDef)
5408 BuildUniqueMethodName(FuncName, CurMethodDef);
5409 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005410 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005411
Steve Narofffa15fd92008-10-28 20:29:00 +00005412 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005413
Steve Narofffa15fd92008-10-28 20:29:00 +00005414 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5415 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005416
Steve Narofffa15fd92008-10-28 20:29:00 +00005417 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005418 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5419 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005420
5421 FunctionDecl *FD;
5422 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005423
Steve Narofffa15fd92008-10-28 20:29:00 +00005424 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005425 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005426 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5427 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005428
Chris Lattner5f9e2722011-07-23 10:55:15 +00005429 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005430
Steve Narofffdc03722008-10-29 21:23:59 +00005431 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005432 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005433 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005434 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005435 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005436 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005437 InitExprs.push_back(castExpr);
5438
Steve Naroff01aec112009-12-06 21:14:13 +00005439 // Initialize the block descriptor.
5440 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005441
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005442 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5443 SourceLocation(), SourceLocation(),
5444 &Context->Idents.get(DescData.c_str()),
5445 Context->VoidPtrTy, 0,
5446 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005447 UnaryOperator *DescRefExpr =
5448 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5449 Context->VoidPtrTy,
5450 VK_LValue,
5451 SourceLocation()),
5452 UO_AddrOf,
5453 Context->getPointerType(Context->VoidPtrTy),
5454 VK_RValue, OK_Ordinary,
5455 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005456 InitExprs.push_back(DescRefExpr);
5457
Steve Narofffa15fd92008-10-28 20:29:00 +00005458 // Add initializers for any closure decl refs.
5459 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005460 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005461 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005462 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005463 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005464 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005465 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005466 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005467 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5468 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005469 if (HasLocalVariableExternalStorage(*I)) {
5470 QualType QT = (*I)->getType();
5471 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005472 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5473 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005474 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005475 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005476 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005477 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5478 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005479 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005480 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005481 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005482 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005483 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5484 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005485 if (HasLocalVariableExternalStorage(*I)) {
5486 QualType QT = (*I)->getType();
5487 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005488 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5489 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005490 }
5491
Steve Narofffa15fd92008-10-28 20:29:00 +00005492 }
Mike Stump1eb44332009-09-09 15:08:12 +00005493 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005494 }
5495 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005496 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005497 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005498 ValueDecl *ND = (*I);
5499 std::string Name(ND->getNameAsString());
5500 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005501 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005502 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5503 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005504 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005505 SourceLocation(), SourceLocation(),
5506 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005507 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5508 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5509
Daniel Dunbar4087f272010-08-17 22:39:59 +00005510 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005511 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5512 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005513 bool isNestedCapturedVar = false;
5514 if (block)
5515 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5516 ce = block->capture_end(); ci != ce; ++ci) {
5517 const VarDecl *variable = ci->getVariable();
5518 if (variable == ND && ci->isNested()) {
5519 assert (ci->isByRef() &&
5520 "SynthBlockInitExpr - captured block variable is not byref");
5521 isNestedCapturedVar = true;
5522 break;
5523 }
5524 }
5525 // captured nested byref variable has its address passed. Do not take
5526 // its address again.
5527 if (!isNestedCapturedVar)
5528 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005529 Context->getPointerType(Exp->getType()),
5530 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005531 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005532 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005533 }
5534 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005535 if (ImportedBlockDecls.size()) {
5536 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5537 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005538 unsigned IntSize =
5539 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005540 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5541 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005542 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005543 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005544 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005545 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005546 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005547 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005548 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005549 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005550 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005551 BlockDeclRefs.clear();
5552 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005553 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005554 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005555 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005556 ImportedBlockDecls.clear();
5557 return NewRep;
5558}
5559
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005560bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5561 if (const ObjCForCollectionStmt * CS =
5562 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5563 return CS->getElement() == DS;
5564 return false;
5565}
5566
Steve Narofffa15fd92008-10-28 20:29:00 +00005567//===----------------------------------------------------------------------===//
5568// Function Body / Expression rewriting
5569//===----------------------------------------------------------------------===//
5570
Steve Naroffc77a6362008-12-04 16:24:46 +00005571// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5572// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5573// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5574// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5575// Since the rewriter isn't capable of rewriting rewritten code, it's important
5576// we get this right.
5577void RewriteObjC::CollectPropertySetters(Stmt *S) {
5578 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005579 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005580 if (*CI)
5581 CollectPropertySetters(*CI);
5582
5583 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5584 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005585 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5586 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005587 }
5588 }
5589}
5590
Steve Narofffa15fd92008-10-28 20:29:00 +00005591Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005592 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005593 isa<DoStmt>(S) || isa<ForStmt>(S))
5594 Stmts.push_back(S);
5595 else if (isa<ObjCForCollectionStmt>(S)) {
5596 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005597 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005598 }
Mike Stump1eb44332009-09-09 15:08:12 +00005599
Steve Narofffa15fd92008-10-28 20:29:00 +00005600 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005601
Steve Narofffa15fd92008-10-28 20:29:00 +00005602 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005603 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005604 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005605 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005606 Stmt *ChildStmt = (*CI);
5607 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005608 Expr *OldBase = IvarRefExpr->getBase();
5609 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005610 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005611 if (replaced) {
5612 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5613 ReplaceStmt(OldBase, IRE->getBase());
5614 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005615 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005616 }
5617 }
5618 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005619 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5620 if (newStmt) {
5621 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5622 if (PropSetters[PropOrImplicitRefExpr] == S) {
5623 S = newStmt;
5624 newStmt = 0;
5625 }
5626 if (newStmt)
5627 *CI = newStmt;
5628 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005629 // If dealing with an assignment with LHS being a property reference
5630 // expression, the entire assignment tree is rewritten into a property
5631 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5632 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005633 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005634 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005635 if (PropSetters[Exp]) {
5636 ++CI;
5637 continue;
5638 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005639 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005640 }
Mike Stump1eb44332009-09-09 15:08:12 +00005641
Steve Narofffa15fd92008-10-28 20:29:00 +00005642 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005643 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005644 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5645 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005646 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005647 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005648 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005649 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005650 Stmt *SaveCurrentBody = CurrentBody;
5651 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005652 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005653 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005654 // block literal on rhs of a property-dot-sytax assignment
5655 // must be replaced by its synthesize ast so getRewrittenText
5656 // works as expected. In this case, what actually ends up on RHS
5657 // is the blockTranscribed which is the helper function for the
5658 // block literal; as in: self.c = ^() {[ace ARR];};
5659 bool saveDisableReplaceStmt = DisableReplaceStmt;
5660 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005661 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005662 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005663 CurrentBody = SaveCurrentBody;
5664 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005665 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005666 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005667 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005668 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005669
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005670 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5671
Steve Narofffa15fd92008-10-28 20:29:00 +00005672 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005673 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005674 return blockTranscribed;
5675 }
5676 // Handle specific things.
5677 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5678 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005679
John McCall12f78a62010-12-02 01:19:52 +00005680 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005681 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5682 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5683
5684 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005685 if (BinOp) {
5686 // Because the rewriter doesn't allow us to rewrite rewritten code,
5687 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005688 DisableReplaceStmt = true;
5689 // Save the source range. Even if we disable the replacement, the
5690 // rewritten node will have been inserted into the tree. If the synthesized
5691 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005692 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005693 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5694 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005695 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005696 // Need to rewrite the ivar access expression if need be.
5697 if (isa<ObjCIvarRefExpr>(newStmt)) {
5698 bool replaced = false;
5699 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5700 }
5701
Steve Naroffb619d952008-12-09 12:56:34 +00005702 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005703 //
5704 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5705 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5706 // to see the original expression). Consider this example:
5707 //
5708 // Foo *obj1, *obj2;
5709 //
5710 // obj1.i = [obj2 rrrr];
5711 //
5712 // 'BinOp' for the previous expression looks like:
5713 //
5714 // (BinaryOperator 0x231ccf0 'int' '='
5715 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5716 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5717 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5718 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5719 //
5720 // 'newStmt' represents the rewritten message expression. For example:
5721 //
5722 // (CallExpr 0x231d300 'id':'struct objc_object *'
5723 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5724 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5725 // (CStyleCastExpr 0x231d220 'void *'
5726 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5727 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005728 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005729 // can be used as the setter argument. ReplaceStmt() will still 'see'
5730 // the original RHS (since we haven't altered BinOp).
5731 //
Mike Stump1eb44332009-09-09 15:08:12 +00005732 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005733 // node. As a result, we now leak the original AST nodes.
5734 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005735 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005736 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005737 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005738 }
5739 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005740
Steve Narofffa15fd92008-10-28 20:29:00 +00005741 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5742 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005743
Steve Narofffa15fd92008-10-28 20:29:00 +00005744 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5745 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005746
Steve Narofffa15fd92008-10-28 20:29:00 +00005747 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005748#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005749 // Before we rewrite it, put the original message expression in a comment.
5750 SourceLocation startLoc = MessExpr->getLocStart();
5751 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005752
Steve Narofffa15fd92008-10-28 20:29:00 +00005753 const char *startBuf = SM->getCharacterData(startLoc);
5754 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 std::string messString;
5757 messString += "// ";
5758 messString.append(startBuf, endBuf-startBuf+1);
5759 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005760
5761 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005762 // InsertText(clang::SourceLocation, char const*, unsigned int).
5763 // InsertText(startLoc, messString.c_str(), messString.size());
5764 // Tried this, but it didn't work either...
5765 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005766#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005767 return RewriteMessageExpr(MessExpr);
5768 }
Mike Stump1eb44332009-09-09 15:08:12 +00005769
Steve Narofffa15fd92008-10-28 20:29:00 +00005770 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5771 return RewriteObjCTryStmt(StmtTry);
5772
5773 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5774 return RewriteObjCSynchronizedStmt(StmtTry);
5775
5776 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5777 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005778
Steve Narofffa15fd92008-10-28 20:29:00 +00005779 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5780 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005781
5782 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005783 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005784 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005785 OrigStmtRange.getEnd());
5786 if (BreakStmt *StmtBreakStmt =
5787 dyn_cast<BreakStmt>(S))
5788 return RewriteBreakStmt(StmtBreakStmt);
5789 if (ContinueStmt *StmtContinueStmt =
5790 dyn_cast<ContinueStmt>(S))
5791 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005792
5793 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005794 // and cast exprs.
5795 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5796 // FIXME: What we're doing here is modifying the type-specifier that
5797 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005798 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005799 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5800 // the context of an ObjCForCollectionStmt. For example:
5801 // NSArray *someArray;
5802 // for (id <FooProtocol> index in someArray) ;
5803 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5804 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005805 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005806 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005807
Steve Narofffa15fd92008-10-28 20:29:00 +00005808 // Blocks rewrite rules.
5809 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5810 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005811 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005812 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005813 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005814 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005815 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005816 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005817 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005818 if (VD->hasAttr<BlocksAttr>()) {
5819 static unsigned uniqueByrefDeclCount = 0;
5820 assert(!BlockByRefDeclNo.count(ND) &&
5821 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5822 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005823 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005824 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005825 else
5826 RewriteTypeOfDecl(VD);
5827 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005828 }
Richard Smith162e1c12011-04-15 14:24:37 +00005829 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005830 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005831 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005832 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005833 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5834 }
5835 }
5836 }
Mike Stump1eb44332009-09-09 15:08:12 +00005837
Steve Narofffa15fd92008-10-28 20:29:00 +00005838 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5839 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005840
5841 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005842 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5843 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005844 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5845 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005846 && "Statement stack mismatch");
5847 Stmts.pop_back();
5848 }
5849 // Handle blocks rewriting.
5850 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5851 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005852 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005853 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005854 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5855 ValueDecl *VD = DRE->getDecl();
5856 if (VD->hasAttr<BlocksAttr>())
5857 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005858 if (HasLocalVariableExternalStorage(VD))
5859 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005860 }
5861
Steve Narofffa15fd92008-10-28 20:29:00 +00005862 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005863 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005864 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005865 ReplaceStmt(S, BlockCall);
5866 return BlockCall;
5867 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005868 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005869 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005870 RewriteCastExpr(CE);
5871 }
5872#if 0
5873 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005874 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5875 ICE->getSubExpr(),
5876 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005877 // Get the new text.
5878 std::string SStr;
5879 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005880 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005881 const std::string &Str = Buf.str();
5882
5883 printf("CAST = %s\n", &Str[0]);
5884 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5885 delete S;
5886 return Replacement;
5887 }
5888#endif
5889 // Return this stmt unmodified.
5890 return S;
5891}
5892
Steve Naroff3d7e7862009-12-05 15:55:59 +00005893void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5894 for (RecordDecl::field_iterator i = RD->field_begin(),
5895 e = RD->field_end(); i != e; ++i) {
5896 FieldDecl *FD = *i;
5897 if (isTopLevelBlockPointerType(FD->getType()))
5898 RewriteBlockPointerDecl(FD);
5899 if (FD->getType()->isObjCQualifiedIdType() ||
5900 FD->getType()->isObjCQualifiedInterfaceType())
5901 RewriteObjCQualifiedInterfaceTypes(FD);
5902 }
5903}
5904
Steve Narofffa15fd92008-10-28 20:29:00 +00005905/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5906/// main file of the input.
5907void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5908 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005909 if (FD->isOverloadedOperator())
5910 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005911
Steve Narofffa15fd92008-10-28 20:29:00 +00005912 // Since function prototypes don't have ParmDecl's, we check the function
5913 // prototype. This enables us to rewrite function declarations and
5914 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005915 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005916
Sebastian Redld3a413d2009-04-26 20:35:05 +00005917 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005918 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005919 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005920 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005921 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005922 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005923 Body =
5924 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5925 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005926 CurrentBody = 0;
5927 if (PropParentMap) {
5928 delete PropParentMap;
5929 PropParentMap = 0;
5930 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005931 // This synthesizes and inserts the block "impl" struct, invoke function,
5932 // and any copy/dispose helper functions.
5933 InsertBlockLiteralsWithinFunction(FD);
5934 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005935 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005936 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005937 return;
5938 }
5939 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005940 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005941 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005942 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005943 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005944 Body =
5945 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5946 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005947 CurrentBody = 0;
5948 if (PropParentMap) {
5949 delete PropParentMap;
5950 PropParentMap = 0;
5951 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005952 InsertBlockLiteralsWithinMethod(MD);
5953 CurMethodDef = 0;
5954 }
5955 }
5956 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5957 ClassImplementation.push_back(CI);
5958 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5959 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005960 else if (isa<ObjCClassDecl>(D))
5961 assert(false && "RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005962 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5963 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005964 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005965 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005966 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005967 CheckFunctionPointerDecl(VD->getType(), VD);
5968 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005969 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005970 RewriteCastExpr(CE);
5971 }
5972 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005973 } else if (VD->getType()->isRecordType()) {
5974 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5975 if (RD->isDefinition())
5976 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005977 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005978 if (VD->getInit()) {
5979 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005980 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005981 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005982 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005983 CurrentBody = 0;
5984 if (PropParentMap) {
5985 delete PropParentMap;
5986 PropParentMap = 0;
5987 }
Mike Stump1eb44332009-09-09 15:08:12 +00005988 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00005989 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005990 GlobalVarDecl = 0;
5991
5992 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005993 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005994 RewriteCastExpr(CE);
5995 }
5996 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005997 return;
5998 }
Richard Smith162e1c12011-04-15 14:24:37 +00005999 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00006000 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00006001 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00006002 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00006003 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6004 return;
6005 }
6006 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00006007 if (RD->isDefinition())
6008 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00006009 return;
6010 }
6011 // Nothing yet.
6012}
6013
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00006014void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00006015 if (Diags.hasErrorOccurred())
6016 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006017
Steve Narofffa15fd92008-10-28 20:29:00 +00006018 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00006019
Steve Naroff621edce2009-04-29 16:37:50 +00006020 // Here's a great place to add any extra declarations that may be needed.
6021 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00006022 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00006023 E = ProtocolExprDecls.end(); I != E; ++I)
6024 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
6025
Benjamin Kramerd999b372010-02-14 14:14:16 +00006026 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00006027 if (ClassImplementation.size() || CategoryImplementation.size())
6028 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00006029
Steve Narofffa15fd92008-10-28 20:29:00 +00006030 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6031 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00006032 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00006033 Rewrite.getRewriteBufferFor(MainFileID)) {
6034 //printf("Changed:\n");
6035 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6036 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00006037 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00006038 }
Steve Narofface66252008-11-13 20:07:04 +00006039
Steve Naroff621edce2009-04-29 16:37:50 +00006040 if (ClassImplementation.size() || CategoryImplementation.size() ||
6041 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00006042 // Rewrite Objective-c meta data*
6043 std::string ResultStr;
6044 SynthesizeMetaDataIntoBuffer(ResultStr);
6045 // Emit metadata.
6046 *OutFile << ResultStr;
6047 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006048 OutFile->flush();
6049}