blob: ab3b69002c16c9d42355f08372dd5fcb4d079eb5 [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;
David Blaikied6471f72011-09-25 23:23:43 +000058 DiagnosticsEngine &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,
David Blaikied6471f72011-09-25 23:23:43 +0000175 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000176 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() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000423 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
424 if (const ObjCObjectPointerType * OBJPT =
425 T->getAsObjCInterfacePointerType()) {
426 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
427 T = QualType(IFaceT, 0);
428 T = Context->getPointerType(T);
429 }
430 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000431 }
432
Steve Naroff54055232008-10-27 17:20:55 +0000433 // FIXME: This predicate seems like it would be useful to add to ASTContext.
434 bool isObjCType(QualType T) {
435 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
436 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000437
Steve Naroff54055232008-10-27 17:20:55 +0000438 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000439
Steve Naroff54055232008-10-27 17:20:55 +0000440 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
441 OCT == Context->getCanonicalType(Context->getObjCClassType()))
442 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Ted Kremenek6217b802009-07-29 21:53:49 +0000444 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000445 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000446 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000447 return true;
448 }
449 return false;
450 }
451 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000452 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000453 void GetExtentOfArgList(const char *Name, const char *&LParen,
454 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000455 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Chris Lattner5f9e2722011-07-23 10:55:15 +0000457 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000458 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000459 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000460
Steve Naroff621edce2009-04-29 16:37:50 +0000461 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000462 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000463 if (From[i] == '"')
464 To += "\\\"";
465 else
466 To += From[i];
467 }
468 }
John McCalle23cf432010-12-14 08:05:40 +0000469
470 QualType getSimpleFunctionType(QualType result,
471 const QualType *args,
472 unsigned numArgs,
473 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000474 if (result == Context->getObjCInstanceType())
475 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000476 FunctionProtoType::ExtProtoInfo fpi;
477 fpi.Variadic = variadic;
478 return Context->getFunctionType(result, args, numArgs, fpi);
479 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000480 };
John McCall9d125032010-01-15 18:39:57 +0000481
482 // Helper function: create a CStyleCastExpr with trivial type source info.
483 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
John McCall2de56d12010-08-25 11:45:40 +0000484 CastKind Kind, Expr *E) {
John McCall9d125032010-01-15 18:39:57 +0000485 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +0000486 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
John McCallf871d0c2010-08-07 06:22:56 +0000487 SourceLocation(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +0000488 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000489}
490
Mike Stump1eb44332009-09-09 15:08:12 +0000491void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
492 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000493 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000494 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000495 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000496 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000497 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000498 // All the args are checked/rewritten. Don't call twice!
499 RewriteBlockPointerDecl(D);
500 break;
501 }
502 }
503}
504
505void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000506 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000507 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000508 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000509}
510
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000511static bool IsHeaderFile(const std::string &Filename) {
512 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000513
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000514 if (DotPos == std::string::npos) {
515 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000516 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000517 }
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000519 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
520 // C header: .h
521 // C++ header: .hh or .H;
522 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000523}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000524
Chris Lattner5f9e2722011-07-23 10:55:15 +0000525RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000526 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000527 bool silenceMacroWarn)
528 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
529 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000530 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000531 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000532 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000533 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
534 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000535 "rewriter doesn't support user-specified control flow semantics "
536 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000537}
538
Eli Friedmanbce831b2009-05-18 22:29:17 +0000539ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000540 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000541 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000542 const LangOptions &LOpts,
543 bool SilenceRewriteMacroWarning) {
544 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000545}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000546
Steve Naroffb29b4272008-04-14 22:03:09 +0000547void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000548 Context = &context;
549 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000550 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000551 MsgSendFunctionDecl = 0;
552 MsgSendSuperFunctionDecl = 0;
553 MsgSendStretFunctionDecl = 0;
554 MsgSendSuperStretFunctionDecl = 0;
555 MsgSendFpretFunctionDecl = 0;
556 GetClassFunctionDecl = 0;
557 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000558 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000559 SelGetUidFunctionDecl = 0;
560 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000561 ConstantStringClassReference = 0;
562 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000563 CurMethodDef = 0;
564 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000565 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000566 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000567 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000568 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000569 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000570 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000571 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000572 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000573 PropParentMap = 0;
574 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000575 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000576 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000577
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000578 // Get the ID and start/end of the main file.
579 MainFileID = SM->getMainFileID();
580 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
581 MainFileStart = MainBuf->getBufferStart();
582 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000583
Chris Lattner2c78b872009-04-14 23:22:57 +0000584 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000585
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000586 // declaring objc_selector outside the parameter list removes a silly
587 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000588 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000589 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000590 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000591 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000592 Preamble += "struct objc_object *superClass; ";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000593 if (LangOpts.MicrosoftExt) {
Steve Naroffc0a123c2008-03-11 17:37:02 +0000594 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000595 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
596 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000597 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000598 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000599 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000600 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
601 Preamble += "typedef struct objc_object Protocol;\n";
602 Preamble += "#define _REWRITER_typedef_Protocol\n";
603 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000604 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000605 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
606 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
607 } else
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000608 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000609 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000610 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000611 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000612 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000614 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +0000615 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000616 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000617 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000618 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000619 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000620 Preamble += "(const char *);\n";
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000621 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
622 Preamble += "(struct objc_class *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000623 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000624 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000625 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
626 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
627 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
628 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
629 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000630 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000631 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000632 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
633 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
634 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000635 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
636 Preamble += "struct __objcFastEnumerationState {\n\t";
637 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000638 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000639 Preamble += "unsigned long *mutationsPtr;\n\t";
640 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000641 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000642 Preamble += "#define __FASTENUMERATIONSTATE\n";
643 Preamble += "#endif\n";
644 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
645 Preamble += "struct __NSConstantStringImpl {\n";
646 Preamble += " int *isa;\n";
647 Preamble += " int flags;\n";
648 Preamble += " char *str;\n";
649 Preamble += " long length;\n";
650 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000651 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
652 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
653 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000654 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000655 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000656 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
657 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000658 // Blocks preamble.
659 Preamble += "#ifndef BLOCK_IMPL\n";
660 Preamble += "#define BLOCK_IMPL\n";
661 Preamble += "struct __block_impl {\n";
662 Preamble += " void *isa;\n";
663 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000664 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000665 Preamble += " void *FuncPtr;\n";
666 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000667 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000668 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000669 Preamble += "extern \"C\" __declspec(dllexport) "
670 "void _Block_object_assign(void *, const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000671 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
672 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
673 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
674 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000675 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
676 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000677 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
678 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
679 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000680 Preamble += "#endif\n";
Francois Pichet62ec1f22011-09-17 17:15:52 +0000681 if (LangOpts.MicrosoftExt) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000682 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
683 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000684 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
Steve Naroffa48396e2008-10-27 18:50:14 +0000685 Preamble += "#define __attribute__(X)\n";
Chris Lattner553e5832010-04-13 17:33:56 +0000686 Preamble += "#endif\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000687 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000688 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000689 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000690 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000691 Preamble += "#define __weak\n";
692 }
Fariborz Jahaniandf496522010-03-02 01:19:04 +0000693 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
694 // as this avoids warning in any 64bit/32bit compilation model.
695 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000696}
697
698
Chris Lattnerf04da132007-10-24 17:06:59 +0000699//===----------------------------------------------------------------------===//
700// Top Level Driver Code
701//===----------------------------------------------------------------------===//
702
Chris Lattner682bf922009-03-29 16:50:03 +0000703void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000704 if (Diags.hasErrorOccurred())
705 return;
706
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000707 // Two cases: either the decl could be in the main file, or it could be in a
708 // #included file. If the former, rewrite it now. If the later, check to see
709 // if we rewrote the #include/#import.
710 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000711 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000712
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000713 // If this is for a builtin, ignore it.
714 if (Loc.isInvalid()) return;
715
Steve Naroffebf2b562007-10-23 23:50:29 +0000716 // Look for built-in declarations that we need to refer during the rewrite.
717 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000718 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000719 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000720 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000721 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000722 ConstantStringClassReference = FVD;
723 return;
724 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000725 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000726 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000727 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000728 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000729 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000730 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000731 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000732 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000733 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000734 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
735 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000736 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
737 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000738 DI != DIEnd; ) {
739 if (isa<ObjCClassDecl>((*DI))) {
740 SmallVector<Decl *, 8> DG;
741 Decl *D = (*DI);
742 SourceLocation Loc = D->getLocation();
743 while (DI != DIEnd &&
744 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
745 DG.push_back(D);
746 ++DI;
747 D = (*DI);
748 }
749 RewriteForwardClassDecl(DG);
750 continue;
751 }
Chris Lattner682bf922009-03-29 16:50:03 +0000752 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000753 ++DI;
754 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000755 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000756 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000757 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000758 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000759}
760
Chris Lattnerf04da132007-10-24 17:06:59 +0000761//===----------------------------------------------------------------------===//
762// Syntactic (non-AST) Rewriting Code
763//===----------------------------------------------------------------------===//
764
Steve Naroffb29b4272008-04-14 22:03:09 +0000765void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000766 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000767 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000768 const char *MainBufStart = MainBuf.begin();
769 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000770 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000771
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000772 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000773 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
774 if (*BufPtr == '#') {
775 if (++BufPtr == MainBufEnd)
776 return;
777 while (*BufPtr == ' ' || *BufPtr == '\t')
778 if (++BufPtr == MainBufEnd)
779 return;
780 if (!strncmp(BufPtr, "import", ImportLen)) {
781 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000782 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000783 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000784 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000785 BufPtr += ImportLen;
786 }
787 }
788 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000789}
790
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000791static std::string getIvarAccessString(ObjCIvarDecl *OID) {
792 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000793 std::string S;
794 S = "((struct ";
795 S += ClassDecl->getIdentifier()->getName();
796 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000797 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000798 return S;
799}
800
Steve Naroffa0876e82008-12-02 17:36:43 +0000801void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
802 ObjCImplementationDecl *IMD,
803 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000804 static bool objcGetPropertyDefined = false;
805 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000806 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000807 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000808 const char *startBuf = SM->getCharacterData(startLoc);
809 assert((*startBuf == '@') && "bogus @synthesize location");
810 const char *semiBuf = strchr(startBuf, ';');
811 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000812 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000813 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000814
815 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
816 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000817
Steve Naroffeb0646c2008-12-02 15:48:25 +0000818 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000819 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000820 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000821
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000822 if (!OID)
823 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000824 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000825 if (!PD->getGetterMethodDecl()->isDefined()) {
826 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
827 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
828 ObjCPropertyDecl::OBJC_PR_copy));
829 std::string Getr;
830 if (GenGetProperty && !objcGetPropertyDefined) {
831 objcGetPropertyDefined = true;
832 // FIXME. Is this attribute correct in all cases?
833 Getr = "\nextern \"C\" __declspec(dllimport) "
834 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000835 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000836 RewriteObjCMethodDecl(OID->getContainingInterface(),
837 PD->getGetterMethodDecl(), Getr);
838 Getr += "{ ";
839 // Synthesize an explicit cast to gain access to the ivar.
840 // See objc-act.c:objc_synthesize_new_getter() for details.
841 if (GenGetProperty) {
842 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
843 Getr += "typedef ";
844 const FunctionType *FPRetType = 0;
845 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
846 FPRetType);
847 Getr += " _TYPE";
848 if (FPRetType) {
849 Getr += ")"; // close the precedence "scope" for "*".
850
851 // Now, emit the argument types (if any).
852 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
853 Getr += "(";
854 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
855 if (i) Getr += ", ";
856 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000857 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000858 Getr += ParamStr;
859 }
860 if (FT->isVariadic()) {
861 if (FT->getNumArgs()) Getr += ", ";
862 Getr += "...";
863 }
864 Getr += ")";
865 } else
866 Getr += "()";
867 }
868 Getr += ";\n";
869 Getr += "return (_TYPE)";
870 Getr += "objc_getProperty(self, _cmd, ";
871 SynthesizeIvarOffsetComputation(OID, Getr);
872 Getr += ", 1)";
873 }
874 else
875 Getr += "return " + getIvarAccessString(OID);
876 Getr += "; }";
877 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000878 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000879
880 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000881 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Steve Naroffeb0646c2008-12-02 15:48:25 +0000883 // Generate the 'setter' function.
884 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000885 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
886 ObjCPropertyDecl::OBJC_PR_copy);
887 if (GenSetProperty && !objcSetPropertyDefined) {
888 objcSetPropertyDefined = true;
889 // FIXME. Is this attribute correct in all cases?
890 Setr = "\nextern \"C\" __declspec(dllimport) "
891 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
892 }
893
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000894 RewriteObjCMethodDecl(OID->getContainingInterface(),
895 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000896 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000897 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000898 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000899 if (GenSetProperty) {
900 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000901 SynthesizeIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000902 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000903 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000904 Setr += ", ";
905 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
906 Setr += "0, ";
907 else
908 Setr += "1, ";
909 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
910 Setr += "1)";
911 else
912 Setr += "0)";
913 }
914 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000915 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000916 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000917 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000918 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000919 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000920}
Chris Lattner8a12c272007-10-11 18:38:32 +0000921
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000922static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
923 std::string &typedefString) {
924 typedefString += "#ifndef _REWRITER_typedef_";
925 typedefString += ForwardDecl->getNameAsString();
926 typedefString += "\n";
927 typedefString += "#define _REWRITER_typedef_";
928 typedefString += ForwardDecl->getNameAsString();
929 typedefString += "\n";
930 typedefString += "typedef struct objc_object ";
931 typedefString += ForwardDecl->getNameAsString();
932 typedefString += ";\n#endif\n";
933}
934
935void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
936 const std::string &typedefString) {
937 SourceLocation startLoc = ClassDecl->getLocation();
938 const char *startBuf = SM->getCharacterData(startLoc);
939 const char *semiPtr = strchr(startBuf, ';');
940 // Replace the @class with typedefs corresponding to the classes.
941 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
942}
943
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000944void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000945 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000946 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
947 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
948 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
949 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000950 // Translate to typedef's that forward reference structs with the same name
951 // as the class. As a convenience, we include the original declaration
952 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000953 typedefString += "// @class ";
954 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000955 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000956 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000957 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000958 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000959 DeclGroupRef::iterator I = D.begin();
960 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
961}
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000963void RewriteObjC::RewriteForwardClassDecl(
964 const llvm::SmallVector<Decl*, 8> &D) {
965 std::string typedefString;
966 for (unsigned i = 0; i < D.size(); i++) {
967 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
968 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
969 if (i == 0) {
970 typedefString += "// @class ";
971 typedefString += ForwardDecl->getNameAsString();
972 typedefString += ";\n";
973 }
974 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
975 }
976 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000977}
978
Steve Naroffb29b4272008-04-14 22:03:09 +0000979void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000980 // When method is a synthesized one, such as a getter/setter there is
981 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000982 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000983 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000984 SourceLocation LocStart = Method->getLocStart();
985 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Chandler Carruth64211622011-07-25 21:09:52 +0000987 if (SM->getExpansionLineNumber(LocEnd) >
988 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000989 InsertText(LocStart, "#if 0\n");
990 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000991 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000992 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000993 }
994}
995
Mike Stump1eb44332009-09-09 15:08:12 +0000996void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000997 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000998
Benjamin Kramerd999b372010-02-14 14:14:16 +0000999 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +00001000 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +00001001}
1002
Steve Naroffb29b4272008-04-14 22:03:09 +00001003void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +00001004 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Steve Naroff423cb562007-10-30 13:30:57 +00001006 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001007 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001008
Fariborz Jahanian13751e32010-02-10 01:15:09 +00001009 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1010 E = CatDecl->prop_end(); I != E; ++I)
1011 RewriteProperty(*I);
1012
Mike Stump1eb44332009-09-09 15:08:12 +00001013 for (ObjCCategoryDecl::instmeth_iterator
1014 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001015 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001016 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001017 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001018 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001019 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001020 RewriteMethodDeclaration(*I);
1021
Steve Naroff423cb562007-10-30 13:30:57 +00001022 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001023 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1024 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +00001025}
1026
Steve Naroffb29b4272008-04-14 22:03:09 +00001027void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +00001028 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Steve Naroff752d6ef2007-10-30 16:42:30 +00001030 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001031 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001032
1033 for (ObjCProtocolDecl::instmeth_iterator
1034 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001035 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001036 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +00001037 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001038 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001039 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001040 RewriteMethodDeclaration(*I);
1041
Fariborz Jahanian07acdf42010-09-24 18:36:58 +00001042 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1043 E = PDecl->prop_end(); I != E; ++I)
1044 RewriteProperty(*I);
1045
Steve Naroff752d6ef2007-10-30 16:42:30 +00001046 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001047 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001048 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +00001049
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001050 // Must comment out @optional/@required
1051 const char *startBuf = SM->getCharacterData(LocStart);
1052 const char *endBuf = SM->getCharacterData(LocEnd);
1053 for (const char *p = startBuf; p < endBuf; p++) {
1054 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001055 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001056 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +00001057
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001058 }
1059 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001060 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001061 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +00001062
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +00001063 }
1064 }
Steve Naroff752d6ef2007-10-30 16:42:30 +00001065}
1066
Steve Naroffb29b4272008-04-14 22:03:09 +00001067void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001068 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001069 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001070 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001071 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001072 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001073}
1074
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001075void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1076 const FunctionType *&FPRetType) {
1077 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001078 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001079 else if (T->isFunctionPointerType() ||
1080 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001081 // needs special handling, since pointer-to-functions have special
1082 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001083 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001084 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001085 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001086 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001087 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001088 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001089 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001090 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001091 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001092 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001093 }
1094 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001095 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001096}
1097
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001098void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1099 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001100 std::string &ResultStr) {
1101 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1102 const FunctionType *FPRetType = 0;
1103 ResultStr += "\nstatic ";
1104 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001105 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001106
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001107 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001108 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001109
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001110 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001111 NameStr += "_I_";
1112 else
1113 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001114
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001115 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001116 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001117
1118 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001119 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001120 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001121 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001122 }
Mike Stump1eb44332009-09-09 15:08:12 +00001123 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001124 {
1125 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001126 int len = selString.size();
1127 for (int i = 0; i < len; i++)
1128 if (selString[i] == ':')
1129 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001130 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001131 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001132 // Remember this name for metadata emission
1133 MethodInternalNames[OMD] = NameStr;
1134 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001135
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001136 // Rewrite arguments
1137 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001139 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001140 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001141 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001142 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001143 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001144 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001145 ResultStr += "struct ";
1146 }
1147 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001148 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001149 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001150 }
1151 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001152 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001153 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001154
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001155 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001156 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001157 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001158
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001159 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001160 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1161 E = OMD->param_end(); PI != E; ++PI) {
1162 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001164 if (PDecl->getType()->isObjCQualifiedIdType()) {
1165 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001166 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001167 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001168 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001169 QualType QT = PDecl->getType();
1170 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1171 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001172 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001173 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001174 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001175 ResultStr += Name;
1176 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001177 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001178 if (OMD->isVariadic())
1179 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001180 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001181
Steve Naroff76e429d2008-07-16 14:40:40 +00001182 if (FPRetType) {
1183 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001184
Steve Naroff76e429d2008-07-16 14:40:40 +00001185 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001186 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001187 ResultStr += "(";
1188 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1189 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001190 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001191 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001192 ResultStr += ParamStr;
1193 }
1194 if (FT->isVariadic()) {
1195 if (FT->getNumArgs()) ResultStr += ", ";
1196 ResultStr += "...";
1197 }
1198 ResultStr += ")";
1199 } else {
1200 ResultStr += "()";
1201 }
1202 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001203}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001204void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001205 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1206 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001207
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001208 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001209
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001210 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001211 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1212 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001213 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001214 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001215 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001216 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001217 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001218 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001219
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001220 const char *startBuf = SM->getCharacterData(LocStart);
1221 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001222 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001223 }
Mike Stump1eb44332009-09-09 15:08:12 +00001224
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001225 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001226 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1227 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001228 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001229 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001230 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001231 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001232 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001233 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001234
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001235 const char *startBuf = SM->getCharacterData(LocStart);
1236 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001237 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001238 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001239 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001240 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001241 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001242 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001243 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001244 }
1245
Benjamin Kramerd999b372010-02-14 14:14:16 +00001246 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001247}
1248
Steve Naroffb29b4272008-04-14 22:03:09 +00001249void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001250 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001251 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001252 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001253 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001254 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001255 ResultStr += "\n";
1256 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001257 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001258 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001259 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001260 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001261 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001262 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001263 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001264 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001265 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001266
1267 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001268 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001269 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001270 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001271 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001272 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001273 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001274 for (ObjCInterfaceDecl::classmeth_iterator
1275 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001276 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001277 RewriteMethodDeclaration(*I);
1278
Steve Naroff2feac5e2007-10-30 03:43:13 +00001279 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001280 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1281 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001282}
1283
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001284Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +00001285 SourceRange SrcRange) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001286 ObjCMethodDecl *OMD = 0;
1287 QualType Ty;
1288 Selector Sel;
Duncan Sands54bd4572010-10-20 08:21:16 +00001289 Stmt *Receiver = 0;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001290 bool Super = false;
1291 QualType SuperTy;
1292 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001293 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001294 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ObjCImplicitSetterGetterRefExpr.
Steve Naroffc77a6362008-12-04 16:24:46 +00001295 // This allows us to reuse all the fun and games in SynthMessageExpr().
John McCall12f78a62010-12-02 01:19:52 +00001296 if (ObjCPropertyRefExpr *PropRefExpr =
1297 dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS())) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001298 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001299 if (PropRefExpr->isExplicitProperty()) {
1300 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1301 OMD = PDecl->getSetterMethodDecl();
1302 Ty = PDecl->getType();
1303 Sel = PDecl->getSetterName();
1304 } else {
1305 OMD = PropRefExpr->getImplicitPropertySetter();
1306 Sel = OMD->getSelector();
1307 Ty = PropRefExpr->getType();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001308 }
John McCall12f78a62010-12-02 01:19:52 +00001309 Super = PropRefExpr->isSuperReceiver();
1310 if (!Super) {
1311 Receiver = PropRefExpr->getBase();
1312 } else {
1313 SuperTy = PropRefExpr->getSuperReceiverType();
1314 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001315 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001316 }
1317
1318 assert(OMD && "RewritePropertyOrImplicitSetter - null OMD");
Mike Stump1eb44332009-09-09 15:08:12 +00001319
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001320 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001321 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001322 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001323 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001324 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001325 /*FIXME?*/SourceLocation(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001326 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001327 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001328 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001329 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001330 newStmt,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001331 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001332 else {
1333 // FIXME. Refactor this into common code with that in
1334 // RewritePropertyOrImplicitGetter
1335 assert(Receiver && "RewritePropertyOrImplicitSetter - null Receiver");
1336 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1337 if (PropGetters[Exp])
1338 // This allows us to handle chain/nested property/implicit getters.
1339 Receiver = PropGetters[Exp];
1340
Douglas Gregor04badcf2010-04-21 00:45:42 +00001341 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001342 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001343 Expr::getValueKindForType(Ty),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001344 /*FIXME: */SourceLocation(),
1345 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001346 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001347 newStmt,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001348 /*FIXME:*/SourceLocation());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001349 }
Steve Naroffc77a6362008-12-04 16:24:46 +00001350 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001351
Steve Naroffc77a6362008-12-04 16:24:46 +00001352 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001353 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001354 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001355 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1356 // to things that stay around.
1357 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001358 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001359}
1360
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001361Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(Expr *PropOrGetterRefExpr) {
1362 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr or ImplicitGetter.
Steve Naroff15f081d2008-12-03 00:56:33 +00001363 // This allows us to reuse all the fun and games in SynthMessageExpr().
Ted Kremenek3b562af2010-10-19 23:10:22 +00001364 Stmt *Receiver = 0;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001365 ObjCMethodDecl *OMD = 0;
1366 QualType Ty;
1367 Selector Sel;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001368 bool Super = false;
1369 QualType SuperTy;
1370 SourceLocation SuperLocation;
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001371 SourceLocation SelectorLoc;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001372 if (ObjCPropertyRefExpr *PropRefExpr =
1373 dyn_cast<ObjCPropertyRefExpr>(PropOrGetterRefExpr)) {
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001374 SelectorLoc = PropRefExpr->getLocation();
John McCall12f78a62010-12-02 01:19:52 +00001375 if (PropRefExpr->isExplicitProperty()) {
1376 ObjCPropertyDecl *PDecl = PropRefExpr->getExplicitProperty();
1377 OMD = PDecl->getGetterMethodDecl();
1378 Ty = PDecl->getType();
1379 Sel = PDecl->getGetterName();
1380 } else {
1381 OMD = PropRefExpr->getImplicitPropertyGetter();
1382 Sel = OMD->getSelector();
1383 Ty = PropRefExpr->getType();
1384 }
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001385 Super = PropRefExpr->isSuperReceiver();
1386 if (!Super)
1387 Receiver = PropRefExpr->getBase();
1388 else {
John McCall12f78a62010-12-02 01:19:52 +00001389 SuperTy = PropRefExpr->getSuperReceiverType();
1390 SuperLocation = PropRefExpr->getReceiverLocation();
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001391 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001392 }
1393
1394 assert (OMD && "RewritePropertyOrImplicitGetter - OMD is null");
1395
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001396 ObjCMessageExpr *MsgExpr;
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001397 if (Super)
Douglas Gregor04badcf2010-04-21 00:45:42 +00001398 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001399 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001400 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001401 PropOrGetterRefExpr->getLocStart(),
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001402 SuperLocation,
Douglas Gregor04badcf2010-04-21 00:45:42 +00001403 /*IsInstanceSuper=*/true,
Fariborz Jahanian8ac2d442010-10-14 16:04:05 +00001404 SuperTy,
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001405 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001406 ArrayRef<Expr*>(),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001407 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001408 else {
1409 assert (Receiver && "RewritePropertyOrImplicitGetter - Receiver is null");
1410 if (Expr *Exp = dyn_cast<Expr>(Receiver))
1411 if (PropGetters[Exp])
1412 // This allows us to handle chain/nested property/implicit getters.
1413 Receiver = PropGetters[Exp];
Douglas Gregor04badcf2010-04-21 00:45:42 +00001414 MsgExpr = ObjCMessageExpr::Create(*Context,
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001415 Ty.getNonReferenceType(),
John McCallf89e55a2010-11-18 06:31:45 +00001416 Expr::getValueKindForType(Ty),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001417 PropOrGetterRefExpr->getLocStart(),
Douglas Gregor04badcf2010-04-21 00:45:42 +00001418 cast<Expr>(Receiver),
Argyrios Kyrtzidisf40f0d52010-12-10 20:08:27 +00001419 Sel, SelectorLoc, OMD,
Argyrios Kyrtzidis8d9ed792011-10-03 06:36:45 +00001420 ArrayRef<Expr*>(),
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001421 PropOrGetterRefExpr->getLocEnd());
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001422 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001423
Fariborz Jahanianbaac58d2011-02-26 00:33:41 +00001424 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr, MsgExpr->getLocStart(),
1425 MsgExpr->getLocEnd());
Steve Naroff8599e7a2008-12-08 16:43:47 +00001426
1427 if (!PropParentMap)
1428 PropParentMap = new ParentMap(CurrentBody);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001429 bool NestedPropertyRef = false;
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001430 Stmt *Parent = PropParentMap->getParent(PropOrGetterRefExpr);
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001431 ImplicitCastExpr*ICE=0;
1432 if (Parent)
1433 if ((ICE = dyn_cast<ImplicitCastExpr>(Parent))) {
1434 assert((ICE->getCastKind() == CK_GetObjCProperty)
1435 && "RewritePropertyOrImplicitGetter");
1436 Parent = PropParentMap->getParent(Parent);
1437 NestedPropertyRef = (Parent && isa<ObjCPropertyRefExpr>(Parent));
1438 }
1439 if (NestedPropertyRef) {
Steve Naroff8599e7a2008-12-08 16:43:47 +00001440 // We stash away the ReplacingStmt since actually doing the
1441 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
Fariborz Jahanian3cd1ea32010-12-04 21:22:13 +00001442 PropGetters[ICE] = ReplacingStmt;
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);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001446 return PropOrGetterRefExpr; // return the original...
Steve Naroff8599e7a2008-12-08 16:43:47 +00001447 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001448 ReplaceStmt(PropOrGetterRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001449 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001450 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1451 // to things that stay around.
1452 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001453 return ReplacingStmt;
1454 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001455}
1456
Mike Stump1eb44332009-09-09 15:08:12 +00001457Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001458 SourceLocation OrigStart,
1459 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001460 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001461 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001462 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001463 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001464 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001465 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001466 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001467 // lookup which class implements the instance variable.
1468 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001469 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001470 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001471 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001472
Steve Narofff0757612008-05-08 17:52:16 +00001473 // Synthesize an explicit cast to gain access to the ivar.
1474 std::string RecName = clsDeclared->getIdentifier()->getName();
1475 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001476 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001477 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001478 SourceLocation(), SourceLocation(),
1479 II);
Steve Narofff0757612008-05-08 17:52:16 +00001480 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1481 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001482 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001483 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001484 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001485 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001486 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
John McCallf89e55a2010-11-18 06:31:45 +00001487 IV->getBase()->getLocEnd(),
1488 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001489 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001490 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001491 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001492 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
John McCallf89e55a2010-11-18 06:31:45 +00001493 IV->getLocation(),
1494 D->getType(),
1495 VK_LValue, OK_Ordinary);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001496 // delete IV; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001497 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001498 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001499 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001500 // Cannot delete IV->getBase(), since PE points to it.
1501 // Replace the old base with the cast. This is important when doing
1502 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001503 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001504 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001505 }
Steve Naroff84472a82008-04-18 21:55:08 +00001506 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001507 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001508
Steve Naroff9f525972008-05-06 23:20:07 +00001509 // Explicit ivar refs need to have a cast inserted.
1510 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001511 if (BaseExpr->getType()->isObjCObjectPointerType()) {
John McCallf4c73712011-01-19 06:33:43 +00001512 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001513 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001514 // lookup which class implements the instance variable.
1515 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001516 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001517 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001518 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001519
Steve Naroff9f525972008-05-06 23:20:07 +00001520 // Synthesize an explicit cast to gain access to the ivar.
1521 std::string RecName = clsDeclared->getIdentifier()->getName();
1522 RecName += "_IMPL";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001523 IdentifierInfo *II = &Context->Idents.get(RecName);
Abramo Bagnara465d41b2010-05-11 21:36:43 +00001524 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00001525 SourceLocation(), SourceLocation(),
1526 II);
Steve Naroff9f525972008-05-06 23:20:07 +00001527 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1528 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001529 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
John McCalla5bbc502010-11-15 09:46:46 +00001530 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00001531 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001532 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001533 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001534 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001535 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001536 // Cannot delete IV->getBase(), since PE points to it.
1537 // Replace the old base with the cast. This is important when doing
1538 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001539 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001540 return IV;
1541 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001542 }
Steve Naroff84472a82008-04-18 21:55:08 +00001543 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001544}
1545
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001546Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
John McCall7502c1d2011-02-13 04:07:26 +00001547 for (Stmt::child_range CI = S->children(); CI; ++CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001548 if (*CI) {
1549 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1550 if (newStmt)
1551 *CI = newStmt;
1552 }
1553 }
1554 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1555 SourceRange OrigStmtRange = S->getSourceRange();
1556 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1557 replaced);
1558 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001559 }
1560 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1561 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1562 return newStmt;
1563 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001564 return S;
1565}
1566
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001567/// SynthCountByEnumWithState - To print:
1568/// ((unsigned int (*)
1569/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001570/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001571/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001572/// "countByEnumeratingWithState:objects:count:"),
1573/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001574/// (id *)items, (unsigned int)16)
1575///
Steve Naroffb29b4272008-04-14 22:03:09 +00001576void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001577 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1578 "id *, unsigned int))(void *)objc_msgSend)";
1579 buf += "\n\t\t";
1580 buf += "((id)l_collection,\n\t\t";
1581 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1582 buf += "\n\t\t";
1583 buf += "&enumState, "
1584 "(id *)items, (unsigned int)16)";
1585}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001586
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001587/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1588/// statement to exit to its outer synthesized loop.
1589///
Steve Naroffb29b4272008-04-14 22:03:09 +00001590Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001591 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1592 return S;
1593 // replace break with goto __break_label
1594 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001595
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001596 SourceLocation startLoc = S->getLocStart();
1597 buf = "goto __break_label_";
1598 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001599 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001600
1601 return 0;
1602}
1603
1604/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1605/// statement to continue with its inner synthesized loop.
1606///
Steve Naroffb29b4272008-04-14 22:03:09 +00001607Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001608 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1609 return S;
1610 // replace continue with goto __continue_label
1611 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001612
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001613 SourceLocation startLoc = S->getLocStart();
1614 buf = "goto __continue_label_";
1615 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001616 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001617
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001618 return 0;
1619}
1620
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001621/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001622/// It rewrites:
1623/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001624
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001625/// Into:
1626/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001627/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001628/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001629/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001630/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001631/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001632/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001633/// if (limit) {
1634/// unsigned long startMutations = *enumState.mutationsPtr;
1635/// do {
1636/// unsigned long counter = 0;
1637/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001638/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001639/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001640/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001641/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001642/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001643/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001644/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001645/// objects:items count:16]);
1646/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001647/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001648/// }
1649/// else
1650/// elem = nil;
1651/// }
1652///
Steve Naroffb29b4272008-04-14 22:03:09 +00001653Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001654 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001655 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001656 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001657 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001658 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001659 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001660
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001661 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001662 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001663 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001664 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001665 std::string buf;
1666 buf = "\n{\n\t";
1667 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1668 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001669 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001670 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001671 if (ElementType->isObjCQualifiedIdType() ||
1672 ElementType->isObjCQualifiedInterfaceType())
1673 // Simply use 'id' for all qualified types.
1674 elementTypeAsString = "id";
1675 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001676 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001677 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001678 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001679 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001680 buf += elementName;
1681 buf += ";\n\t";
1682 }
Chris Lattner06767512008-04-08 05:52:18 +00001683 else {
1684 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001685 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001686 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1687 if (VD->getType()->isObjCQualifiedIdType() ||
1688 VD->getType()->isObjCQualifiedInterfaceType())
1689 // Simply use 'id' for all qualified types.
1690 elementTypeAsString = "id";
1691 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001692 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001693 }
Mike Stump1eb44332009-09-09 15:08:12 +00001694
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001695 // struct __objcFastEnumerationState enumState = { 0 };
1696 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1697 // id items[16];
1698 buf += "id items[16];\n\t";
1699 // id l_collection = (id)
1700 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001701 // Find start location of 'collection' the hard way!
1702 const char *startCollectionBuf = startBuf;
1703 startCollectionBuf += 3; // skip 'for'
1704 startCollectionBuf = strchr(startCollectionBuf, '(');
1705 startCollectionBuf++; // skip '('
1706 // find 'in' and skip it.
1707 while (*startCollectionBuf != ' ' ||
1708 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1709 (*(startCollectionBuf+3) != ' ' &&
1710 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1711 startCollectionBuf++;
1712 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001713
1714 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001715 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001716 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001717 SourceLocation rightParenLoc = S->getRParenLoc();
1718 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001719 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001720 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001721
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001722 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1723 // objects:items count:16];
1724 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001725 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001726 // ((unsigned int (*)
1727 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001728 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001729 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001730 // "countByEnumeratingWithState:objects:count:"),
1731 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001732 // (id *)items, (unsigned int)16);
1733 buf += "unsigned long limit =\n\t\t";
1734 SynthCountByEnumWithState(buf);
1735 buf += ";\n\t";
1736 /// if (limit) {
1737 /// unsigned long startMutations = *enumState.mutationsPtr;
1738 /// do {
1739 /// unsigned long counter = 0;
1740 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001741 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001742 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001743 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001744 buf += "if (limit) {\n\t";
1745 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1746 buf += "do {\n\t\t";
1747 buf += "unsigned long counter = 0;\n\t\t";
1748 buf += "do {\n\t\t\t";
1749 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1750 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1751 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001752 buf += " = (";
1753 buf += elementTypeAsString;
1754 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001755 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001756 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001757
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001758 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001759 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001760 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001761 /// objects:items count:16]);
1762 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001763 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001764 /// }
1765 /// else
1766 /// elem = nil;
1767 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001768 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001769 buf = ";\n\t";
1770 buf += "__continue_label_";
1771 buf += utostr(ObjCBcLabelNo.back());
1772 buf += ": ;";
1773 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001774 buf += "} while (counter < limit);\n\t";
1775 buf += "} while (limit = ";
1776 SynthCountByEnumWithState(buf);
1777 buf += ");\n\t";
1778 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001779 buf += " = ((";
1780 buf += elementTypeAsString;
1781 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001782 buf += "__break_label_";
1783 buf += utostr(ObjCBcLabelNo.back());
1784 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001785 buf += "}\n\t";
1786 buf += "else\n\t\t";
1787 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001788 buf += " = ((";
1789 buf += elementTypeAsString;
1790 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001791 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001793 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001794 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001795 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001796 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001797 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001798 } else {
1799 /* Need to treat single statements specially. For example:
1800 *
1801 * for (A *a in b) if (stuff()) break;
1802 * for (A *a in b) xxxyy;
1803 *
1804 * The following code simply scans ahead to the semi to find the actual end.
1805 */
1806 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1807 const char *semiBuf = strchr(stmtBuf, ';');
1808 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001809 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001810 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001811 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001812 Stmts.pop_back();
1813 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001814 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001815}
1816
Mike Stump1eb44332009-09-09 15:08:12 +00001817/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001818/// This routine rewrites @synchronized(expr) stmt;
1819/// into:
1820/// objc_sync_enter(expr);
1821/// @try stmt @finally { objc_sync_exit(expr); }
1822///
Steve Naroffb29b4272008-04-14 22:03:09 +00001823Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001824 // Get the start location and compute the semi location.
1825 SourceLocation startLoc = S->getLocStart();
1826 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001827
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001828 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001829
1830 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001831 buf = "objc_sync_enter((id)";
1832 const char *lparenBuf = startBuf;
1833 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001834 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001835 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1836 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001837 // been rewritten! (which implies the SourceLocation's are invalid).
1838 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001839 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001840 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001841 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001842 buf = ");\n";
1843 // declare a new scope with two variables, _stack and _rethrow.
1844 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1845 buf += "int buf[18/*32-bit i386*/];\n";
1846 buf += "char *pointers[4];} _stack;\n";
1847 buf += "id volatile _rethrow = 0;\n";
1848 buf += "objc_exception_try_enter(&_stack);\n";
1849 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001850 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001851 startLoc = S->getSynchBody()->getLocEnd();
1852 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Steve Naroffc7089f12008-08-19 13:04:19 +00001854 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001855 SourceLocation lastCurlyLoc = startLoc;
1856 buf = "}\nelse {\n";
1857 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001858 buf += "}\n";
1859 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001860 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001861
1862 std::string syncBuf;
1863 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001864
1865 Expr *syncExpr = S->getSynchExpr();
1866 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1867 ? CK_BitCast :
1868 syncExpr->getType()->isBlockPointerType()
1869 ? CK_BlockPointerToObjCPointerCast
1870 : CK_CPointerToObjCPointerCast;
1871 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1872 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001873 std::string syncExprBufS;
1874 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001875 syncExpr->printPretty(syncExprBuf, *Context, 0,
1876 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001877 syncBuf += syncExprBuf.str();
1878 syncBuf += ");";
1879
1880 buf += syncBuf;
1881 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001882 buf += "}\n";
1883 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001884
Benjamin Kramerd999b372010-02-14 14:14:16 +00001885 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001886
1887 bool hasReturns = false;
1888 HasReturnStmts(S->getSynchBody(), hasReturns);
1889 if (hasReturns)
1890 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1891
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001892 return 0;
1893}
1894
Steve Naroffb85e77a2009-12-05 21:43:12 +00001895void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1896{
Steve Naroff8c565152008-12-05 17:03:39 +00001897 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001898 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001899 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001900 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001901
Steve Naroffb85e77a2009-12-05 21:43:12 +00001902 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001903 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001904 TryFinallyContainsReturnDiag);
1905 }
1906 return;
1907}
1908
Steve Naroffb85e77a2009-12-05 21:43:12 +00001909void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1910{
1911 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001912 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001913 if (*CI)
1914 HasReturnStmts(*CI, hasReturns);
1915
1916 if (isa<ReturnStmt>(S))
1917 hasReturns = true;
1918 return;
1919}
1920
1921void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1922 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001923 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001924 if (*CI) {
1925 RewriteTryReturnStmts(*CI);
1926 }
1927 if (isa<ReturnStmt>(S)) {
1928 SourceLocation startLoc = S->getLocStart();
1929 const char *startBuf = SM->getCharacterData(startLoc);
1930
1931 const char *semiBuf = strchr(startBuf, ';');
1932 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001933 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001934
1935 std::string buf;
1936 buf = "{ objc_exception_try_exit(&_stack); return";
1937
Benjamin Kramerd999b372010-02-14 14:14:16 +00001938 ReplaceText(startLoc, 6, buf);
1939 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001940 }
1941 return;
1942}
1943
1944void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1945 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001946 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001947 if (*CI) {
1948 RewriteSyncReturnStmts(*CI, syncExitBuf);
1949 }
1950 if (isa<ReturnStmt>(S)) {
1951 SourceLocation startLoc = S->getLocStart();
1952 const char *startBuf = SM->getCharacterData(startLoc);
1953
1954 const char *semiBuf = strchr(startBuf, ';');
1955 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001956 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001957
1958 std::string buf;
1959 buf = "{ objc_exception_try_exit(&_stack);";
1960 buf += syncExitBuf;
1961 buf += " return";
1962
Benjamin Kramerd999b372010-02-14 14:14:16 +00001963 ReplaceText(startLoc, 6, buf);
1964 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001965 }
1966 return;
1967}
1968
Steve Naroffb29b4272008-04-14 22:03:09 +00001969Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001970 // Get the start location and compute the semi location.
1971 SourceLocation startLoc = S->getLocStart();
1972 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Steve Naroff75730982007-11-07 04:08:17 +00001974 assert((*startBuf == '@') && "bogus @try location");
1975
1976 std::string buf;
1977 // declare a new scope with two variables, _stack and _rethrow.
1978 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1979 buf += "int buf[18/*32-bit i386*/];\n";
1980 buf += "char *pointers[4];} _stack;\n";
1981 buf += "id volatile _rethrow = 0;\n";
1982 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001983 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001984
Benjamin Kramerd999b372010-02-14 14:14:16 +00001985 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001986
Steve Naroff75730982007-11-07 04:08:17 +00001987 startLoc = S->getTryBody()->getLocEnd();
1988 startBuf = SM->getCharacterData(startLoc);
1989
1990 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Steve Naroff75730982007-11-07 04:08:17 +00001992 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001993 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001994 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001995 buf = " /* @catch begin */ else {\n";
1996 buf += " id _caught = objc_exception_extract(&_stack);\n";
1997 buf += " objc_exception_try_enter (&_stack);\n";
1998 buf += " if (_setjmp(_stack.buf))\n";
1999 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2000 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Benjamin Kramerd999b372010-02-14 14:14:16 +00002002 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00002003 } else { /* no catch list */
2004 buf = "}\nelse {\n";
2005 buf += " _rethrow = objc_exception_extract(&_stack);\n";
2006 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002007 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00002008 }
Steve Naroff75730982007-11-07 04:08:17 +00002009 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002010 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2011 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00002012 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00002013
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002014 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00002015 buf = "if ("; // we are generating code for the first catch clause
2016 else
2017 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002018 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00002019 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002020
Steve Naroff75730982007-11-07 04:08:17 +00002021 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00002022
Steve Naroff75730982007-11-07 04:08:17 +00002023 const char *lParenLoc = strchr(startBuf, '(');
2024
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002025 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00002026 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002027 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00002028 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2029 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002030 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00002031 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00002032 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002033
Steve Naroffe12e6922008-02-01 20:02:07 +00002034 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00002035 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00002036 } else if (catchDecl) {
2037 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002038 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00002039 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002040 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00002041 } else if (const ObjCObjectPointerType *Ptr =
2042 t->getAs<ObjCObjectPointerType>()) {
2043 // Should be a pointer to a class.
2044 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2045 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00002046 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00002047 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00002048 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002049 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00002050 }
2051 }
2052 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00002053 lastCatchBody = Catch->getCatchBody();
2054 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00002055 SourceLocation bodyLoc = lastCatchBody->getLocStart();
2056 const char *bodyBuf = SM->getCharacterData(bodyLoc);
2057 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2058 assert((*rParenBuf == ')') && "bogus @catch paren location");
2059 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002060
Mike Stump1eb44332009-09-09 15:08:12 +00002061 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00002062 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00002063 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00002064 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00002065 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00002066 }
Steve Naroff75730982007-11-07 04:08:17 +00002067 }
2068 // Complete the catch list...
2069 if (lastCatchBody) {
2070 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002071 assert(*SM->getCharacterData(bodyLoc) == '}' &&
2072 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Steve Naroff378f47a2008-09-11 15:29:03 +00002074 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002075 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00002076 buf = "} /* last catch end */\n";
2077 buf += "else {\n";
2078 buf += " _rethrow = _caught;\n";
2079 buf += " objc_exception_try_exit(&_stack);\n";
2080 buf += "} } /* @catch end */\n";
2081 if (!S->getFinallyStmt())
2082 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002083 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002084
Steve Naroff75730982007-11-07 04:08:17 +00002085 // Set lastCurlyLoc
2086 lastCurlyLoc = lastCatchBody->getLocEnd();
2087 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002088 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00002089 startLoc = finalStmt->getLocStart();
2090 startBuf = SM->getCharacterData(startLoc);
2091 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00002092
Benjamin Kramerd999b372010-02-14 14:14:16 +00002093 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00002094
Steve Naroff75730982007-11-07 04:08:17 +00002095 Stmt *body = finalStmt->getFinallyBody();
2096 SourceLocation startLoc = body->getLocStart();
2097 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00002098 assert(*SM->getCharacterData(startLoc) == '{' &&
2099 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002100 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00002101 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00002102
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002103 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002104 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002105 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002106 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Steve Naroff75730982007-11-07 04:08:17 +00002108 // Set lastCurlyLoc
2109 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002110
Steve Naroff8c565152008-12-05 17:03:39 +00002111 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00002112 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00002113 } else { /* no finally clause - make sure we synthesize an implicit one */
2114 buf = "{ /* implicit finally clause */\n";
2115 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
2116 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
2117 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002118 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00002119
2120 // Now check for any return/continue/go statements within the @try.
2121 // The implicit finally clause won't called if the @try contains any
2122 // jump statements.
2123 bool hasReturns = false;
2124 HasReturnStmts(S->getTryBody(), hasReturns);
2125 if (hasReturns)
2126 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00002127 }
2128 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002129 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002130 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002131 return 0;
2132}
2133
Mike Stump1eb44332009-09-09 15:08:12 +00002134// This can't be done with ReplaceStmt(S, ThrowExpr), since
2135// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00002136// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00002137Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00002138 // Get the start location and compute the semi location.
2139 SourceLocation startLoc = S->getLocStart();
2140 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Steve Naroff2bd03922007-11-07 15:32:26 +00002142 assert((*startBuf == '@') && "bogus @throw location");
2143
2144 std::string buf;
2145 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00002146 if (S->getThrowExpr())
2147 buf = "objc_exception_throw(";
2148 else // add an implicit argument
2149 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Steve Naroff4ba0acb2008-07-25 15:41:30 +00002151 // handle "@ throw" correctly.
2152 const char *wBuf = strchr(startBuf, 'w');
2153 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00002154 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Steve Naroff2bd03922007-11-07 15:32:26 +00002156 const char *semiBuf = strchr(startBuf, ';');
2157 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002158 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002159 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00002160 return 0;
2161}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00002162
Steve Naroffb29b4272008-04-14 22:03:09 +00002163Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00002164 // Create a new string expression.
2165 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00002166 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00002167 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00002168 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00002169 StringLiteral::Ascii, false,
2170 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002171 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00002172
Chris Lattner07506182007-11-30 22:53:43 +00002173 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002174 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00002175 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00002176}
2177
Steve Naroffb29b4272008-04-14 22:03:09 +00002178Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00002179 if (!SelGetUidFunctionDecl)
2180 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00002181 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2182 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00002183 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00002184 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002185 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002186 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002187 StringLiteral::Ascii, false,
2188 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00002189 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2190 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002191 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002192 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00002193 return SelExp;
2194}
2195
Steve Naroffb29b4272008-04-14 22:03:09 +00002196CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002197 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2198 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002199 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002200 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002201
Steve Naroffebf2b562007-10-23 23:50:29 +00002202 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002203 DeclRefExpr *DRE =
2204 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002205
Steve Naroffebf2b562007-10-23 23:50:29 +00002206 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002207 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002208 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002209 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002210 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002211
John McCall183700f2009-09-21 23:43:11 +00002212 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002214 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002215 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002216 FT->getCallResultType(*Context),
2217 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002218 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002219}
2220
Steve Naroffd5255f52007-11-01 13:24:47 +00002221static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2222 const char *&startRef, const char *&endRef) {
2223 while (startBuf < endBuf) {
2224 if (*startBuf == '<')
2225 startRef = startBuf; // mark the start.
2226 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002227 if (startRef && *startRef == '<') {
2228 endRef = startBuf; // mark the end.
2229 return true;
2230 }
2231 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002232 }
2233 startBuf++;
2234 }
2235 return false;
2236}
2237
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002238static void scanToNextArgument(const char *&argRef) {
2239 int angle = 0;
2240 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2241 if (*argRef == '<')
2242 angle++;
2243 else if (*argRef == '>')
2244 angle--;
2245 argRef++;
2246 }
2247 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2248}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002249
Steve Naroffb29b4272008-04-14 22:03:09 +00002250bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002251 if (T->isObjCQualifiedIdType())
2252 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002253 if (const PointerType *PT = T->getAs<PointerType>()) {
2254 if (PT->getPointeeType()->isObjCQualifiedIdType())
2255 return true;
2256 }
2257 if (T->isObjCObjectPointerType()) {
2258 T = T->getPointeeType();
2259 return T->isObjCQualifiedInterfaceType();
2260 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002261 if (T->isArrayType()) {
2262 QualType ElemTy = Context->getBaseElementType(T);
2263 return needToScanForQualifiers(ElemTy);
2264 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002265 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002266}
2267
Steve Naroff4f95b752008-07-29 18:15:38 +00002268void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2269 QualType Type = E->getType();
2270 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002271 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002272
Steve Naroffcda658e2008-11-19 21:15:47 +00002273 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2274 Loc = ECE->getLParenLoc();
2275 EndLoc = ECE->getRParenLoc();
2276 } else {
2277 Loc = E->getLocStart();
2278 EndLoc = E->getLocEnd();
2279 }
2280 // This will defend against trying to rewrite synthesized expressions.
2281 if (Loc.isInvalid() || EndLoc.isInvalid())
2282 return;
2283
Steve Naroff4f95b752008-07-29 18:15:38 +00002284 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002285 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002286 const char *startRef = 0, *endRef = 0;
2287 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2288 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002289 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2290 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002291 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002292 InsertText(LessLoc, "/*");
2293 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002294 }
2295 }
2296}
2297
Steve Naroffb29b4272008-04-14 22:03:09 +00002298void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002299 SourceLocation Loc;
2300 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002301 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002302 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2303 Loc = VD->getLocation();
2304 Type = VD->getType();
2305 }
2306 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2307 Loc = FD->getLocation();
2308 // Check for ObjC 'id' and class types that have been adorned with protocol
2309 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002310 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002311 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002312 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002313 if (!proto)
2314 return;
2315 Type = proto->getResultType();
2316 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002317 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2318 Loc = FD->getLocation();
2319 Type = FD->getType();
2320 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002321 else
2322 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002323
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002324 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002325 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002326
Steve Naroffd5255f52007-11-01 13:24:47 +00002327 const char *endBuf = SM->getCharacterData(Loc);
2328 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002329 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002330 startBuf--; // scan backward (from the decl location) for return type.
2331 const char *startRef = 0, *endRef = 0;
2332 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2333 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002334 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2335 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002336 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002337 InsertText(LessLoc, "/*");
2338 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002339 }
2340 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002341 if (!proto)
2342 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002343 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002344 const char *startBuf = SM->getCharacterData(Loc);
2345 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002346 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2347 if (needToScanForQualifiers(proto->getArgType(i))) {
2348 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002349
Steve Naroffd5255f52007-11-01 13:24:47 +00002350 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002351 // scan forward (from the decl location) for argument types.
2352 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002353 const char *startRef = 0, *endRef = 0;
2354 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2355 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002356 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002357 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002358 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002359 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002360 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002361 InsertText(LessLoc, "/*");
2362 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002363 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002364 startBuf = ++endBuf;
2365 }
2366 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002367 // If the function name is derived from a macro expansion, then the
2368 // argument buffer will not follow the name. Need to speak with Chris.
2369 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002370 startBuf++; // scan forward (from the decl location) for argument types.
2371 startBuf++;
2372 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002373 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002374}
2375
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002376void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2377 QualType QT = ND->getType();
2378 const Type* TypePtr = QT->getAs<Type>();
2379 if (!isa<TypeOfExprType>(TypePtr))
2380 return;
2381 while (isa<TypeOfExprType>(TypePtr)) {
2382 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2383 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2384 TypePtr = QT->getAs<Type>();
2385 }
2386 // FIXME. This will not work for multiple declarators; as in:
2387 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002388 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002389 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2390 const char *startBuf = SM->getCharacterData(DeclLoc);
2391 if (ND->getInit()) {
2392 std::string Name(ND->getNameAsString());
2393 TypeAsString += " " + Name + " = ";
2394 Expr *E = ND->getInit();
2395 SourceLocation startLoc;
2396 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2397 startLoc = ECE->getLParenLoc();
2398 else
2399 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002400 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002401 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002402 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002403 }
2404 else {
2405 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002406 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002407 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002408 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002409 }
2410}
2411
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002412// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002413void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002414 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002415 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002416 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002417 QualType getFuncType =
2418 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002419 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002420 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002421 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002422 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002423 SC_Extern,
2424 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002425}
2426
Steve Naroffb29b4272008-04-14 22:03:09 +00002427void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002428 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002429 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002430 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002431 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002432 return;
2433 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002434 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002435}
2436
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002437void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002438 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002439 const char *argPtr = TypeString.c_str();
2440 if (!strchr(argPtr, '^')) {
2441 Str += TypeString;
2442 return;
2443 }
2444 while (*argPtr) {
2445 Str += (*argPtr == '^' ? '*' : *argPtr);
2446 argPtr++;
2447 }
2448}
2449
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002450// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002451void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2452 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002453 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002454 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002455 const char *argPtr = TypeString.c_str();
2456 int paren = 0;
2457 while (*argPtr) {
2458 switch (*argPtr) {
2459 case '(':
2460 Str += *argPtr;
2461 paren++;
2462 break;
2463 case ')':
2464 Str += *argPtr;
2465 paren--;
2466 break;
2467 case '^':
2468 Str += '*';
2469 if (paren == 1)
2470 Str += VD->getNameAsString();
2471 break;
2472 default:
2473 Str += *argPtr;
2474 break;
2475 }
2476 argPtr++;
2477 }
2478}
2479
2480
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002481void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2482 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2483 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2484 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2485 if (!proto)
2486 return;
2487 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002488 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002489 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002490 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002491 FdStr += "(";
2492 unsigned numArgs = proto->getNumArgs();
2493 for (unsigned i = 0; i < numArgs; i++) {
2494 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002495 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002496 if (i+1 < numArgs)
2497 FdStr += ", ";
2498 }
2499 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002500 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002501 CurFunctionDeclToDeclareForBlock = 0;
2502}
2503
Steve Naroffc0a123c2008-03-11 17:37:02 +00002504// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002505void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002506 if (SuperContructorFunctionDecl)
2507 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002508 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002509 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002510 QualType argT = Context->getObjCIdType();
2511 assert(!argT.isNull() && "Can't find 'id' type");
2512 ArgTys.push_back(argT);
2513 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002514 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2515 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002516 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002517 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002518 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002519 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002520 SC_Extern,
2521 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002522}
2523
Steve Naroff09b266e2007-10-30 23:14:51 +00002524// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002525void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002526 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002527 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002528 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002529 assert(!argT.isNull() && "Can't find 'id' type");
2530 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002531 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002532 assert(!argT.isNull() && "Can't find 'SEL' type");
2533 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002534 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2535 &ArgTys[0], ArgTys.size(),
2536 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002537 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002538 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002539 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002540 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002541 SC_Extern,
2542 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002543}
2544
Steve Naroff874e2322007-11-15 10:28:18 +00002545// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002546void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002547 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002548 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002549 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002550 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002551 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002552 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2553 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2554 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002555 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002556 assert(!argT.isNull() && "Can't find 'SEL' type");
2557 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002558 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2559 &ArgTys[0], ArgTys.size(),
2560 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002561 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002562 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002563 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002564 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002565 SC_Extern,
2566 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002567}
2568
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002569// SynthMsgSendStretFunctionDecl - void objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002570void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002571 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002572 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002573 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002574 assert(!argT.isNull() && "Can't find 'id' type");
2575 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002576 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002577 assert(!argT.isNull() && "Can't find 'SEL' type");
2578 ArgTys.push_back(argT);
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002579 QualType msgSendType = getSimpleFunctionType(Context->VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00002580 &ArgTys[0], ArgTys.size(),
2581 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002582 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002583 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002584 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002585 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002586 SC_Extern,
2587 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002588}
2589
Mike Stump1eb44332009-09-09 15:08:12 +00002590// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002591// void objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002592void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002593 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002594 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002595 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002596 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002597 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002598 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002599 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2600 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2601 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002602 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002603 assert(!argT.isNull() && "Can't find 'SEL' type");
2604 ArgTys.push_back(argT);
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002605 QualType msgSendType = getSimpleFunctionType(Context->VoidTy,
John McCalle23cf432010-12-14 08:05:40 +00002606 &ArgTys[0], ArgTys.size(),
2607 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002608 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002609 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002610 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002611 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002612 SC_Extern,
2613 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002614}
2615
Steve Naroff1284db82008-05-08 22:02:18 +00002616// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002617void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002618 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002619 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002620 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002621 assert(!argT.isNull() && "Can't find 'id' type");
2622 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002623 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002624 assert(!argT.isNull() && "Can't find 'SEL' type");
2625 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002626 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2627 &ArgTys[0], ArgTys.size(),
2628 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002629 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002630 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002631 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002632 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002633 SC_Extern,
2634 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002635}
2636
Steve Naroff09b266e2007-10-30 23:14:51 +00002637// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002638void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002639 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002640 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002641 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002642 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2643 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002644 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002645 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002646 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002647 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002648 SC_Extern,
2649 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002650}
2651
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002652// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2653void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2654 IdentifierInfo *getSuperClassIdent =
2655 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002656 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002657 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002658 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2659 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002660 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002661 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002662 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002663 getSuperClassIdent,
2664 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002665 SC_Extern,
2666 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002667 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002668}
2669
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002670// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002671void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002672 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002673 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002674 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002675 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2676 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002677 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002678 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002679 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002680 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002681 SC_Extern,
2682 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002683}
2684
Steve Naroffb29b4272008-04-14 22:03:09 +00002685Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002686 QualType strType = getConstantStringStructType();
2687
2688 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002689
2690 std::string tmpName = InFileName;
2691 unsigned i;
2692 for (i=0; i < tmpName.length(); i++) {
2693 char c = tmpName.at(i);
2694 // replace any non alphanumeric characters with '_'.
2695 if (!isalpha(c) && (c < '0' || c > '9'))
2696 tmpName[i] = '_';
2697 }
2698 S += tmpName;
2699 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002700 S += utostr(NumObjCStringLiterals++);
2701
Steve Naroffba92b2e2008-03-27 22:29:16 +00002702 Preamble += "static __NSConstantStringImpl " + S;
2703 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2704 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002705 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002706 std::string prettyBufS;
2707 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002708 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2709 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002710 Preamble += prettyBuf.str();
2711 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002712 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002713
2714 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002715 SourceLocation(), &Context->Idents.get(S),
2716 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002717 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2718 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002719 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002720 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002721 VK_RValue, OK_Ordinary,
2722 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002723 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002724 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002725 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002726 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002727 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002728 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002729}
2730
Steve Naroff874e2322007-11-15 10:28:18 +00002731// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002732QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002733 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002734 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002735 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002736 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002737 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002738
Steve Naroff874e2322007-11-15 10:28:18 +00002739 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002740 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002741 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002742 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002743
Steve Naroff874e2322007-11-15 10:28:18 +00002744 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002745 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002746 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002747 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002748 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002749 FieldTypes[i], 0,
2750 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002751 /*Mutable=*/false,
2752 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002753 }
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Douglas Gregor838db382010-02-11 01:19:42 +00002755 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002756 }
2757 return Context->getTagDeclType(SuperStructDecl);
2758}
2759
Steve Naroffb29b4272008-04-14 22:03:09 +00002760QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002761 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002762 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002763 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002764 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002765 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002767 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002768 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002769 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002770 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002771 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002772 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002773 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002774 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002775
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002776 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002777 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002778 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2779 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002780 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002781 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002782 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002783 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002784 /*Mutable=*/true,
2785 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002786 }
2787
Douglas Gregor838db382010-02-11 01:19:42 +00002788 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002789 }
2790 return Context->getTagDeclType(ConstantStringDecl);
2791}
2792
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002793Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2794 SourceLocation StartLoc,
2795 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002796 if (!SelGetUidFunctionDecl)
2797 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002798 if (!MsgSendFunctionDecl)
2799 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002800 if (!MsgSendSuperFunctionDecl)
2801 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002802 if (!MsgSendStretFunctionDecl)
2803 SynthMsgSendStretFunctionDecl();
2804 if (!MsgSendSuperStretFunctionDecl)
2805 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002806 if (!MsgSendFpretFunctionDecl)
2807 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002808 if (!GetClassFunctionDecl)
2809 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002810 if (!GetSuperClassFunctionDecl)
2811 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002812 if (!GetMetaClassFunctionDecl)
2813 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002814
Steve Naroff874e2322007-11-15 10:28:18 +00002815 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002816 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2817 // May need to use objc_msgSend_stret() as well.
2818 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002819 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2820 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002821 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002822 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002823 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002824 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002825 }
Mike Stump1eb44332009-09-09 15:08:12 +00002826
Steve Naroff934f2762007-10-24 22:48:43 +00002827 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002828 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002829 switch (Exp->getReceiverKind()) {
2830 case ObjCMessageExpr::SuperClass: {
2831 MsgSendFlavor = MsgSendSuperFunctionDecl;
2832 if (MsgSendStretFlavor)
2833 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2834 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002835
Douglas Gregor04badcf2010-04-21 00:45:42 +00002836 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002837
Chris Lattner5f9e2722011-07-23 10:55:15 +00002838 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002839
Douglas Gregor04badcf2010-04-21 00:45:42 +00002840 // set the receiver to self, the first argument to all methods.
2841 InitExprs.push_back(
2842 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002843 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002844 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002845 Context->getObjCIdType(),
2846 VK_RValue,
2847 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002848 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002849
Douglas Gregor04badcf2010-04-21 00:45:42 +00002850 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002851 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002852 QualType argType = Context->getPointerType(Context->CharTy);
2853 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002854 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002855 StringLiteral::Ascii, false,
2856 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002857 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2858 &ClsExprs[0],
2859 ClsExprs.size(),
2860 StartLoc,
2861 EndLoc);
2862 // (Class)objc_getClass("CurrentClass")
2863 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2864 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002865 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002866 ClsExprs.clear();
2867 ClsExprs.push_back(ArgExpr);
2868 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2869 &ClsExprs[0], ClsExprs.size(),
2870 StartLoc, EndLoc);
2871
2872 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2873 // To turn off a warning, type-cast to 'id'
2874 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2875 NoTypeInfoCStyleCastExpr(Context,
2876 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002877 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002878 // struct objc_super
2879 QualType superType = getSuperStructType();
2880 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002881
Francois Pichet62ec1f22011-09-17 17:15:52 +00002882 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002883 SynthSuperContructorFunctionDecl();
2884 // Simulate a contructor call...
2885 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002886 superType, VK_LValue,
2887 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002888 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2889 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002890 superType, VK_LValue,
2891 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002892 // The code for super is a little tricky to prevent collision with
2893 // the structure definition in the header. The rewriter has it's own
2894 // internal definition (__rw_objc_super) that is uses. This is why
2895 // we need the cast below. For example:
2896 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2897 //
John McCall2de56d12010-08-25 11:45:40 +00002898 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002899 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002900 VK_RValue, OK_Ordinary,
2901 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002902 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2903 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002904 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002905 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002906 // (struct objc_super) { <exprs from above> }
2907 InitListExpr *ILE =
2908 new (Context) InitListExpr(*Context, SourceLocation(),
2909 &InitExprs[0], InitExprs.size(),
2910 SourceLocation());
2911 TypeSourceInfo *superTInfo
2912 = Context->getTrivialTypeSourceInfo(superType);
2913 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002914 superType, VK_LValue,
2915 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002916 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002917 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002918 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002919 VK_RValue, OK_Ordinary,
2920 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002921 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002922 MsgExprs.push_back(SuperRep);
2923 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002924 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002925
2926 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002927 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002928 QualType argType = Context->getPointerType(Context->CharTy);
2929 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002930 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002931 IdentifierInfo *clsName = Class->getIdentifier();
2932 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002933 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002934 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002935 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002936 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2937 &ClsExprs[0],
2938 ClsExprs.size(),
2939 StartLoc, EndLoc);
2940 MsgExprs.push_back(Cls);
2941 break;
2942 }
2943
2944 case ObjCMessageExpr::SuperInstance:{
2945 MsgSendFlavor = MsgSendSuperFunctionDecl;
2946 if (MsgSendStretFlavor)
2947 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2948 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2949 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002950 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002951
2952 InitExprs.push_back(
2953 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002954 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002955 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002956 Context->getObjCIdType(),
2957 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002958 ); // set the 'receiver'.
2959
2960 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002961 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002962 QualType argType = Context->getPointerType(Context->CharTy);
2963 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002964 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002965 StringLiteral::Ascii, false, argType,
2966 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002967 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2968 &ClsExprs[0],
2969 ClsExprs.size(),
2970 StartLoc, EndLoc);
2971 // (Class)objc_getClass("CurrentClass")
2972 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2973 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002974 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002975 ClsExprs.clear();
2976 ClsExprs.push_back(ArgExpr);
2977 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2978 &ClsExprs[0], ClsExprs.size(),
2979 StartLoc, EndLoc);
2980
2981 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2982 // To turn off a warning, type-cast to 'id'
2983 InitExprs.push_back(
2984 // set 'super class', using class_getSuperclass().
2985 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002986 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002987 // struct objc_super
2988 QualType superType = getSuperStructType();
2989 Expr *SuperRep;
2990
Francois Pichet62ec1f22011-09-17 17:15:52 +00002991 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002992 SynthSuperContructorFunctionDecl();
2993 // Simulate a contructor call...
2994 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002995 superType, VK_LValue,
2996 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002997 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2998 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002999 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00003000 // The code for super is a little tricky to prevent collision with
3001 // the structure definition in the header. The rewriter has it's own
3002 // internal definition (__rw_objc_super) that is uses. This is why
3003 // we need the cast below. For example:
3004 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3005 //
John McCall2de56d12010-08-25 11:45:40 +00003006 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003007 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003008 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00003009 SourceLocation());
3010 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3011 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00003012 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003013 } else {
3014 // (struct objc_super) { <exprs from above> }
3015 InitListExpr *ILE =
3016 new (Context) InitListExpr(*Context, SourceLocation(),
3017 &InitExprs[0], InitExprs.size(),
3018 SourceLocation());
3019 TypeSourceInfo *superTInfo
3020 = Context->getTrivialTypeSourceInfo(superType);
3021 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00003022 superType, VK_RValue, ILE,
3023 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003024 }
3025 MsgExprs.push_back(SuperRep);
3026 break;
3027 }
3028
3029 case ObjCMessageExpr::Instance: {
3030 // Remove all type-casts because it may contain objc-style types; e.g.
3031 // Foo<Proto> *.
3032 Expr *recExpr = Exp->getInstanceReceiver();
3033 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3034 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003035 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3036 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3037 ? CK_BlockPointerToObjCPointerCast
3038 : CK_CPointerToObjCPointerCast;
3039
Douglas Gregor04badcf2010-04-21 00:45:42 +00003040 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00003041 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00003042 MsgExprs.push_back(recExpr);
3043 break;
3044 }
3045 }
3046
Steve Naroffbeaf2992007-11-03 11:27:19 +00003047 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003048 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00003049 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00003050 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00003051 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00003052 StringLiteral::Ascii, false,
3053 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00003054 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003055 &SelExprs[0], SelExprs.size(),
3056 StartLoc,
3057 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00003058 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00003059
Steve Naroff934f2762007-10-24 22:48:43 +00003060 // Now push any user supplied arguments.
3061 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00003062 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00003063 // Make all implicit casts explicit...ICE comes in handy:-)
3064 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3065 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00003066 QualType type = ICE->getType();
3067 if (needToScanForQualifiers(type))
3068 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003069 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003070 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00003071 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00003072 CastKind CK;
3073 if (SubExpr->getType()->isIntegralType(*Context) &&
3074 type->isBooleanType()) {
3075 CK = CK_IntegralToBoolean;
3076 } else if (type->isObjCObjectPointerType()) {
3077 if (SubExpr->getType()->isBlockPointerType()) {
3078 CK = CK_BlockPointerToObjCPointerCast;
3079 } else if (SubExpr->getType()->isPointerType()) {
3080 CK = CK_CPointerToObjCPointerCast;
3081 } else {
3082 CK = CK_BitCast;
3083 }
3084 } else {
3085 CK = CK_BitCast;
3086 }
3087
3088 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003089 }
3090 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003091 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003092 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00003093 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003094 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00003095 CastKind CK;
3096 if (userExpr->getType()->isIntegralType(*Context)) {
3097 CK = CK_IntegralToPointer;
3098 } else if (userExpr->getType()->isBlockPointerType()) {
3099 CK = CK_BlockPointerToObjCPointerCast;
3100 } else if (userExpr->getType()->isPointerType()) {
3101 CK = CK_CPointerToObjCPointerCast;
3102 } else {
3103 CK = CK_BitCast;
3104 }
John McCall9d125032010-01-15 18:39:57 +00003105 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00003106 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00003107 }
Mike Stump1eb44332009-09-09 15:08:12 +00003108 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00003109 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003110 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3111 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003112 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003113 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00003114 }
Steve Naroffab972d32007-11-04 22:37:50 +00003115 // Generate the funky cast.
3116 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003117 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00003118 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00003119
Steve Naroffab972d32007-11-04 22:37:50 +00003120 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00003121 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3122 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3123 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003124 ArgTypes.push_back(Context->getObjCIdType());
3125 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00003126 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00003127 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00003128 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3129 E = OMD->param_end(); PI != E; ++PI) {
3130 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00003131 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00003132 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00003133 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003134 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00003135 ArgTypes.push_back(t);
3136 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00003137 returnType = Exp->getType();
3138 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003139 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00003140 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003141 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00003142 }
3143 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00003144 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00003145
Steve Naroffab972d32007-11-04 22:37:50 +00003146 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003147 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003148 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00003149
Mike Stump1eb44332009-09-09 15:08:12 +00003150 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00003151 // If we don't do this cast, we get the following bizarre warning/note:
3152 // xx.m:13: warning: function called through a non-compatible type
3153 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00003154 cast = NoTypeInfoCStyleCastExpr(Context,
3155 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003156 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00003157
Steve Naroffab972d32007-11-04 22:37:50 +00003158 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003159 QualType castType =
3160 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3161 // If we don't have a method decl, force a variadic cast.
3162 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00003163 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003164 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003165 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00003166
3167 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003168 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003169
John McCall183700f2009-09-21 23:43:11 +00003170 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003171 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003172 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003173 FT->getResultType(), VK_RValue,
3174 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003175 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003176 if (MsgSendStretFlavor) {
3177 // We have the method which returns a struct/union. Must also generate
3178 // call to objc_msgSend_stret and hang both varieties on a conditional
3179 // expression which dictate which one to envoke depending on size of
3180 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00003181
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003182 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00003183 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00003184 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003185 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00003186 cast = NoTypeInfoCStyleCastExpr(Context,
3187 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00003188 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003189 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003190 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3191 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003192 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00003193 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003194 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003195
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003196 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003197 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00003198
John McCall183700f2009-09-21 23:43:11 +00003199 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003200 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003201 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003202 FT->getResultType(), VK_RValue,
3203 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003204
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003205 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003206 UnaryExprOrTypeTraitExpr *sizeofExpr =
3207 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3208 Context->getTrivialTypeSourceInfo(returnType),
3209 Context->getSizeType(), SourceLocation(),
3210 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003211 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3212 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3213 // For X86 it is more complicated and some kind of target specific routine
3214 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003215 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003216 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003217 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3218 llvm::APInt(IntSize, 8),
3219 Context->IntTy,
3220 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003221 BinaryOperator *lessThanExpr =
3222 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3223 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003224 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003225 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003226 new (Context) ConditionalOperator(lessThanExpr,
3227 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003228 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003229 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003230 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3231 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003232 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003233 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003234 return ReplacingStmt;
3235}
3236
Steve Naroffb29b4272008-04-14 22:03:09 +00003237Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003238 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3239 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003240
Steve Naroff934f2762007-10-24 22:48:43 +00003241 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003242 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003243
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003244 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003245 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003246}
3247
Steve Naroff621edce2009-04-29 16:37:50 +00003248// typedef struct objc_object Protocol;
3249QualType RewriteObjC::getProtocolType() {
3250 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003251 TypeSourceInfo *TInfo
3252 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003253 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003254 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003255 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003256 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003257 }
3258 return Context->getTypeDeclType(ProtocolTypeDecl);
3259}
3260
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003261/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003262/// a synthesized/forward data reference (to the protocol's metadata).
3263/// The forward references (and metadata) are generated in
3264/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003265Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003266 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3267 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003268 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003269 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003270 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003271 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3272 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003273 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003274 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003275 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003276 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003277 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003278 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003279 ReplaceStmt(Exp, castExpr);
3280 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003281 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003282 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003283
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003284}
3285
Mike Stump1eb44332009-09-09 15:08:12 +00003286bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003287 const char *endBuf) {
3288 while (startBuf < endBuf) {
3289 if (*startBuf == '#') {
3290 // Skip whitespace.
3291 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3292 ;
3293 if (!strncmp(startBuf, "if", strlen("if")) ||
3294 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3295 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3296 !strncmp(startBuf, "define", strlen("define")) ||
3297 !strncmp(startBuf, "undef", strlen("undef")) ||
3298 !strncmp(startBuf, "else", strlen("else")) ||
3299 !strncmp(startBuf, "elif", strlen("elif")) ||
3300 !strncmp(startBuf, "endif", strlen("endif")) ||
3301 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3302 !strncmp(startBuf, "include", strlen("include")) ||
3303 !strncmp(startBuf, "import", strlen("import")) ||
3304 !strncmp(startBuf, "include_next", strlen("include_next")))
3305 return true;
3306 }
3307 startBuf++;
3308 }
3309 return false;
3310}
3311
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003312/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003313/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00003314void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003315 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003316 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003317 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003318 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003319 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003320 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003321 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003322 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003323 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003324 SourceLocation LocStart = CDecl->getLocStart();
3325 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003326
Steve Narofffea763e82007-11-14 19:25:57 +00003327 const char *startBuf = SM->getCharacterData(LocStart);
3328 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003330 // If no ivars and no root or if its root, directly or indirectly,
3331 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003332 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3333 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003334 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003335 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003336 return;
3337 }
Mike Stump1eb44332009-09-09 15:08:12 +00003338
3339 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003340 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003341 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003342 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003343 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003344 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003345
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003346 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003347 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003348 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003349 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003350 // If the buffer contains preprocessor directives, we do more fine-grained
3351 // rewrites. This is intended to fix code that looks like (which occurs in
3352 // NSURL.h, for example):
3353 //
3354 // #ifdef XYZ
3355 // @interface Foo : NSObject
3356 // #else
3357 // @interface FooBar : NSObject
3358 // #endif
3359 // {
3360 // int i;
3361 // }
3362 // @end
3363 //
3364 // This clause is segregated to avoid breaking the common case.
3365 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003366 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003367 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003368 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003369 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003370
Chris Lattnercafeb352009-02-20 18:18:36 +00003371 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003372 // advance to the end of the referenced protocols.
3373 while (endHeader < cursor && *endHeader != '>') endHeader++;
3374 endHeader++;
3375 }
3376 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003377 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003378 } else {
3379 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003380 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003381 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003382 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003383 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003384 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003385 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003386 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003387 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003388
Steve Narofffea763e82007-11-14 19:25:57 +00003389 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003390 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003391 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003392 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003393 }
3394 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003395
Steve Narofffea763e82007-11-14 19:25:57 +00003396 // Now comment out any visibility specifiers.
3397 while (cursor < endBuf) {
3398 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003399 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003400 // Skip whitespace.
3401 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3402 /*scan*/;
3403
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003404 // FIXME: presence of @public, etc. inside comment results in
3405 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003406 if (!strncmp(cursor, "public", strlen("public")) ||
3407 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003408 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003409 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003410 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003411 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003412 // FIXME: If there are cases where '<' is used in ivar declaration part
3413 // of user code, then scan the ivar list and use needToScanForQualifiers
3414 // for type checking.
3415 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003416 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003417 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003418 cursor = strchr(cursor, '>');
3419 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003420 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003421 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003422 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003423 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003424 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003425 }
Steve Narofffea763e82007-11-14 19:25:57 +00003426 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003427 }
Steve Narofffea763e82007-11-14 19:25:57 +00003428 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003429 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003430 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003431 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003432 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003433 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003434 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003435 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003436 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003437 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003438 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003439 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003440 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003441 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003442}
3443
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003444// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003445/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003446template<typename MethodIterator>
3447void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3448 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003449 bool IsInstanceMethod,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003450 StringRef prefix,
3451 StringRef ClassName,
Chris Lattner158ecb92007-10-25 17:07:24 +00003452 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003453 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003454
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003455 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003456 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003457 SEL _cmd;
3458 char *method_types;
3459 void *_imp;
3460 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003461 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003462 Result += "\nstruct _objc_method {\n";
3463 Result += "\tSEL _cmd;\n";
3464 Result += "\tchar *method_types;\n";
3465 Result += "\tvoid *_imp;\n";
3466 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003467
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003468 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003469 }
Mike Stump1eb44332009-09-09 15:08:12 +00003470
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003471 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003472
Steve Naroff946a6932008-03-11 00:12:29 +00003473 /* struct {
3474 struct _objc_method_list *next_method;
3475 int method_count;
3476 struct _objc_method method_list[];
3477 }
3478 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003479 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003480 Result += "\nstatic struct {\n";
3481 Result += "\tstruct _objc_method_list *next_method;\n";
3482 Result += "\tint method_count;\n";
3483 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003484 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003485 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003486 Result += prefix;
3487 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3488 Result += "_METHODS_";
3489 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003490 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003491 Result += IsInstanceMethod ? "inst" : "cls";
3492 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003493 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003494
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003495 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003496 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003497 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003498 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003499 Result += "\", \"";
3500 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003501 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003502 Result += MethodInternalNames[*MethodBegin];
3503 Result += "}\n";
3504 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3505 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003506 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003507 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003508 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003509 Result += "\", \"";
3510 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003511 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003512 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003513 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003514 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003515 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003516}
3517
Steve Naroff621edce2009-04-29 16:37:50 +00003518/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003519void RewriteObjC::
Chris Lattner5f9e2722011-07-23 10:55:15 +00003520RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, StringRef prefix,
3521 StringRef ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003522 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003523
3524 // Output struct protocol_methods holder of method selector and type.
3525 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3526 /* struct protocol_methods {
3527 SEL _cmd;
3528 char *method_types;
3529 }
3530 */
3531 Result += "\nstruct _protocol_methods {\n";
3532 Result += "\tstruct objc_selector *_cmd;\n";
3533 Result += "\tchar *method_types;\n";
3534 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003535
Steve Naroff621edce2009-04-29 16:37:50 +00003536 objc_protocol_methods = true;
3537 }
3538 // Do not synthesize the protocol more than once.
3539 if (ObjCSynthesizedProtocols.count(PDecl))
3540 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003541
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003542 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3543 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3544 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003545 /* struct _objc_protocol_method_list {
3546 int protocol_method_count;
3547 struct protocol_methods protocols[];
3548 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003549 */
Steve Naroff621edce2009-04-29 16:37:50 +00003550 Result += "\nstatic struct {\n";
3551 Result += "\tint protocol_method_count;\n";
3552 Result += "\tstruct _protocol_methods protocol_methods[";
3553 Result += utostr(NumMethods);
3554 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3555 Result += PDecl->getNameAsString();
3556 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3557 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003558
Steve Naroff621edce2009-04-29 16:37:50 +00003559 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003560 for (ObjCProtocolDecl::instmeth_iterator
3561 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003562 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003563 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003564 Result += "\t ,{{(struct objc_selector *)\"";
3565 else
3566 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003567 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003568 std::string MethodTypeString;
3569 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3570 Result += "\", \"";
3571 Result += MethodTypeString;
3572 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003573 }
Steve Naroff621edce2009-04-29 16:37:50 +00003574 Result += "\t }\n};\n";
3575 }
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Steve Naroff621edce2009-04-29 16:37:50 +00003577 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003578 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3579 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003580 if (NumMethods > 0) {
3581 /* struct _objc_protocol_method_list {
3582 int protocol_method_count;
3583 struct protocol_methods protocols[];
3584 }
3585 */
3586 Result += "\nstatic struct {\n";
3587 Result += "\tint protocol_method_count;\n";
3588 Result += "\tstruct _protocol_methods protocol_methods[";
3589 Result += utostr(NumMethods);
3590 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3591 Result += PDecl->getNameAsString();
3592 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3593 "{\n\t";
3594 Result += utostr(NumMethods);
3595 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003596
Steve Naroff621edce2009-04-29 16:37:50 +00003597 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003598 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003599 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003600 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003601 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003602 Result += "\t ,{{(struct objc_selector *)\"";
3603 else
3604 Result += "\t ,{(struct objc_selector *)\"";
Daniel Dunbar4087f272010-08-17 22:39:59 +00003605 Result += (*I)->getSelector().getAsString();
Steve Naroff621edce2009-04-29 16:37:50 +00003606 std::string MethodTypeString;
3607 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3608 Result += "\", \"";
3609 Result += MethodTypeString;
3610 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003611 }
Steve Naroff621edce2009-04-29 16:37:50 +00003612 Result += "\t }\n};\n";
3613 }
3614
3615 // Output:
3616 /* struct _objc_protocol {
3617 // Objective-C 1.0 extensions
3618 struct _objc_protocol_extension *isa;
3619 char *protocol_name;
3620 struct _objc_protocol **protocol_list;
3621 struct _objc_protocol_method_list *instance_methods;
3622 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003623 };
Steve Naroff621edce2009-04-29 16:37:50 +00003624 */
3625 static bool objc_protocol = false;
3626 if (!objc_protocol) {
3627 Result += "\nstruct _objc_protocol {\n";
3628 Result += "\tstruct _objc_protocol_extension *isa;\n";
3629 Result += "\tchar *protocol_name;\n";
3630 Result += "\tstruct _objc_protocol **protocol_list;\n";
3631 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3632 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003633 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003634
Steve Naroff621edce2009-04-29 16:37:50 +00003635 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003636 }
Mike Stump1eb44332009-09-09 15:08:12 +00003637
Steve Naroff621edce2009-04-29 16:37:50 +00003638 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3639 Result += PDecl->getNameAsString();
3640 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3641 "{\n\t0, \"";
3642 Result += PDecl->getNameAsString();
3643 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003644 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003645 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3646 Result += PDecl->getNameAsString();
3647 Result += ", ";
3648 }
3649 else
3650 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003651 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003652 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3653 Result += PDecl->getNameAsString();
3654 Result += "\n";
3655 }
3656 else
3657 Result += "0\n";
3658 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003659
Steve Naroff621edce2009-04-29 16:37:50 +00003660 // Mark this protocol as having been generated.
3661 if (!ObjCSynthesizedProtocols.insert(PDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003662 llvm_unreachable("protocol already synthesized");
Steve Naroff621edce2009-04-29 16:37:50 +00003663
3664}
3665
3666void RewriteObjC::
3667RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003668 StringRef prefix, StringRef ClassName,
Steve Naroff621edce2009-04-29 16:37:50 +00003669 std::string &Result) {
3670 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003671
Steve Naroff621edce2009-04-29 16:37:50 +00003672 for (unsigned i = 0; i != Protocols.size(); i++)
3673 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3674
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003675 // Output the top lovel protocol meta-data for the class.
3676 /* struct _objc_protocol_list {
3677 struct _objc_protocol_list *next;
3678 int protocol_count;
3679 struct _objc_protocol *class_protocols[];
3680 }
3681 */
3682 Result += "\nstatic struct {\n";
3683 Result += "\tstruct _objc_protocol_list *next;\n";
3684 Result += "\tint protocol_count;\n";
3685 Result += "\tstruct _objc_protocol *class_protocols[";
3686 Result += utostr(Protocols.size());
3687 Result += "];\n} _OBJC_";
3688 Result += prefix;
3689 Result += "_PROTOCOLS_";
3690 Result += ClassName;
3691 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3692 "{\n\t0, ";
3693 Result += utostr(Protocols.size());
3694 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003695
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003696 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003697 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003698 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003699
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003700 for (unsigned i = 1; i != Protocols.size(); i++) {
3701 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003702 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003703 Result += "\n";
3704 }
3705 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003706}
3707
Steve Naroff621edce2009-04-29 16:37:50 +00003708
Mike Stump1eb44332009-09-09 15:08:12 +00003709/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003710/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003711void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003712 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003713 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003714 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003715 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003716 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003717 CDecl = CDecl->getNextClassCategory())
3718 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3719 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003720
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003721 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003722 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003723 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003724
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003725 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003726 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003727 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003728
3729 // If any of our property implementations have associated getters or
3730 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003731 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3732 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003733 Prop != PropEnd; ++Prop) {
3734 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3735 continue;
3736 if (!(*Prop)->getPropertyIvarDecl())
3737 continue;
3738 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3739 if (!PD)
3740 continue;
3741 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3742 InstanceMethods.push_back(Getter);
3743 if (PD->isReadOnly())
3744 continue;
3745 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3746 InstanceMethods.push_back(Setter);
3747 }
3748 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003749 true, "CATEGORY_", FullCategoryName.c_str(),
3750 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003751
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003752 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003753 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003754 false, "CATEGORY_", FullCategoryName.c_str(),
3755 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003756
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003757 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003758 // Null CDecl is case of a category implementation with no category interface
3759 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003760 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
Daniel Dunbar4087f272010-08-17 22:39:59 +00003761 FullCategoryName, Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003762 /* struct _objc_category {
3763 char *category_name;
3764 char *class_name;
3765 struct _objc_method_list *instance_methods;
3766 struct _objc_method_list *class_methods;
3767 struct _objc_protocol_list *protocols;
3768 // Objective-C 1.0 extensions
3769 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003770 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003771 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003772 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003773 */
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003775 static bool objc_category = false;
3776 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003777 Result += "\nstruct _objc_category {\n";
3778 Result += "\tchar *category_name;\n";
3779 Result += "\tchar *class_name;\n";
3780 Result += "\tstruct _objc_method_list *instance_methods;\n";
3781 Result += "\tstruct _objc_method_list *class_methods;\n";
3782 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003783 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003784 Result += "\tstruct _objc_property_list *instance_properties;\n";
3785 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003786 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003787 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003788 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3789 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003790 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003791 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003792 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003793 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003794 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003795
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003796 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003797 Result += "\t, (struct _objc_method_list *)"
3798 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3799 Result += FullCategoryName;
3800 Result += "\n";
3801 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003802 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003803 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003804 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003805 Result += "\t, (struct _objc_method_list *)"
3806 "&_OBJC_CATEGORY_CLASS_METHODS_";
3807 Result += FullCategoryName;
3808 Result += "\n";
3809 }
3810 else
3811 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003812
Chris Lattnercafeb352009-02-20 18:18:36 +00003813 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003814 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003815 Result += FullCategoryName;
3816 Result += "\n";
3817 }
3818 else
3819 Result += "\t, 0\n";
3820 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003821}
3822
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003823/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3824/// ivar offset.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003825void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003826 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003827 if (ivar->isBitField()) {
3828 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3829 // place all bitfields at offset 0.
3830 Result += "0";
3831 } else {
3832 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003833 Result += ivar->getContainingInterface()->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003834 if (LangOpts.MicrosoftExt)
Steve Naroff8f3b2652008-07-16 18:22:22 +00003835 Result += "_IMPL";
3836 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003837 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003838 Result += ")";
3839 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003840}
3841
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003842//===----------------------------------------------------------------------===//
3843// Meta Data Emission
3844//===----------------------------------------------------------------------===//
3845
Steve Naroffb29b4272008-04-14 22:03:09 +00003846void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003847 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003848 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003849
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003850 // Explicitly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003851 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003852 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003853 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003854 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003855 }
Mike Stump1eb44332009-09-09 15:08:12 +00003856
Chris Lattnerbe6df082007-12-12 07:56:42 +00003857 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003858 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003859 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003860 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003861 if (NumIvars > 0) {
3862 static bool objc_ivar = false;
3863 if (!objc_ivar) {
3864 /* struct _objc_ivar {
3865 char *ivar_name;
3866 char *ivar_type;
3867 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003868 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003869 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003870 Result += "\nstruct _objc_ivar {\n";
3871 Result += "\tchar *ivar_name;\n";
3872 Result += "\tchar *ivar_type;\n";
3873 Result += "\tint ivar_offset;\n";
3874 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003875
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003876 objc_ivar = true;
3877 }
3878
Steve Naroff946a6932008-03-11 00:12:29 +00003879 /* struct {
3880 int ivar_count;
3881 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003882 };
Steve Naroff946a6932008-03-11 00:12:29 +00003883 */
Mike Stump1eb44332009-09-09 15:08:12 +00003884 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003885 Result += "\tint ivar_count;\n";
3886 Result += "\tstruct _objc_ivar ivar_list[";
3887 Result += utostr(NumIvars);
3888 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003889 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003890 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003891 "{\n\t";
3892 Result += utostr(NumIvars);
3893 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003894
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003895 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003896 SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003897 if (!IDecl->ivar_empty()) {
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003898 for (ObjCInterfaceDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003899 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003900 IV != IVEnd; ++IV)
3901 IVars.push_back(*IV);
Fariborz Jahanian11062e12010-02-19 00:31:17 +00003902 IVI = IDecl->ivar_begin();
3903 IVE = IDecl->ivar_end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003904 } else {
3905 IVI = CDecl->ivar_begin();
3906 IVE = CDecl->ivar_end();
3907 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003908 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003909 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003910 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003911 std::string TmpString, StrEncoding;
3912 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3913 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003914 Result += StrEncoding;
3915 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003916 SynthesizeIvarOffsetComputation(*IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003917 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003918 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003919 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003920 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003921 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003922 std::string TmpString, StrEncoding;
3923 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3924 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003925 Result += StrEncoding;
3926 Result += "\", ";
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00003927 SynthesizeIvarOffsetComputation((*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003928 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003929 }
Mike Stump1eb44332009-09-09 15:08:12 +00003930
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003931 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003932 }
Mike Stump1eb44332009-09-09 15:08:12 +00003933
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003934 // Build _objc_method_list for class's instance methods if needed
Chris Lattner5f9e2722011-07-23 10:55:15 +00003935 SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003936 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003937
3938 // If any of our property implementations have associated getters or
3939 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003940 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3941 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003942 Prop != PropEnd; ++Prop) {
3943 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3944 continue;
3945 if (!(*Prop)->getPropertyIvarDecl())
3946 continue;
3947 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3948 if (!PD)
3949 continue;
3950 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003951 if (!Getter->isDefined())
3952 InstanceMethods.push_back(Getter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003953 if (PD->isReadOnly())
3954 continue;
3955 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianec3683b2010-10-19 23:47:54 +00003956 if (!Setter->isDefined())
3957 InstanceMethods.push_back(Setter);
Douglas Gregor653f1b12009-04-23 01:02:12 +00003958 }
3959 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003960 true, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003961
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003962 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003963 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003964 false, "", IDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003965
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003966 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003967 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00003968 "CLASS", CDecl->getName(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003969
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003970 // Declaration of class/meta-class metadata
3971 /* struct _objc_class {
3972 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003973 const char *super_class_name;
3974 char *name;
3975 long version;
3976 long info;
3977 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003978 struct _objc_ivar_list *ivars;
3979 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003980 struct objc_cache *cache;
3981 struct objc_protocol_list *protocols;
3982 const char *ivar_layout;
3983 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003984 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003985 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003986 static bool objc_class = false;
3987 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003988 Result += "\nstruct _objc_class {\n";
3989 Result += "\tstruct _objc_class *isa;\n";
3990 Result += "\tconst char *super_class_name;\n";
3991 Result += "\tchar *name;\n";
3992 Result += "\tlong version;\n";
3993 Result += "\tlong info;\n";
3994 Result += "\tlong instance_size;\n";
3995 Result += "\tstruct _objc_ivar_list *ivars;\n";
3996 Result += "\tstruct _objc_method_list *methods;\n";
3997 Result += "\tstruct objc_cache *cache;\n";
3998 Result += "\tstruct _objc_protocol_list *protocols;\n";
3999 Result += "\tconst char *ivar_layout;\n";
4000 Result += "\tstruct _objc_class_ext *ext;\n";
4001 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004002 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004003 }
Mike Stump1eb44332009-09-09 15:08:12 +00004004
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004005 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004006 ObjCInterfaceDecl *RootClass = 0;
4007 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004008 while (SuperClass) {
4009 RootClass = SuperClass;
4010 SuperClass = SuperClass->getSuperClass();
4011 }
4012 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00004013
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004014 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004015 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004016 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004017 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004018 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004019 Result += "\"";
4020
4021 if (SuperClass) {
4022 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004023 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004024 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004025 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004026 Result += "\"";
4027 }
4028 else {
4029 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004030 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004031 Result += "\"";
4032 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004033 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004034 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004035 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004036 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00004037 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004038 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004039 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004040 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004041 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004042 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00004043 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004044 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004045 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004046 Result += ",0,0\n";
4047 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00004048 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004049 Result += "\t,0,0,0,0\n";
4050 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004051
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004052 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004053 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004054 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00004055 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004056 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004057 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004058 if (SuperClass) {
4059 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004060 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004061 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004062 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004063 Result += "\"";
4064 }
4065 else {
4066 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004067 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004068 Result += "\"";
4069 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004070 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004071 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004072 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004073 Result += ",0";
4074 else {
4075 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00004076 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004077 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00004078 if (LangOpts.MicrosoftExt)
Steve Naroffba9ac4e2008-03-10 23:33:22 +00004079 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00004080 Result += ")";
4081 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004082 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00004083 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004084 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004085 Result += "\n\t";
4086 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004087 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004088 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00004089 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00004090 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004091 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00004092 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004093 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004094 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004095 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00004096 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00004097 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004098 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004099 Result += ", 0,0\n";
4100 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00004101 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004102 Result += ",0,0,0\n";
4103 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00004104}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004105
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004106/// RewriteImplementations - This routine rewrites all method implementations
4107/// and emits meta-data.
4108
Steve Narofface66252008-11-13 20:07:04 +00004109void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004110 int ClsDefCount = ClassImplementation.size();
4111 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00004112
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00004113 // Rewrite implemented methods
4114 for (int i = 0; i < ClsDefCount; i++)
4115 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00004116
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00004117 for (int i = 0; i < CatDefCount; i++)
4118 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00004119}
Mike Stump1eb44332009-09-09 15:08:12 +00004120
Steve Narofface66252008-11-13 20:07:04 +00004121void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
4122 int ClsDefCount = ClassImplementation.size();
4123 int CatDefCount = CategoryImplementation.size();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00004124
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004125 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00004126 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004127 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00004128
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00004129 // For each implemented category, write out all its meta data.
4130 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00004131 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00004132
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004133 // Write objc_symtab metadata
4134 /*
4135 struct _objc_symtab
4136 {
4137 long sel_ref_cnt;
4138 SEL *refs;
4139 short cls_def_cnt;
4140 short cat_def_cnt;
4141 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00004142 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004143 */
Mike Stump1eb44332009-09-09 15:08:12 +00004144
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004145 Result += "\nstruct _objc_symtab {\n";
4146 Result += "\tlong sel_ref_cnt;\n";
4147 Result += "\tSEL *refs;\n";
4148 Result += "\tshort cls_def_cnt;\n";
4149 Result += "\tshort cat_def_cnt;\n";
4150 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
4151 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004152
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004153 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00004154 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004155 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004156 + ", " + utostr(CatDefCount) + "\n";
4157 for (int i = 0; i < ClsDefCount; i++) {
4158 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004159 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004160 Result += "\n";
4161 }
Mike Stump1eb44332009-09-09 15:08:12 +00004162
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004163 for (int i = 0; i < CatDefCount; i++) {
4164 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004165 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004166 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004167 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004168 Result += "\n";
4169 }
Mike Stump1eb44332009-09-09 15:08:12 +00004170
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004171 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004172
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004173 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00004174
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004175 /*
4176 struct _objc_module {
4177 long version;
4178 long size;
4179 const char *name;
4180 struct _objc_symtab *symtab;
4181 }
4182 */
Mike Stump1eb44332009-09-09 15:08:12 +00004183
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004184 Result += "\nstruct _objc_module {\n";
4185 Result += "\tlong version;\n";
4186 Result += "\tlong size;\n";
4187 Result += "\tconst char *name;\n";
4188 Result += "\tstruct _objc_symtab *symtab;\n";
4189 Result += "};\n\n";
4190 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00004191 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004192 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00004193 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00004194 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004195
Francois Pichet62ec1f22011-09-17 17:15:52 +00004196 if (LangOpts.MicrosoftExt) {
Steve Naroff621edce2009-04-29 16:37:50 +00004197 if (ProtocolExprDecls.size()) {
4198 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
4199 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004200 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00004201 E = ProtocolExprDecls.end(); I != E; ++I) {
4202 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
4203 Result += (*I)->getNameAsString();
4204 Result += " = &_OBJC_PROTOCOL_";
4205 Result += (*I)->getNameAsString();
4206 Result += ";\n";
4207 }
4208 Result += "#pragma data_seg(pop)\n\n";
4209 }
Steve Naroff4f943c22008-03-10 20:43:59 +00004210 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00004211 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00004212 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
4213 Result += "&_OBJC_MODULES;\n";
4214 Result += "#pragma data_seg(pop)\n\n";
4215 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00004216}
Chris Lattner311ff022007-10-16 22:36:42 +00004217
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004218void RewriteObjC::RewriteByRefString(std::string &ResultStr,
4219 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004220 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004221 assert(BlockByRefDeclNo.count(VD) &&
4222 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004223 if (def)
4224 ResultStr += "struct ";
4225 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004226 "_" + utostr(BlockByRefDeclNo[VD]) ;
4227}
4228
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004229static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4230 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4231 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4232 return false;
4233}
4234
Steve Naroff54055232008-10-27 17:20:55 +00004235std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004236 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004237 std::string Tag) {
4238 const FunctionType *AFT = CE->getFunctionType();
4239 QualType RT = AFT->getResultType();
4240 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00004241 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00004242 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00004243
Steve Naroff54055232008-10-27 17:20:55 +00004244 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00004245
Douglas Gregor72564e72009-02-26 23:50:07 +00004246 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00004247 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00004248 // block (to reference imported block decl refs).
4249 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00004250 } else if (BD->param_empty()) {
4251 S += "(" + StructRef + " *__cself)";
4252 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00004253 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00004254 assert(FT && "SynthesizeBlockFunc: No function proto");
4255 S += '(';
4256 // first add the implicit argument.
4257 S += StructRef + " *__cself, ";
4258 std::string ParamStr;
4259 for (BlockDecl::param_iterator AI = BD->param_begin(),
4260 E = BD->param_end(); AI != E; ++AI) {
4261 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004262 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004263 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004264 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00004265 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004266 else
Douglas Gregor30c42402011-09-27 22:38:19 +00004267 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004268 S += ParamStr;
4269 }
4270 if (FT->isVariadic()) {
4271 if (!BD->param_empty()) S += ", ";
4272 S += "...";
4273 }
4274 S += ')';
4275 }
4276 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004277
Steve Naroff54055232008-10-27 17:20:55 +00004278 // Create local declarations to avoid rewriting all closure decl ref exprs.
4279 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004280 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004281 E = BlockByRefDecls.end(); I != E; ++I) {
4282 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004283 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004284 std::string TypeString;
4285 RewriteByRefString(TypeString, Name, (*I));
4286 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004287 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004288 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004289 }
Steve Naroff54055232008-10-27 17:20:55 +00004290 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004291 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004292 E = BlockByCopyDecls.end(); I != E; ++I) {
4293 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00004294 // Handle nested closure invocation. For example:
4295 //
4296 // void (^myImportedClosure)(void);
4297 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004298 //
Steve Naroff54055232008-10-27 17:20:55 +00004299 // void (^anotherClosure)(void);
4300 // anotherClosure = ^(void) {
4301 // myImportedClosure(); // import and invoke the closure
4302 // };
4303 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004304 if (isTopLevelBlockPointerType((*I)->getType())) {
4305 RewriteBlockPointerTypeVariable(S, (*I));
4306 S += " = (";
4307 RewriteBlockPointerType(S, (*I)->getType());
4308 S += ")";
4309 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4310 }
4311 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00004312 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004313 QualType QT = (*I)->getType();
4314 if (HasLocalVariableExternalStorage(*I))
4315 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004316 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00004317 S += Name + " = __cself->" +
4318 (*I)->getNameAsString() + "; // bound by copy\n";
4319 }
Steve Naroff54055232008-10-27 17:20:55 +00004320 }
4321 std::string RewrittenStr = RewrittenBlockExprs[CE];
4322 const char *cstr = RewrittenStr.c_str();
4323 while (*cstr++ != '{') ;
4324 S += cstr;
4325 S += "\n";
4326 return S;
4327}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00004328
Steve Naroff54055232008-10-27 17:20:55 +00004329std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004330 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00004331 std::string Tag) {
4332 std::string StructRef = "struct " + Tag;
4333 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00004334
Steve Naroff54055232008-10-27 17:20:55 +00004335 S += funcName;
4336 S += "_block_copy_" + utostr(i);
4337 S += "(" + StructRef;
4338 S += "*dst, " + StructRef;
4339 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004340 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004341 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004342 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004343 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004344 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00004345 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004346 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004347 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004348 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004349 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004350 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004351 else
4352 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004353 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00004354 S += "}\n";
4355
Steve Naroff54055232008-10-27 17:20:55 +00004356 S += "\nstatic void __";
4357 S += funcName;
4358 S += "_block_dispose_" + utostr(i);
4359 S += "(" + StructRef;
4360 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00004361 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004362 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004363 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00004364 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004365 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004366 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00004367 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004368 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00004369 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00004370 else
4371 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00004372 }
Mike Stump1eb44332009-09-09 15:08:12 +00004373 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00004374 return S;
4375}
4376
Steve Naroff01aec112009-12-06 21:14:13 +00004377std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4378 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00004379 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00004380 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00004381
Steve Naroff54055232008-10-27 17:20:55 +00004382 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004383 S += " struct " + Desc;
4384 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004385
Steve Naroff01aec112009-12-06 21:14:13 +00004386 Constructor += "(void *fp, "; // Invoke function pointer.
4387 Constructor += "struct " + Desc; // Descriptor pointer.
4388 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00004389
Steve Naroff54055232008-10-27 17:20:55 +00004390 if (BlockDeclRefs.size()) {
4391 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004392 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004393 E = BlockByCopyDecls.end(); I != E; ++I) {
4394 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004395 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004396 std::string ArgName = "_" + FieldName;
4397 // Handle nested closure invocation. For example:
4398 //
4399 // void (^myImportedBlock)(void);
4400 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00004401 //
Steve Naroff54055232008-10-27 17:20:55 +00004402 // void (^anotherBlock)(void);
4403 // anotherBlock = ^(void) {
4404 // myImportedBlock(); // import and invoke the closure
4405 // };
4406 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004407 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00004408 S += "struct __block_impl *";
4409 Constructor += ", void *" + ArgName;
4410 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004411 QualType QT = (*I)->getType();
4412 if (HasLocalVariableExternalStorage(*I))
4413 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00004414 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4415 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00004416 Constructor += ", " + ArgName;
4417 }
4418 S += FieldName + ";\n";
4419 }
4420 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004421 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004422 E = BlockByRefDecls.end(); I != E; ++I) {
4423 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004424 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004425 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004426 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004427 std::string TypeString;
4428 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004429 TypeString += " *";
4430 FieldName = TypeString + FieldName;
4431 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00004432 Constructor += ", " + ArgName;
4433 }
4434 S += FieldName + "; // by ref\n";
4435 }
4436 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004437 Constructor += ", int flags=0)";
4438 // Initialize all "by copy" arguments.
4439 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00004440 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004441 E = BlockByCopyDecls.end(); I != E; ++I) {
4442 std::string Name = (*I)->getNameAsString();
4443 if (firsTime) {
4444 Constructor += " : ";
4445 firsTime = false;
4446 }
4447 else
4448 Constructor += ", ";
4449 if (isTopLevelBlockPointerType((*I)->getType()))
4450 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4451 else
4452 Constructor += Name + "(_" + Name + ")";
4453 }
4454 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004455 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004456 E = BlockByRefDecls.end(); I != E; ++I) {
4457 std::string Name = (*I)->getNameAsString();
4458 if (firsTime) {
4459 Constructor += " : ";
4460 firsTime = false;
4461 }
4462 else
4463 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00004464 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00004465 }
4466
4467 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004468 if (GlobalVarDecl)
4469 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4470 else
4471 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004472 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Steve Naroff01aec112009-12-06 21:14:13 +00004474 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004475 } else {
4476 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004477 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004478 if (GlobalVarDecl)
4479 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4480 else
4481 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004482 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4483 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004484 }
4485 Constructor += " ";
4486 Constructor += "}\n";
4487 S += Constructor;
4488 S += "};\n";
4489 return S;
4490}
4491
Steve Naroff01aec112009-12-06 21:14:13 +00004492std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4493 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004494 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00004495 unsigned hasCopy) {
4496 std::string S = "\nstatic struct " + DescTag;
4497
4498 S += " {\n unsigned long reserved;\n";
4499 S += " unsigned long Block_size;\n";
4500 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004501 S += " void (*copy)(struct ";
4502 S += ImplTag; S += "*, struct ";
4503 S += ImplTag; S += "*);\n";
4504
4505 S += " void (*dispose)(struct ";
4506 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004507 }
4508 S += "} ";
4509
4510 S += DescTag + "_DATA = { 0, sizeof(struct ";
4511 S += ImplTag + ")";
4512 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004513 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4514 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00004515 }
4516 S += "};\n";
4517 return S;
4518}
4519
Steve Naroff54055232008-10-27 17:20:55 +00004520void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004521 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004522 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004523 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004524 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004525 bool RewriteSC = (GlobalVarDecl &&
4526 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00004527 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004528 GlobalVarDecl->getType().getCVRQualifiers());
4529 if (RewriteSC) {
4530 std::string SC(" void __");
4531 SC += GlobalVarDecl->getNameAsString();
4532 SC += "() {}";
4533 InsertText(FunLocStart, SC);
4534 }
4535
Steve Naroff54055232008-10-27 17:20:55 +00004536 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004537 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4538 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004539 // Need to copy-in the inner copied-in variables not actually used in this
4540 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004541 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4542 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
4543 ValueDecl *VD = Exp->getDecl();
4544 BlockDeclRefs.push_back(Exp);
4545 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
4546 BlockByCopyDeclsPtrSet.insert(VD);
4547 BlockByCopyDecls.push_back(VD);
4548 }
4549 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4550 BlockByRefDeclsPtrSet.insert(VD);
4551 BlockByRefDecls.push_back(VD);
4552 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00004553 // imported objects in the inner blocks not used in the outer
4554 // blocks must be copied/disposed in the outer block as well.
4555 if (Exp->isByRef() ||
4556 VD->getType()->isObjCObjectPointerType() ||
4557 VD->getType()->isBlockPointerType())
4558 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004559 }
Steve Naroff54055232008-10-27 17:20:55 +00004560
Daniel Dunbar4087f272010-08-17 22:39:59 +00004561 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4562 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004563
Steve Naroff01aec112009-12-06 21:14:13 +00004564 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004565
Benjamin Kramerd999b372010-02-14 14:14:16 +00004566 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00004567
Steve Naroff01aec112009-12-06 21:14:13 +00004568 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004569
Benjamin Kramerd999b372010-02-14 14:14:16 +00004570 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00004571
4572 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004573 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004574 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00004575 }
Steve Naroff01aec112009-12-06 21:14:13 +00004576 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4577 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004578 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00004579
Steve Naroff54055232008-10-27 17:20:55 +00004580 BlockDeclRefs.clear();
4581 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004582 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004583 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004584 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004585 ImportedBlockDecls.clear();
4586 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004587 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004588 // Must insert any 'const/volatile/static here. Since it has been
4589 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004590 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00004591 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004592 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004593 if (GlobalVarDecl->getType().isConstQualified())
4594 SC += "const ";
4595 if (GlobalVarDecl->getType().isVolatileQualified())
4596 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00004597 if (GlobalVarDecl->getType().isRestrictQualified())
4598 SC += "restrict ";
4599 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00004600 }
4601
Steve Naroff54055232008-10-27 17:20:55 +00004602 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004603 InnerDeclRefsCount.clear();
4604 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00004605 RewrittenBlockExprs.clear();
4606}
4607
4608void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4609 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00004610 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00004611
Steve Naroff54055232008-10-27 17:20:55 +00004612 SynthesizeBlockLiterals(FunLocStart, FuncName);
4613}
4614
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004615static void BuildUniqueMethodName(std::string &Name,
4616 ObjCMethodDecl *MD) {
4617 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00004618 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004619 Name += "__" + MD->getSelector().getAsString();
4620 // Convert colons to underscores.
4621 std::string::size_type loc = 0;
4622 while ((loc = Name.find(":", loc)) != std::string::npos)
4623 Name.replace(loc, 1, "_");
4624}
4625
Steve Naroff54055232008-10-27 17:20:55 +00004626void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004627 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4628 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004629 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004630 std::string FuncName;
4631 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00004632 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00004633}
4634
4635void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00004636 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00004637 if (*CI) {
4638 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4639 GetBlockDeclRefExprs(CBE->getBody());
4640 else
4641 GetBlockDeclRefExprs(*CI);
4642 }
4643 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004644 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00004645 // FIXME: Handle enums.
4646 if (!isa<FunctionDecl>(CDRE->getDecl()))
4647 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004648 }
4649 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4650 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
4651 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00004652 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
4653 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00004654 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004655 BlockDeclRefs.push_back(BDRE);
4656 }
4657
Steve Naroff54055232008-10-27 17:20:55 +00004658 return;
4659}
4660
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004661void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004662 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004663 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00004664 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004665 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004666 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4667 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004668 GetInnerBlockDeclRefExprs(CBE->getBody(),
4669 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004670 InnerContexts);
4671 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004672 else
4673 GetInnerBlockDeclRefExprs(*CI,
4674 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004675 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004676
4677 }
4678 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004679 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004680 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004681 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004682 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004683 }
4684 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4685 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4686 if (Var->isFunctionOrMethodVarDecl())
4687 ImportedLocalExternalDecls.insert(Var);
4688 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004689
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004690 return;
4691}
4692
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004693/// convertFunctionTypeOfBlocks - This routine converts a function type
4694/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00004695/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004696/// all block pointers to function pointers.
4697QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4698 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4699 // FTP will be null for closures that don't take arguments.
4700 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004701 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004702 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004703 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004704
4705 if (FTP) {
4706 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4707 E = FTP->arg_type_end(); I && (I != E); ++I) {
4708 QualType t = *I;
4709 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00004710 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004711 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004712 ArgTypes.push_back(t);
4713 }
4714 }
4715 QualType FuncType;
4716 // FIXME. Does this work if block takes no argument but has a return type
4717 // which is of block type?
4718 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00004719 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004720 else FuncType = QualType(FT, 0);
4721 return FuncType;
4722}
4723
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004724Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004725 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004726 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004727
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004728 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004729 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004730 } else if (const BlockDeclRefExpr *CDRE =
4731 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004732 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004733 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004734 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004735 }
4736 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4737 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4738 }
4739 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4740 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4741 else if (const ConditionalOperator *CEXPR =
4742 dyn_cast<ConditionalOperator>(BlockExp)) {
4743 Expr *LHSExp = CEXPR->getLHS();
4744 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4745 Expr *RHSExp = CEXPR->getRHS();
4746 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4747 Expr *CONDExp = CEXPR->getCond();
4748 ConditionalOperator *CondExpr =
4749 new (Context) ConditionalOperator(CONDExp,
4750 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00004751 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00004752 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004753 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004754 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4755 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004756 } else {
4757 assert(1 && "RewriteBlockClass: Bad type");
4758 }
4759 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004760 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004761 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004762 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004763 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004764
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004765 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004766 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004767 &Context->Idents.get("__block_impl"));
4768 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004769
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004770 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004771 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004772
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004773 // Push the block argument type.
4774 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004775 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004776 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004777 E = FTP->arg_type_end(); I && (I != E); ++I) {
4778 QualType t = *I;
4779 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004780 if (!convertBlockPointerToFunctionPointer(t))
4781 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004782 ArgTypes.push_back(t);
4783 }
Steve Naroff54055232008-10-27 17:20:55 +00004784 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004785 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00004786 QualType PtrToFuncCastType
4787 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004788
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004789 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004790
John McCall9d125032010-01-15 18:39:57 +00004791 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00004792 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004793 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004794 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004795 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4796 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004797 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004798
Douglas Gregor44b43212008-12-11 16:49:14 +00004799 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004800 SourceLocation(),
4801 &Context->Idents.get("FuncPtr"),
4802 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004803 /*BitWidth=*/0, /*Mutable=*/true,
4804 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004805 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004806 FD->getType(), VK_LValue,
4807 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00004808
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00004809
John McCall9d125032010-01-15 18:39:57 +00004810 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00004811 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004812 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004813
Chris Lattner5f9e2722011-07-23 10:55:15 +00004814 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004815 // Add the implicit argument.
4816 BlkExprs.push_back(BlkCast);
4817 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004818 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004819 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004820 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004821 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004822 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4823 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004824 Exp->getType(), VK_RValue,
4825 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004826 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004827}
4828
Steve Naroff621edce2009-04-29 16:37:50 +00004829// We need to return the rewritten expression to handle cases where the
4830// BlockDeclRefExpr is embedded in another expression being rewritten.
4831// For example:
4832//
4833// int main() {
4834// __block Foo *f;
4835// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004836//
Steve Naroff621edce2009-04-29 16:37:50 +00004837// void (^myblock)() = ^() {
4838// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4839// i = 77;
4840// };
4841//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004842Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004843 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004844 // for each DeclRefExp where BYREFVAR is name of the variable.
4845 ValueDecl *VD;
4846 bool isArrow = true;
4847 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4848 VD = BDRE->getDecl();
4849 else {
4850 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4851 isArrow = false;
4852 }
4853
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004854 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004855 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004856 &Context->Idents.get("__forwarding"),
4857 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004858 /*BitWidth=*/0, /*Mutable=*/true,
4859 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004860 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4861 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004862 FD->getType(), VK_LValue,
4863 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004864
Chris Lattner5f9e2722011-07-23 10:55:15 +00004865 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004866 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004867 &Context->Idents.get(Name),
4868 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00004869 /*BitWidth=*/0, /*Mutable=*/true,
4870 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004871 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00004872 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004873
4874
4875
Steve Naroffdf8570d2009-02-02 17:19:26 +00004876 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00004877 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4878 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004879 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004880 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004881 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004882}
4883
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004884// Rewrites the imported local variable V with external storage
4885// (static, extern, etc.) as *V
4886//
4887Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4888 ValueDecl *VD = DRE->getDecl();
4889 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4890 if (!ImportedLocalExternalDecls.count(Var))
4891 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00004892 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4893 VK_LValue, OK_Ordinary,
4894 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004895 // Need parens to enforce precedence.
4896 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4897 Exp);
4898 ReplaceStmt(DRE, PE);
4899 return PE;
4900}
4901
Steve Naroffb2f9e512008-11-03 23:29:32 +00004902void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4903 SourceLocation LocStart = CE->getLParenLoc();
4904 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004905
4906 // Need to avoid trying to rewrite synthesized casts.
4907 if (LocStart.isInvalid())
4908 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004909 // Need to avoid trying to rewrite casts contained in macros.
4910 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4911 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004912
Steve Naroff54055232008-10-27 17:20:55 +00004913 const char *startBuf = SM->getCharacterData(LocStart);
4914 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004915 QualType QT = CE->getType();
4916 const Type* TypePtr = QT->getAs<Type>();
4917 if (isa<TypeOfExprType>(TypePtr)) {
4918 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4919 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4920 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00004921 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004922 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00004923 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004924 return;
4925 }
Steve Naroff54055232008-10-27 17:20:55 +00004926 // advance the location to startArgList.
4927 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004928
Steve Naroff54055232008-10-27 17:20:55 +00004929 while (*argPtr++ && (argPtr < endBuf)) {
4930 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004931 case '^':
4932 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004933 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004934 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004935 break;
Steve Naroff54055232008-10-27 17:20:55 +00004936 }
4937 }
4938 return;
4939}
4940
4941void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4942 SourceLocation DeclLoc = FD->getLocation();
4943 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004944
Steve Naroff54055232008-10-27 17:20:55 +00004945 // We have 1 or more arguments that have closure pointers.
4946 const char *startBuf = SM->getCharacterData(DeclLoc);
4947 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004948
Steve Naroff54055232008-10-27 17:20:55 +00004949 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004950
Steve Naroff54055232008-10-27 17:20:55 +00004951 parenCount++;
4952 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004953 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004954 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004955
Steve Naroff54055232008-10-27 17:20:55 +00004956 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004957
Steve Naroff54055232008-10-27 17:20:55 +00004958 while (*argPtr++ && parenCount) {
4959 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004960 case '^':
4961 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004962 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004963 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004964 break;
4965 case '(':
4966 parenCount++;
4967 break;
4968 case ')':
4969 parenCount--;
4970 break;
Steve Naroff54055232008-10-27 17:20:55 +00004971 }
4972 }
4973 return;
4974}
4975
4976bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004977 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004978 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004979 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004980 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004981 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004982 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004983 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004984 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004985 }
4986 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004987 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004988 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004989 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004990 return true;
4991 }
4992 return false;
4993}
4994
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004995bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4996 const FunctionProtoType *FTP;
4997 const PointerType *PT = QT->getAs<PointerType>();
4998 if (PT) {
4999 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5000 } else {
5001 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5002 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5003 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5004 }
5005 if (FTP) {
5006 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005007 E = FTP->arg_type_end(); I != E; ++I) {
5008 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005009 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00005010 if ((*I)->isObjCObjectPointerType() &&
5011 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5012 return true;
5013 }
5014
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005015 }
5016 return false;
5017}
5018
Ted Kremenek8189cde2009-02-07 01:47:29 +00005019void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5020 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00005021 const char *argPtr = strchr(Name, '(');
5022 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00005023
Steve Naroff54055232008-10-27 17:20:55 +00005024 LParen = argPtr; // output the start.
5025 argPtr++; // skip past the left paren.
5026 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00005027
Steve Naroff54055232008-10-27 17:20:55 +00005028 while (*argPtr && parenCount) {
5029 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00005030 case '(': parenCount++; break;
5031 case ')': parenCount--; break;
5032 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00005033 }
5034 if (parenCount) argPtr++;
5035 }
5036 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5037 RParen = argPtr; // output the end
5038}
5039
5040void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5041 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5042 RewriteBlockPointerFunctionArgs(FD);
5043 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005044 }
Steve Naroff54055232008-10-27 17:20:55 +00005045 // Handle Variables and Typedefs.
5046 SourceLocation DeclLoc = ND->getLocation();
5047 QualType DeclT;
5048 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5049 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00005050 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00005051 DeclT = TDD->getUnderlyingType();
5052 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5053 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00005054 else
David Blaikieb219cfc2011-09-23 05:06:16 +00005055 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00005056
Steve Naroff54055232008-10-27 17:20:55 +00005057 const char *startBuf = SM->getCharacterData(DeclLoc);
5058 const char *endBuf = startBuf;
5059 // scan backward (from the decl location) for the end of the previous decl.
5060 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5061 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005062 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005063 std::string buf;
5064 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00005065 // *startBuf != '^' if we are dealing with a pointer to function that
5066 // may take block argument types (which will be handled below).
5067 if (*startBuf == '^') {
5068 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005069 buf = '*';
5070 startBuf++;
5071 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005072 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005073 while (*startBuf != ')') {
5074 buf += *startBuf;
5075 startBuf++;
5076 OrigLength++;
5077 }
5078 buf += ')';
5079 OrigLength++;
5080
5081 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5082 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00005083 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005084 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00005085 DeclLoc = ND->getLocation();
5086 startBuf = SM->getCharacterData(DeclLoc);
5087 const char *argListBegin, *argListEnd;
5088 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5089 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005090 if (*argListBegin == '^')
5091 buf += '*';
5092 else if (*argListBegin == '<') {
5093 buf += "/*";
5094 buf += *argListBegin++;
5095 OrigLength++;;
5096 while (*argListBegin != '>') {
5097 buf += *argListBegin++;
5098 OrigLength++;
5099 }
5100 buf += *argListBegin;
5101 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00005102 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005103 else
5104 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00005105 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005106 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005107 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005108 buf += ')';
5109 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00005110 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00005111 ReplaceText(Start, OrigLength, buf);
5112
Steve Naroff54055232008-10-27 17:20:55 +00005113 return;
5114}
5115
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005116
5117/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5118/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5119/// struct Block_byref_id_object *src) {
5120/// _Block_object_assign (&_dest->object, _src->object,
5121/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5122/// [|BLOCK_FIELD_IS_WEAK]) // object
5123/// _Block_object_assign(&_dest->object, _src->object,
5124/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5125/// [|BLOCK_FIELD_IS_WEAK]) // block
5126/// }
5127/// And:
5128/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5129/// _Block_object_dispose(_src->object,
5130/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5131/// [|BLOCK_FIELD_IS_WEAK]) // object
5132/// _Block_object_dispose(_src->object,
5133/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5134/// [|BLOCK_FIELD_IS_WEAK]) // block
5135/// }
5136
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005137std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5138 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005139 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00005140 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005141 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005142 CopyDestroyCache.insert(flag);
5143 S = "static void __Block_byref_id_object_copy_";
5144 S += utostr(flag);
5145 S += "(void *dst, void *src) {\n";
5146
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005147 // offset into the object pointer is computed as:
5148 // void * + void* + int + int + void* + void *
5149 unsigned IntSize =
5150 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5151 unsigned VoidPtrSize =
5152 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5153
Ken Dyck0c4e5d62011-04-30 16:08:27 +00005154 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005155 S += " _Block_object_assign((char*)dst + ";
5156 S += utostr(offset);
5157 S += ", *(void * *) ((char*)src + ";
5158 S += utostr(offset);
5159 S += "), ";
5160 S += utostr(flag);
5161 S += ");\n}\n";
5162
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005163 S += "static void __Block_byref_id_object_dispose_";
5164 S += utostr(flag);
5165 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005166 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5167 S += utostr(offset);
5168 S += "), ";
5169 S += utostr(flag);
5170 S += ");\n}\n";
5171 return S;
5172}
5173
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005174/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5175/// the declaration into:
5176/// struct __Block_byref_ND {
5177/// void *__isa; // NULL for everything except __weak pointers
5178/// struct __Block_byref_ND *__forwarding;
5179/// int32_t __flags;
5180/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005181/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5182/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005183/// typex ND;
5184/// };
5185///
5186/// It then replaces declaration of ND variable with:
5187/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5188/// __size=sizeof(struct __Block_byref_ND),
5189/// ND=initializer-if-any};
5190///
5191///
5192void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005193 // Insert declaration for the function in which block literal is
5194 // used.
5195 if (CurFunctionDeclToDeclareForBlock)
5196 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005197 int flag = 0;
5198 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005199 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00005200 if (DeclLoc.isInvalid())
5201 // If type location is missing, it is because of missing type (a warning).
5202 // Use variable's location which is good for this case.
5203 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005204 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005205 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00005206 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00005207 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005208 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005209 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005210 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005211 ByrefType += " {\n";
5212 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005213 RewriteByRefString(ByrefType, Name, ND);
5214 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005215 ByrefType += " int __flags;\n";
5216 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005217 // Add void *__Block_byref_id_object_copy;
5218 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005219 QualType Ty = ND->getType();
5220 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
5221 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005222 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5223 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005224 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005225
5226 QualType T = Ty;
5227 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00005228 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005229
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005230 ByrefType += " " + Name + ";\n";
5231 ByrefType += "};\n";
5232 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005233 SourceLocation FunLocStart;
5234 if (CurFunctionDef)
5235 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
5236 else {
5237 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5238 FunLocStart = CurMethodDef->getLocStart();
5239 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005240 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005241 if (Ty.isObjCGCWeak()) {
5242 flag |= BLOCK_FIELD_IS_WEAK;
5243 isa = 1;
5244 }
5245
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005246 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005247 flag = BLOCK_BYREF_CALLER;
5248 QualType Ty = ND->getType();
5249 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5250 if (Ty->isBlockPointerType())
5251 flag |= BLOCK_FIELD_IS_BLOCK;
5252 else
5253 flag |= BLOCK_FIELD_IS_OBJECT;
5254 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005255 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00005256 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005257 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005258
5259 // struct __Block_byref_ND ND =
5260 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5261 // initializer-if-any};
5262 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00005263 unsigned flags = 0;
5264 if (HasCopyAndDispose)
5265 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005266 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005267 ByrefType.clear();
5268 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005269 std::string ForwardingCastType("(");
5270 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005271 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005272 ByrefType += " " + Name + " = {(void*)";
5273 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005274 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005275 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005276 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005277 ByrefType += "sizeof(";
5278 RewriteByRefString(ByrefType, Name, ND);
5279 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005280 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005281 ByrefType += ", __Block_byref_id_object_copy_";
5282 ByrefType += utostr(flag);
5283 ByrefType += ", __Block_byref_id_object_dispose_";
5284 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005285 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005286 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00005287 unsigned nameSize = Name.size();
5288 // for block or function pointer declaration. Name is aleady
5289 // part of the declaration.
5290 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5291 nameSize = 1;
5292 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005293 }
5294 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005295 SourceLocation startLoc;
5296 Expr *E = ND->getInit();
5297 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5298 startLoc = ECE->getLParenLoc();
5299 else
5300 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00005301 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005302 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005303 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00005304 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00005305 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005306 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005307 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005308 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005309 ByrefType += "sizeof(";
5310 RewriteByRefString(ByrefType, Name, ND);
5311 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005312 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00005313 ByrefType += "__Block_byref_id_object_copy_";
5314 ByrefType += utostr(flag);
5315 ByrefType += ", __Block_byref_id_object_dispose_";
5316 ByrefType += utostr(flag);
5317 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00005318 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00005319 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00005320
5321 // Complete the newly synthesized compound expression by inserting a right
5322 // curly brace before the end of the declaration.
5323 // FIXME: This approach avoids rewriting the initializer expression. It
5324 // also assumes there is only one declarator. For example, the following
5325 // isn't currently supported by this routine (in general):
5326 //
5327 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
5328 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00005329 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5330 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00005331 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
5332 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00005333 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00005334
Benjamin Kramerd999b372010-02-14 14:14:16 +00005335 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005336 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00005337 return;
5338}
5339
Mike Stump1eb44332009-09-09 15:08:12 +00005340void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00005341 // Add initializers for any closure decl refs.
5342 GetBlockDeclRefExprs(Exp->getBody());
5343 if (BlockDeclRefs.size()) {
5344 // Unique all "by copy" declarations.
5345 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005346 if (!BlockDeclRefs[i]->isByRef()) {
5347 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5348 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5349 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5350 }
5351 }
Steve Naroff54055232008-10-27 17:20:55 +00005352 // Unique all "by ref" declarations.
5353 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5354 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005355 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5356 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5357 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5358 }
Steve Naroff54055232008-10-27 17:20:55 +00005359 }
5360 // Find any imported blocks...they will need special attention.
5361 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00005362 if (BlockDeclRefs[i]->isByRef() ||
5363 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00005364 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00005365 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00005366 }
5367}
5368
Chris Lattner5f9e2722011-07-23 10:55:15 +00005369FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005370 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00005371 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005372 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5373 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00005374 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00005375}
5376
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005377Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00005378 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005379 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00005380 Blocks.push_back(Exp);
5381
5382 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005383
5384 // Add inner imported variables now used in current block.
5385 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005386 if (!InnerBlockDeclRefs.empty()) {
5387 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5388 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
5389 ValueDecl *VD = Exp->getDecl();
5390 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005391 // We need to save the copied-in variables in nested
5392 // blocks because it is needed at the end for some of the API generations.
5393 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005394 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5395 BlockDeclRefs.push_back(Exp);
5396 BlockByCopyDeclsPtrSet.insert(VD);
5397 BlockByCopyDecls.push_back(VD);
5398 }
5399 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
5400 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5401 BlockDeclRefs.push_back(Exp);
5402 BlockByRefDeclsPtrSet.insert(VD);
5403 BlockByRefDecls.push_back(VD);
5404 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005405 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00005406 // Find any imported blocks...they will need special attention.
5407 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5408 if (InnerBlockDeclRefs[i]->isByRef() ||
5409 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5410 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5411 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005412 }
5413 InnerDeclRefsCount.push_back(countOfInnerDecls);
5414
Steve Narofffa15fd92008-10-28 20:29:00 +00005415 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00005416
Steve Narofffa15fd92008-10-28 20:29:00 +00005417 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00005418 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00005419 else if (CurMethodDef)
5420 BuildUniqueMethodName(FuncName, CurMethodDef);
5421 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00005422 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00005423
Steve Narofffa15fd92008-10-28 20:29:00 +00005424 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00005425
Steve Narofffa15fd92008-10-28 20:29:00 +00005426 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
5427 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00005428
Steve Narofffa15fd92008-10-28 20:29:00 +00005429 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00005430 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5431 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00005432
5433 FunctionDecl *FD;
5434 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00005435
Steve Narofffa15fd92008-10-28 20:29:00 +00005436 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00005437 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00005438 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
5439 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00005440
Chris Lattner5f9e2722011-07-23 10:55:15 +00005441 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00005442
Steve Narofffdc03722008-10-29 21:23:59 +00005443 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00005444 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00005445 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00005446 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005447 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005448 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00005449 InitExprs.push_back(castExpr);
5450
Steve Naroff01aec112009-12-06 21:14:13 +00005451 // Initialize the block descriptor.
5452 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00005453
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00005454 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5455 SourceLocation(), SourceLocation(),
5456 &Context->Idents.get(DescData.c_str()),
5457 Context->VoidPtrTy, 0,
5458 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00005459 UnaryOperator *DescRefExpr =
5460 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
5461 Context->VoidPtrTy,
5462 VK_LValue,
5463 SourceLocation()),
5464 UO_AddrOf,
5465 Context->getPointerType(Context->VoidPtrTy),
5466 VK_RValue, OK_Ordinary,
5467 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00005468 InitExprs.push_back(DescRefExpr);
5469
Steve Narofffa15fd92008-10-28 20:29:00 +00005470 // Add initializers for any closure decl refs.
5471 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00005472 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00005473 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005474 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005475 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005476 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00005477 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00005478 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005479 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5480 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005481 if (HasLocalVariableExternalStorage(*I)) {
5482 QualType QT = (*I)->getType();
5483 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005484 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5485 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00005486 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005487 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005488 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005489 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5490 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00005491 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00005492 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00005493 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00005494 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005495 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5496 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005497 if (HasLocalVariableExternalStorage(*I)) {
5498 QualType QT = (*I)->getType();
5499 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00005500 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5501 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005502 }
5503
Steve Narofffa15fd92008-10-28 20:29:00 +00005504 }
Mike Stump1eb44332009-09-09 15:08:12 +00005505 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005506 }
5507 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00005508 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00005509 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005510 ValueDecl *ND = (*I);
5511 std::string Name(ND->getNameAsString());
5512 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00005513 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005514 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5515 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00005516 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00005517 SourceLocation(), SourceLocation(),
5518 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00005519 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5520 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5521
Daniel Dunbar4087f272010-08-17 22:39:59 +00005522 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00005523 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
5524 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00005525 bool isNestedCapturedVar = false;
5526 if (block)
5527 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5528 ce = block->capture_end(); ci != ce; ++ci) {
5529 const VarDecl *variable = ci->getVariable();
5530 if (variable == ND && ci->isNested()) {
5531 assert (ci->isByRef() &&
5532 "SynthBlockInitExpr - captured block variable is not byref");
5533 isNestedCapturedVar = true;
5534 break;
5535 }
5536 }
5537 // captured nested byref variable has its address passed. Do not take
5538 // its address again.
5539 if (!isNestedCapturedVar)
5540 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00005541 Context->getPointerType(Exp->getType()),
5542 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005543 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00005544 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00005545 }
5546 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00005547 if (ImportedBlockDecls.size()) {
5548 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5549 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00005550 unsigned IntSize =
5551 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00005552 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5553 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00005554 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00005555 }
Ted Kremenek668bf912009-02-09 20:51:47 +00005556 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00005557 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00005558 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00005559 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00005560 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00005561 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00005562 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00005563 BlockDeclRefs.clear();
5564 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005565 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005566 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00005567 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005568 ImportedBlockDecls.clear();
5569 return NewRep;
5570}
5571
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005572bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5573 if (const ObjCForCollectionStmt * CS =
5574 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5575 return CS->getElement() == DS;
5576 return false;
5577}
5578
Steve Narofffa15fd92008-10-28 20:29:00 +00005579//===----------------------------------------------------------------------===//
5580// Function Body / Expression rewriting
5581//===----------------------------------------------------------------------===//
5582
Steve Naroffc77a6362008-12-04 16:24:46 +00005583// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
5584// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
5585// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
5586// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
5587// Since the rewriter isn't capable of rewriting rewritten code, it's important
5588// we get this right.
5589void RewriteObjC::CollectPropertySetters(Stmt *S) {
5590 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005591 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffc77a6362008-12-04 16:24:46 +00005592 if (*CI)
5593 CollectPropertySetters(*CI);
5594
5595 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
5596 if (BinOp->isAssignmentOp()) {
John McCall12f78a62010-12-02 01:19:52 +00005597 if (isa<ObjCPropertyRefExpr>(BinOp->getLHS()))
5598 PropSetters[BinOp->getLHS()] = BinOp;
Steve Naroffc77a6362008-12-04 16:24:46 +00005599 }
5600 }
5601}
5602
Steve Narofffa15fd92008-10-28 20:29:00 +00005603Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00005604 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005605 isa<DoStmt>(S) || isa<ForStmt>(S))
5606 Stmts.push_back(S);
5607 else if (isa<ObjCForCollectionStmt>(S)) {
5608 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00005609 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00005610 }
Mike Stump1eb44332009-09-09 15:08:12 +00005611
Steve Narofffa15fd92008-10-28 20:29:00 +00005612 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00005613
Steve Narofffa15fd92008-10-28 20:29:00 +00005614 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00005615 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00005616 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005617 Stmt *newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005618 Stmt *ChildStmt = (*CI);
5619 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(ChildStmt)) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005620 Expr *OldBase = IvarRefExpr->getBase();
5621 bool replaced = false;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005622 newStmt = RewriteObjCNestedIvarRefExpr(ChildStmt, replaced);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005623 if (replaced) {
5624 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
5625 ReplaceStmt(OldBase, IRE->getBase());
5626 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005627 ReplaceStmt(ChildStmt, newStmt);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00005628 }
5629 }
5630 else
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005631 newStmt = RewriteFunctionBodyOrGlobalInitializer(ChildStmt);
5632 if (newStmt) {
5633 if (Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(ChildStmt))
5634 if (PropSetters[PropOrImplicitRefExpr] == S) {
5635 S = newStmt;
5636 newStmt = 0;
5637 }
5638 if (newStmt)
5639 *CI = newStmt;
5640 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005641 // If dealing with an assignment with LHS being a property reference
5642 // expression, the entire assignment tree is rewritten into a property
5643 // setter messaging. This involvs the RHS too. Do not attempt to rewrite
5644 // RHS again.
Fariborz Jahanian1d015312011-04-11 21:17:02 +00005645 if (Expr *Exp = dyn_cast<Expr>(ChildStmt))
John McCall12f78a62010-12-02 01:19:52 +00005646 if (isa<ObjCPropertyRefExpr>(Exp)) {
Fariborz Jahanian8537f7b2010-10-11 22:21:03 +00005647 if (PropSetters[Exp]) {
5648 ++CI;
5649 continue;
5650 }
Fariborz Jahanian90fe4bc2010-10-08 21:12:22 +00005651 }
Nick Lewycky7e749242010-10-31 21:07:24 +00005652 }
Mike Stump1eb44332009-09-09 15:08:12 +00005653
Steve Narofffa15fd92008-10-28 20:29:00 +00005654 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00005655 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005656 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5657 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005658 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005659 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00005660 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00005661 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005662 Stmt *SaveCurrentBody = CurrentBody;
5663 CurrentBody = BE->getBody();
Fariborz Jahanian36178092011-04-08 23:48:29 +00005664 CollectPropertySetters(CurrentBody);
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005665 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005666 // block literal on rhs of a property-dot-sytax assignment
5667 // must be replaced by its synthesize ast so getRewrittenText
5668 // works as expected. In this case, what actually ends up on RHS
5669 // is the blockTranscribed which is the helper function for the
5670 // block literal; as in: self.c = ^() {[ace ARR];};
5671 bool saveDisableReplaceStmt = DisableReplaceStmt;
5672 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00005673 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005674 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00005675 CurrentBody = SaveCurrentBody;
5676 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005677 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00005678 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00005679 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005680 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00005681
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00005682 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5683
Steve Narofffa15fd92008-10-28 20:29:00 +00005684 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005685 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00005686 return blockTranscribed;
5687 }
5688 // Handle specific things.
5689 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5690 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00005691
John McCall12f78a62010-12-02 01:19:52 +00005692 if (isa<ObjCPropertyRefExpr>(S)) {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005693 Expr *PropOrImplicitRefExpr = dyn_cast<Expr>(S);
5694 assert(PropOrImplicitRefExpr && "Property or implicit setter/getter is null");
5695
5696 BinaryOperator *BinOp = PropSetters[PropOrImplicitRefExpr];
Steve Naroffc77a6362008-12-04 16:24:46 +00005697 if (BinOp) {
5698 // Because the rewriter doesn't allow us to rewrite rewritten code,
5699 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00005700 DisableReplaceStmt = true;
5701 // Save the source range. Even if we disable the replacement, the
5702 // rewritten node will have been inserted into the tree. If the synthesized
5703 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00005704 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00005705 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
5706 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00005707 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Fariborz Jahanianf2c6fa42010-10-14 23:31:39 +00005708 // Need to rewrite the ivar access expression if need be.
5709 if (isa<ObjCIvarRefExpr>(newStmt)) {
5710 bool replaced = false;
5711 newStmt = RewriteObjCNestedIvarRefExpr(newStmt, replaced);
5712 }
5713
Steve Naroffb619d952008-12-09 12:56:34 +00005714 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00005715 //
5716 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
5717 // we changed the RHS of BinOp, the rewriter would fail (since it needs
5718 // to see the original expression). Consider this example:
5719 //
5720 // Foo *obj1, *obj2;
5721 //
5722 // obj1.i = [obj2 rrrr];
5723 //
5724 // 'BinOp' for the previous expression looks like:
5725 //
5726 // (BinaryOperator 0x231ccf0 'int' '='
5727 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
5728 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
5729 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
5730 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
5731 //
5732 // 'newStmt' represents the rewritten message expression. For example:
5733 //
5734 // (CallExpr 0x231d300 'id':'struct objc_object *'
5735 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
5736 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
5737 // (CStyleCastExpr 0x231d220 'void *'
5738 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
5739 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005740 // Note that 'newStmt' is passed to RewritePropertyOrImplicitSetter so that it
Steve Naroff4c3580e2008-12-04 23:50:32 +00005741 // can be used as the setter argument. ReplaceStmt() will still 'see'
5742 // the original RHS (since we haven't altered BinOp).
5743 //
Mike Stump1eb44332009-09-09 15:08:12 +00005744 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00005745 // node. As a result, we now leak the original AST nodes.
5746 //
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005747 return RewritePropertyOrImplicitSetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00005748 } else {
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005749 return RewritePropertyOrImplicitGetter(PropOrImplicitRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00005750 }
5751 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00005752
Steve Narofffa15fd92008-10-28 20:29:00 +00005753 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5754 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00005755
Steve Narofffa15fd92008-10-28 20:29:00 +00005756 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5757 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00005758
Steve Narofffa15fd92008-10-28 20:29:00 +00005759 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00005760#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00005761 // Before we rewrite it, put the original message expression in a comment.
5762 SourceLocation startLoc = MessExpr->getLocStart();
5763 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00005764
Steve Narofffa15fd92008-10-28 20:29:00 +00005765 const char *startBuf = SM->getCharacterData(startLoc);
5766 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00005767
Steve Narofffa15fd92008-10-28 20:29:00 +00005768 std::string messString;
5769 messString += "// ";
5770 messString.append(startBuf, endBuf-startBuf+1);
5771 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00005772
5773 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005774 // InsertText(clang::SourceLocation, char const*, unsigned int).
5775 // InsertText(startLoc, messString.c_str(), messString.size());
5776 // Tried this, but it didn't work either...
5777 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005778#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005779 return RewriteMessageExpr(MessExpr);
5780 }
Mike Stump1eb44332009-09-09 15:08:12 +00005781
Steve Narofffa15fd92008-10-28 20:29:00 +00005782 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5783 return RewriteObjCTryStmt(StmtTry);
5784
5785 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5786 return RewriteObjCSynchronizedStmt(StmtTry);
5787
5788 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5789 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005790
Steve Narofffa15fd92008-10-28 20:29:00 +00005791 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5792 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005793
5794 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005795 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005796 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005797 OrigStmtRange.getEnd());
5798 if (BreakStmt *StmtBreakStmt =
5799 dyn_cast<BreakStmt>(S))
5800 return RewriteBreakStmt(StmtBreakStmt);
5801 if (ContinueStmt *StmtContinueStmt =
5802 dyn_cast<ContinueStmt>(S))
5803 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005804
5805 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005806 // and cast exprs.
5807 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5808 // FIXME: What we're doing here is modifying the type-specifier that
5809 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005810 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005811 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5812 // the context of an ObjCForCollectionStmt. For example:
5813 // NSArray *someArray;
5814 // for (id <FooProtocol> index in someArray) ;
5815 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5816 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00005817 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005818 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005819
Steve Narofffa15fd92008-10-28 20:29:00 +00005820 // Blocks rewrite rules.
5821 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5822 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005823 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005824 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005825 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005826 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005827 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005828 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005829 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005830 if (VD->hasAttr<BlocksAttr>()) {
5831 static unsigned uniqueByrefDeclCount = 0;
5832 assert(!BlockByRefDeclNo.count(ND) &&
5833 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5834 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005835 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005836 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00005837 else
5838 RewriteTypeOfDecl(VD);
5839 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005840 }
Richard Smith162e1c12011-04-15 14:24:37 +00005841 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005842 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005843 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005844 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005845 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5846 }
5847 }
5848 }
Mike Stump1eb44332009-09-09 15:08:12 +00005849
Steve Narofffa15fd92008-10-28 20:29:00 +00005850 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5851 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005852
5853 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005854 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5855 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005856 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5857 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005858 && "Statement stack mismatch");
5859 Stmts.pop_back();
5860 }
5861 // Handle blocks rewriting.
5862 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5863 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005864 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005865 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005866 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5867 ValueDecl *VD = DRE->getDecl();
5868 if (VD->hasAttr<BlocksAttr>())
5869 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00005870 if (HasLocalVariableExternalStorage(VD))
5871 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005872 }
5873
Steve Narofffa15fd92008-10-28 20:29:00 +00005874 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005875 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005876 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005877 ReplaceStmt(S, BlockCall);
5878 return BlockCall;
5879 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005880 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005881 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005882 RewriteCastExpr(CE);
5883 }
5884#if 0
5885 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00005886 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5887 ICE->getSubExpr(),
5888 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005889 // Get the new text.
5890 std::string SStr;
5891 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005892 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005893 const std::string &Str = Buf.str();
5894
5895 printf("CAST = %s\n", &Str[0]);
5896 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5897 delete S;
5898 return Replacement;
5899 }
5900#endif
5901 // Return this stmt unmodified.
5902 return S;
5903}
5904
Steve Naroff3d7e7862009-12-05 15:55:59 +00005905void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5906 for (RecordDecl::field_iterator i = RD->field_begin(),
5907 e = RD->field_end(); i != e; ++i) {
5908 FieldDecl *FD = *i;
5909 if (isTopLevelBlockPointerType(FD->getType()))
5910 RewriteBlockPointerDecl(FD);
5911 if (FD->getType()->isObjCQualifiedIdType() ||
5912 FD->getType()->isObjCQualifiedInterfaceType())
5913 RewriteObjCQualifiedInterfaceTypes(FD);
5914 }
5915}
5916
Steve Narofffa15fd92008-10-28 20:29:00 +00005917/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5918/// main file of the input.
5919void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5920 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005921 if (FD->isOverloadedOperator())
5922 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005923
Steve Narofffa15fd92008-10-28 20:29:00 +00005924 // Since function prototypes don't have ParmDecl's, we check the function
5925 // prototype. This enables us to rewrite function declarations and
5926 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005927 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005928
Sebastian Redld3a413d2009-04-26 20:35:05 +00005929 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis5f1bfc12010-07-07 11:31:34 +00005930 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005931 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005932 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005933 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005934 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005935 Body =
5936 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5937 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005938 CurrentBody = 0;
5939 if (PropParentMap) {
5940 delete PropParentMap;
5941 PropParentMap = 0;
5942 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005943 // This synthesizes and inserts the block "impl" struct, invoke function,
5944 // and any copy/dispose helper functions.
5945 InsertBlockLiteralsWithinFunction(FD);
5946 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005947 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005948 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005949 return;
5950 }
5951 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005952 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005953 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005954 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005955 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005956 Body =
5957 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5958 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005959 CurrentBody = 0;
5960 if (PropParentMap) {
5961 delete PropParentMap;
5962 PropParentMap = 0;
5963 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005964 InsertBlockLiteralsWithinMethod(MD);
5965 CurMethodDef = 0;
5966 }
5967 }
5968 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5969 ClassImplementation.push_back(CI);
5970 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5971 CategoryImplementation.push_back(CI);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +00005972 else if (isa<ObjCClassDecl>(D))
David Blaikieb219cfc2011-09-23 05:06:16 +00005973 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
Steve Narofffa15fd92008-10-28 20:29:00 +00005974 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5975 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005976 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005977 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005978 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005979 CheckFunctionPointerDecl(VD->getType(), VD);
5980 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005981 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005982 RewriteCastExpr(CE);
5983 }
5984 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005985 } else if (VD->getType()->isRecordType()) {
5986 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
John McCall5e1cdac2011-10-07 06:10:15 +00005987 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00005988 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005989 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005990 if (VD->getInit()) {
5991 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005992 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005993 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005994 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005995 CurrentBody = 0;
5996 if (PropParentMap) {
5997 delete PropParentMap;
5998 PropParentMap = 0;
5999 }
Mike Stump1eb44332009-09-09 15:08:12 +00006000 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Daniel Dunbar4087f272010-08-17 22:39:59 +00006001 VD->getName());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00006002 GlobalVarDecl = 0;
6003
6004 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00006005 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00006006 RewriteCastExpr(CE);
6007 }
6008 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006009 return;
6010 }
Richard Smith162e1c12011-04-15 14:24:37 +00006011 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00006012 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00006013 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00006014 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00006015 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6016 return;
6017 }
6018 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
John McCall5e1cdac2011-10-07 06:10:15 +00006019 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00006020 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00006021 return;
6022 }
6023 // Nothing yet.
6024}
6025
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00006026void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00006027 if (Diags.hasErrorOccurred())
6028 return;
Mike Stump1eb44332009-09-09 15:08:12 +00006029
Steve Narofffa15fd92008-10-28 20:29:00 +00006030 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00006031
Steve Naroff621edce2009-04-29 16:37:50 +00006032 // Here's a great place to add any extra declarations that may be needed.
6033 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00006034 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00006035 E = ProtocolExprDecls.end(); I != E; ++I)
6036 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
6037
Benjamin Kramerd999b372010-02-14 14:14:16 +00006038 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00006039 if (ClassImplementation.size() || CategoryImplementation.size())
6040 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00006041
Steve Narofffa15fd92008-10-28 20:29:00 +00006042 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6043 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00006044 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00006045 Rewrite.getRewriteBufferFor(MainFileID)) {
6046 //printf("Changed:\n");
6047 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6048 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00006049 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00006050 }
Steve Narofface66252008-11-13 20:07:04 +00006051
Steve Naroff621edce2009-04-29 16:37:50 +00006052 if (ClassImplementation.size() || CategoryImplementation.size() ||
6053 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00006054 // Rewrite Objective-c meta data*
6055 std::string ResultStr;
6056 SynthesizeMetaDataIntoBuffer(ResultStr);
6057 // Emit metadata.
6058 *OutFile << ResultStr;
6059 }
Steve Narofffa15fd92008-10-28 20:29:00 +00006060 OutFile->flush();
6061}