blob: f50282ef8b34b80499fbe5a4875942fe87cd6b0e [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 Jahaniand5c3fa22011-12-08 18:25:15 +000035 protected:
36
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000037 enum {
Nico Weber59b173d2010-11-22 10:26:41 +000038 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000039 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
Nico Weber59b173d2010-11-22 10:26:41 +000043 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000044 helpers */
Nico Weber59b173d2010-11-22 10:26:41 +000045 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000046 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
Fariborz Jahanian58457172011-12-05 18:43:13 +000058 static const int OBJC_ABI_VERSION = 7;
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000059
Chris Lattner2c64b7b2007-10-16 21:07:07 +000060 Rewriter Rewrite;
David Blaikied6471f72011-09-25 23:23:43 +000061 DiagnosticsEngine &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000062 const LangOptions &LangOpts;
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;
Fariborz Jahanian58457172011-12-05 18:43:13 +000068 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000070 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
76 unsigned RewriteFailedDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000077 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
Fariborz Jahanian58457172011-12-05 18:43:13 +000081
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000082 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +000085 unsigned TryFinallyContainsReturnDiag;
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +000086 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Mike Stump1eb44332009-09-09 15:08:12 +0000104
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000105 /* Misc. containers needed for meta-data rewrite. */
Chris Lattner5f9e2722011-07-23 10:55:15 +0000106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +0000109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
111 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000112 SmallVector<Stmt *, 32> Stmts;
113 SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +0000114 // Remember all the @protocol(<expr>) expressions.
115 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000116
117 llvm::DenseSet<uint64_t> CopyDestroyCache;
Steve Naroff54055232008-10-27 17:20:55 +0000118
119 // Block expressions.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000120 SmallVector<BlockExpr *, 32> Blocks;
121 SmallVector<int, 32> InnerDeclRefsCount;
122 SmallVector<BlockDeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000123
Chris Lattner5f9e2722011-07-23 10:55:15 +0000124 SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000127 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
Chris Lattner5f9e2722011-07-23 10:55:15 +0000129 SmallVector<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahanianbab71682010-02-11 23:35:57 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000131 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000132 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000133 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
134
Steve Naroff54055232008-10-27 17:20:55 +0000135 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
136
Steve Naroff4c3580e2008-12-04 23:50:32 +0000137 // This maps an original source AST to it's rewritten form. This allows
138 // us to avoid rewriting the same node twice (which is very uncommon).
139 // This is needed to support some of the exotic property rewriting.
140 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000141
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000142 // Needed for header files being rewritten
143 bool IsHeader;
144 bool SilenceRewriteMacroWarning;
145 bool objc_impl_method;
146
Steve Naroffb619d952008-12-09 12:56:34 +0000147 bool DisableReplaceStmt;
John McCall4b9c2d22011-11-06 09:01:30 +0000148 class DisableReplaceStmtScope {
149 RewriteObjC &R;
150 bool SavedValue;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000151
John McCall4b9c2d22011-11-06 09:01:30 +0000152 public:
153 DisableReplaceStmtScope(RewriteObjC &R)
154 : R(R), SavedValue(R.DisableReplaceStmt) {
155 R.DisableReplaceStmt = true;
156 }
157 ~DisableReplaceStmtScope() {
158 R.DisableReplaceStmt = SavedValue;
159 }
160 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000161 void InitializeCommon(ASTContext &context);
Mike Stump1eb44332009-09-09 15:08:12 +0000162
Chris Lattner77cd2a02007-10-11 00:43:27 +0000163 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000164
Chris Lattnerf04da132007-10-24 17:06:59 +0000165 // Top Level Driver code.
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000166 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000167 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
168 if (isa<ObjCClassDecl>((*I))) {
169 RewriteForwardClassDecl(D);
170 break;
171 }
Chris Lattner682bf922009-03-29 16:50:03 +0000172 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000173 }
Argyrios Kyrtzidis88c25962011-11-18 00:26:59 +0000174 return true;
Chris Lattner682bf922009-03-29 16:50:03 +0000175 }
176 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000177 void HandleDeclInMainFile(Decl *D);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000178 RewriteObjC(std::string inFile, raw_ostream *OS,
David Blaikied6471f72011-09-25 23:23:43 +0000179 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000180 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000181
182 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000183
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000184 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000185
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000186 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000187 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000188
Steve Naroff4c3580e2008-12-04 23:50:32 +0000189 if (ReplacingStmt)
190 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000191
Steve Naroffb619d952008-12-09 12:56:34 +0000192 if (DisableReplaceStmt)
John McCall4b9c2d22011-11-06 09:01:30 +0000193 return;
Steve Naroffb619d952008-12-09 12:56:34 +0000194
Steve Naroff4c3580e2008-12-04 23:50:32 +0000195 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000196 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000197 ReplacedNodes[Old] = New;
198 return;
199 }
200 if (SilenceRewriteMacroWarning)
201 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000202 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
203 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000204 }
Steve Naroffb619d952008-12-09 12:56:34 +0000205
206 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
John McCall4b9c2d22011-11-06 09:01:30 +0000207 if (DisableReplaceStmt)
208 return;
209
Nick Lewycky7e749242010-10-31 21:07:24 +0000210 // Measure the old text.
Steve Naroffb619d952008-12-09 12:56:34 +0000211 int Size = Rewrite.getRangeSize(SrcRange);
212 if (Size == -1) {
213 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
214 << Old->getSourceRange();
215 return;
216 }
217 // Get the new text.
218 std::string SStr;
219 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000220 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000221 const std::string &Str = S.str();
222
223 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000224 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000225 ReplacedNodes[Old] = New;
226 return;
227 }
228 if (SilenceRewriteMacroWarning)
229 return;
230 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
231 << Old->getSourceRange();
232 }
233
Chris Lattner5f9e2722011-07-23 10:55:15 +0000234 void InsertText(SourceLocation Loc, StringRef Str,
Steve Naroffba92b2e2008-03-27 22:29:16 +0000235 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000236 // If insertion succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000237 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000238 SilenceRewriteMacroWarning)
239 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000240
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000241 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
242 }
Mike Stump1eb44332009-09-09 15:08:12 +0000243
Chris Lattneraadaf782008-01-31 19:51:04 +0000244 void ReplaceText(SourceLocation Start, unsigned OrigLength,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000245 StringRef Str) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000246 // If removal succeeded or warning disabled return with no warning.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000247 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000248 SilenceRewriteMacroWarning)
249 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000250
Chris Lattneraadaf782008-01-31 19:51:04 +0000251 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
252 }
Mike Stump1eb44332009-09-09 15:08:12 +0000253
Chris Lattnerf04da132007-10-24 17:06:59 +0000254 // Syntactic Rewriting.
Fariborz Jahanian58457172011-12-05 18:43:13 +0000255 void RewriteRecordBody(RecordDecl *RD);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000256 void RewriteInclude();
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000257 void RewriteForwardClassDecl(DeclGroupRef D);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000258 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
259 void RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
260 const std::string &typedefString);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000261 void RewriteImplementations();
Steve Naroffa0876e82008-12-02 17:36:43 +0000262 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
263 ObjCImplementationDecl *IMD,
264 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000266 void RewriteImplementationDecl(Decl *Dcl);
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000267 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
268 ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000269 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
270 const FunctionType *&FPRetType);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000271 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +0000272 ValueDecl *VD, bool def=false);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000273 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
274 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
275 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
276 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000277 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000278 void RewriteFunctionDecl(FunctionDecl *FD);
Daniel Dunbarfa297fb2010-06-30 19:16:53 +0000279 void RewriteBlockPointerType(std::string& Str, QualType Type);
280 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000281 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000282 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +0000283 void RewriteTypeOfDecl(VarDecl *VD);
Steve Naroff4f95b752008-07-29 18:15:38 +0000284 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000285
Chris Lattnerf04da132007-10-24 17:06:59 +0000286 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000287 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
John McCall4b9c2d22011-11-06 09:01:30 +0000289 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
290 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
Steve Naroffb42f8412007-11-05 14:50:49 +0000291 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000292 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000293 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000294 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000295 void RewriteTryReturnStmts(Stmt *S);
296 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000297 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000298 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000299 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000300 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
301 SourceLocation OrigEnd);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000302 Stmt *RewriteBreakStmt(BreakStmt *S);
303 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000304 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000305
Steve Naroff54055232008-10-27 17:20:55 +0000306 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000307 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000308
Mike Stump1eb44332009-09-09 15:08:12 +0000309 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000310 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000311 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000312 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +0000313 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
Steve Naroff54055232008-10-27 17:20:55 +0000314 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000315
316 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
317 std::string &Result);
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000318
319 virtual void Initialize(ASTContext &context) = 0;
320
321 // Metadata Rewriting.
322 virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
323 virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
324 StringRef prefix,
325 StringRef ClassName,
326 std::string &Result) = 0;
327 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
328 std::string &Result) = 0;
329 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
330 StringRef prefix,
331 StringRef ClassName,
332 std::string &Result) = 0;
333 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
334 std::string &Result) = 0;
335
336 // Rewriting ivar access
337 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
338 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
339 std::string &Result) = 0;
Fariborz Jahanian58457172011-12-05 18:43:13 +0000340
341 // Misc. AST transformation routines. Somtimes they end up calling
342 // rewriting routines on the new ASTs.
343 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
344 Expr **args, unsigned nargs,
345 SourceLocation StartLoc=SourceLocation(),
346 SourceLocation EndLoc=SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +0000347
Fariborz Jahanian58457172011-12-05 18:43:13 +0000348 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
349 SourceLocation StartLoc=SourceLocation(),
350 SourceLocation EndLoc=SourceLocation());
351
352 void SynthCountByEnumWithState(std::string &buf);
353 void SynthMsgSendFunctionDecl();
354 void SynthMsgSendSuperFunctionDecl();
355 void SynthMsgSendStretFunctionDecl();
356 void SynthMsgSendFpretFunctionDecl();
357 void SynthMsgSendSuperStretFunctionDecl();
358 void SynthGetClassFunctionDecl();
359 void SynthGetMetaClassFunctionDecl();
360 void SynthGetSuperClassFunctionDecl();
361 void SynthSelGetUidFunctionDecl();
362 void SynthSuperContructorFunctionDecl();
363
364 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Mike Stump1eb44332009-09-09 15:08:12 +0000365 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000366 StringRef funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000368 StringRef funcName, std::string Tag);
Steve Naroff01aec112009-12-06 21:14:13 +0000369 std::string SynthesizeBlockImpl(BlockExpr *CE,
370 std::string Tag, std::string Desc);
371 std::string SynthesizeBlockDescriptor(std::string DescTag,
372 std::string ImplTag,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000373 int i, StringRef funcName,
Steve Naroff01aec112009-12-06 21:14:13 +0000374 unsigned hasCopy);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +0000375 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff54055232008-10-27 17:20:55 +0000376 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000377 StringRef FunName);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000378 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
379 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
380 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs);
Mike Stump1eb44332009-09-09 15:08:12 +0000381
Fariborz Jahanian58457172011-12-05 18:43:13 +0000382 // Misc. helper routines.
Fariborz Jahaniandd8079c2011-12-05 19:50:04 +0000383 QualType getProtocolType();
Fariborz Jahanian58457172011-12-05 18:43:13 +0000384 void WarnAboutReturnGotoStmts(Stmt *S);
385 void HasReturnStmts(Stmt *S, bool &hasReturns);
386 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
387 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
388 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
389
390 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
Steve Naroff54055232008-10-27 17:20:55 +0000391 void CollectBlockDeclRefInfo(BlockExpr *Exp);
Steve Naroff54055232008-10-27 17:20:55 +0000392 void GetBlockDeclRefExprs(Stmt *S);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +0000393 void GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000394 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +0000395 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Steve Naroff54055232008-10-27 17:20:55 +0000397 // We avoid calling Type::isBlockPointerType(), since it operates on the
398 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000399 bool isTopLevelBlockPointerType(QualType T) {
400 return isa<BlockPointerType>(T);
401 }
Mike Stump1eb44332009-09-09 15:08:12 +0000402
Fariborz Jahanian4fc84532010-05-25 17:12:52 +0000403 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
404 /// to a function pointer type and upon success, returns true; false
405 /// otherwise.
406 bool convertBlockPointerToFunctionPointer(QualType &T) {
407 if (isTopLevelBlockPointerType(T)) {
408 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
409 T = Context->getPointerType(BPT->getPointeeType());
410 return true;
411 }
412 return false;
413 }
414
Fariborz Jahanian58457172011-12-05 18:43:13 +0000415 bool needToScanForQualifiers(QualType T);
416 QualType getSuperStructType();
417 QualType getConstantStringStructType();
418 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
419 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
420
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000421 void convertToUnqualifiedObjCType(QualType &T) {
422 if (T->isObjCQualifiedIdType())
423 T = Context->getObjCIdType();
424 else if (T->isObjCQualifiedClassType())
425 T = Context->getObjCClassType();
426 else if (T->isObjCObjectPointerType() &&
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +0000427 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
428 if (const ObjCObjectPointerType * OBJPT =
429 T->getAsObjCInterfacePointerType()) {
430 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
431 T = QualType(IFaceT, 0);
432 T = Context->getPointerType(T);
433 }
434 }
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +0000435 }
436
Steve Naroff54055232008-10-27 17:20:55 +0000437 // FIXME: This predicate seems like it would be useful to add to ASTContext.
438 bool isObjCType(QualType T) {
439 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
440 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000441
Steve Naroff54055232008-10-27 17:20:55 +0000442 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000443
Steve Naroff54055232008-10-27 17:20:55 +0000444 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
445 OCT == Context->getCanonicalType(Context->getObjCClassType()))
446 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000447
Ted Kremenek6217b802009-07-29 21:53:49 +0000448 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000449 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000450 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000451 return true;
452 }
453 return false;
454 }
455 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Fariborz Jahaniane985d012010-11-03 23:29:24 +0000456 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000457 void GetExtentOfArgList(const char *Name, const char *&LParen,
458 const char *&RParen);
Fariborz Jahanian58457172011-12-05 18:43:13 +0000459
Steve Naroff621edce2009-04-29 16:37:50 +0000460 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000461 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000462 if (From[i] == '"')
463 To += "\\\"";
464 else
465 To += From[i];
466 }
467 }
John McCalle23cf432010-12-14 08:05:40 +0000468
469 QualType getSimpleFunctionType(QualType result,
470 const QualType *args,
471 unsigned numArgs,
472 bool variadic = false) {
Fariborz Jahanian88914802011-09-09 20:35:22 +0000473 if (result == Context->getObjCInstanceType())
474 result = Context->getObjCIdType();
John McCalle23cf432010-12-14 08:05:40 +0000475 FunctionProtoType::ExtProtoInfo fpi;
476 fpi.Variadic = variadic;
477 return Context->getFunctionType(result, args, numArgs, fpi);
478 }
John McCall9d125032010-01-15 18:39:57 +0000479
Fariborz Jahanian58457172011-12-05 18:43:13 +0000480 // Helper function: create a CStyleCastExpr with trivial type source info.
481 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
482 CastKind Kind, Expr *E) {
483 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
484 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
485 SourceLocation(), SourceLocation());
486 }
487 };
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000488
489 class RewriteObjCFragileABI : public RewriteObjC {
490 public:
491
492 RewriteObjCFragileABI(std::string inFile, raw_ostream *OS,
493 DiagnosticsEngine &D, const LangOptions &LOpts,
494 bool silenceMacroWarn) : RewriteObjC(inFile, OS,
495 D, LOpts,
496 silenceMacroWarn) {}
497
498 ~RewriteObjCFragileABI() {}
499 virtual void Initialize(ASTContext &context);
500
501 // Rewriting metadata
502 template<typename MethodIterator>
503 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
504 MethodIterator MethodEnd,
505 bool IsInstanceMethod,
506 StringRef prefix,
507 StringRef ClassName,
508 std::string &Result);
509 virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
510 StringRef prefix,
511 StringRef ClassName,
512 std::string &Result);
513 virtual void RewriteObjCProtocolListMetaData(
514 const ObjCList<ObjCProtocolDecl> &Prots,
515 StringRef prefix, StringRef ClassName, std::string &Result);
516 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
517 std::string &Result);
518 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
519 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
520 std::string &Result);
521
522 // Rewriting ivar
523 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
524 std::string &Result);
525 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
526 };
Chris Lattner77cd2a02007-10-11 00:43:27 +0000527}
528
Mike Stump1eb44332009-09-09 15:08:12 +0000529void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
530 NamedDecl *D) {
John McCallf4c73712011-01-19 06:33:43 +0000531 if (const FunctionProtoType *fproto
Abramo Bagnara723df242010-12-14 22:11:44 +0000532 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Mike Stump1eb44332009-09-09 15:08:12 +0000533 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000534 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000535 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000536 // All the args are checked/rewritten. Don't call twice!
537 RewriteBlockPointerDecl(D);
538 break;
539 }
540 }
541}
542
543void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000544 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000545 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000546 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000547}
548
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000549static bool IsHeaderFile(const std::string &Filename) {
550 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000551
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000552 if (DotPos == std::string::npos) {
553 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000554 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000555 }
Mike Stump1eb44332009-09-09 15:08:12 +0000556
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000557 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
558 // C header: .h
559 // C++ header: .hh or .H;
560 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000561}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000562
Chris Lattner5f9e2722011-07-23 10:55:15 +0000563RewriteObjC::RewriteObjC(std::string inFile, raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000564 DiagnosticsEngine &D, const LangOptions &LOpts,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000565 bool silenceMacroWarn)
566 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
567 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000568 IsHeader = IsHeaderFile(inFile);
David Blaikied6471f72011-09-25 23:23:43 +0000569 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000570 "rewriting sub-expression within a macro (may not be correct)");
David Blaikied6471f72011-09-25 23:23:43 +0000571 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
572 DiagnosticsEngine::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000573 "rewriter doesn't support user-specified control flow semantics "
574 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000575}
576
Eli Friedmanbce831b2009-05-18 22:29:17 +0000577ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
Chris Lattner5f9e2722011-07-23 10:55:15 +0000578 raw_ostream* OS,
David Blaikied6471f72011-09-25 23:23:43 +0000579 DiagnosticsEngine &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000580 const LangOptions &LOpts,
581 bool SilenceRewriteMacroWarning) {
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000582 if (true /*!LOpts.ObjCNonFragileABI*/)
583 return new RewriteObjCFragileABI(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
584 else {
585 assert(false && "objective-C rewriter for nonfragile ABI = NYI");
586 return 0;
587 }
Chris Lattnere365c502007-11-30 22:25:36 +0000588}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000589
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +0000590void RewriteObjC::InitializeCommon(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000591 Context = &context;
592 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000593 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000594 MsgSendFunctionDecl = 0;
595 MsgSendSuperFunctionDecl = 0;
596 MsgSendStretFunctionDecl = 0;
597 MsgSendSuperStretFunctionDecl = 0;
598 MsgSendFpretFunctionDecl = 0;
599 GetClassFunctionDecl = 0;
600 GetMetaClassFunctionDecl = 0;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +0000601 GetSuperClassFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000602 SelGetUidFunctionDecl = 0;
603 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000604 ConstantStringClassReference = 0;
605 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000606 CurMethodDef = 0;
607 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000608 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000609 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000610 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000611 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000612 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000613 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000614 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000615 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000616 PropParentMap = 0;
617 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000618 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000619 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000620
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000621 // Get the ID and start/end of the main file.
622 MainFileID = SM->getMainFileID();
623 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
624 MainFileStart = MainBuf->getBufferStart();
625 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000626
Chris Lattner2c78b872009-04-14 23:22:57 +0000627 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000628}
629
Chris Lattnerf04da132007-10-24 17:06:59 +0000630//===----------------------------------------------------------------------===//
631// Top Level Driver Code
632//===----------------------------------------------------------------------===//
633
Chris Lattner682bf922009-03-29 16:50:03 +0000634void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Ted Kremeneke50187a2010-02-05 21:28:51 +0000635 if (Diags.hasErrorOccurred())
636 return;
637
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000638 // Two cases: either the decl could be in the main file, or it could be in a
639 // #included file. If the former, rewrite it now. If the later, check to see
640 // if we rewrote the #include/#import.
641 SourceLocation Loc = D->getLocation();
Chandler Carruth40278532011-07-25 16:49:02 +0000642 Loc = SM->getExpansionLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000643
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000644 // If this is for a builtin, ignore it.
645 if (Loc.isInvalid()) return;
646
Steve Naroffebf2b562007-10-23 23:50:29 +0000647 // Look for built-in declarations that we need to refer during the rewrite.
648 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000649 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000650 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000651 // declared in <Foundation/NSString.h>
Daniel Dunbar4087f272010-08-17 22:39:59 +0000652 if (FVD->getName() == "_NSConstantStringClassReference") {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000653 ConstantStringClassReference = FVD;
654 return;
655 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000656 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000657 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000658 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000659 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000660 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000661 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000662 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000663 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000664 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000665 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
666 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000667 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
668 DIEnd = LSD->decls_end();
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000669 DI != DIEnd; ) {
670 if (isa<ObjCClassDecl>((*DI))) {
671 SmallVector<Decl *, 8> DG;
672 Decl *D = (*DI);
673 SourceLocation Loc = D->getLocation();
674 while (DI != DIEnd &&
675 isa<ObjCClassDecl>(D) && D->getLocation() == Loc) {
676 DG.push_back(D);
677 ++DI;
678 D = (*DI);
679 }
680 RewriteForwardClassDecl(DG);
681 continue;
682 }
Chris Lattner682bf922009-03-29 16:50:03 +0000683 HandleTopLevelSingleDecl(*DI);
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000684 ++DI;
685 }
Steve Naroffebf2b562007-10-23 23:50:29 +0000686 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000687 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000688 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000689 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000690}
691
Chris Lattnerf04da132007-10-24 17:06:59 +0000692//===----------------------------------------------------------------------===//
693// Syntactic (non-AST) Rewriting Code
694//===----------------------------------------------------------------------===//
695
Steve Naroffb29b4272008-04-14 22:03:09 +0000696void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000697 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Chris Lattner5f9e2722011-07-23 10:55:15 +0000698 StringRef MainBuf = SM->getBufferData(MainFileID);
Benjamin Kramerf6ac97b2010-03-16 14:14:31 +0000699 const char *MainBufStart = MainBuf.begin();
700 const char *MainBufEnd = MainBuf.end();
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000701 size_t ImportLen = strlen("import");
Mike Stump1eb44332009-09-09 15:08:12 +0000702
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000703 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000704 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
705 if (*BufPtr == '#') {
706 if (++BufPtr == MainBufEnd)
707 return;
708 while (*BufPtr == ' ' || *BufPtr == '\t')
709 if (++BufPtr == MainBufEnd)
710 return;
711 if (!strncmp(BufPtr, "import", ImportLen)) {
712 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000713 SourceLocation ImportLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000714 LocStart.getLocWithOffset(BufPtr-MainBufStart);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000715 ReplaceText(ImportLoc, ImportLen, "include");
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000716 BufPtr += ImportLen;
717 }
718 }
719 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000720}
721
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000722static std::string getIvarAccessString(ObjCIvarDecl *OID) {
723 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000724 std::string S;
725 S = "((struct ";
726 S += ClassDecl->getIdentifier()->getName();
727 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000728 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000729 return S;
730}
731
Steve Naroffa0876e82008-12-02 17:36:43 +0000732void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
733 ObjCImplementationDecl *IMD,
734 ObjCCategoryImplDecl *CID) {
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000735 static bool objcGetPropertyDefined = false;
736 static bool objcSetPropertyDefined = false;
Steve Naroffd40910b2008-12-01 20:33:01 +0000737 SourceLocation startLoc = PID->getLocStart();
Benjamin Kramerd999b372010-02-14 14:14:16 +0000738 InsertText(startLoc, "// ");
Steve Naroffeb0646c2008-12-02 15:48:25 +0000739 const char *startBuf = SM->getCharacterData(startLoc);
740 assert((*startBuf == '@') && "bogus @synthesize location");
741 const char *semiBuf = strchr(startBuf, ';');
742 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000743 SourceLocation onePastSemiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000744 startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000745
746 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
747 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000748
Steve Naroffeb0646c2008-12-02 15:48:25 +0000749 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000750 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000751 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000752
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000753 if (!OID)
754 return;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000755 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000756 if (!PD->getGetterMethodDecl()->isDefined()) {
757 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
758 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
759 ObjCPropertyDecl::OBJC_PR_copy));
760 std::string Getr;
761 if (GenGetProperty && !objcGetPropertyDefined) {
762 objcGetPropertyDefined = true;
763 // FIXME. Is this attribute correct in all cases?
764 Getr = "\nextern \"C\" __declspec(dllimport) "
765 "id objc_getProperty(id, SEL, long, bool);\n";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000766 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000767 RewriteObjCMethodDecl(OID->getContainingInterface(),
768 PD->getGetterMethodDecl(), Getr);
769 Getr += "{ ";
770 // Synthesize an explicit cast to gain access to the ivar.
771 // See objc-act.c:objc_synthesize_new_getter() for details.
772 if (GenGetProperty) {
773 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
774 Getr += "typedef ";
775 const FunctionType *FPRetType = 0;
776 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
777 FPRetType);
778 Getr += " _TYPE";
779 if (FPRetType) {
780 Getr += ")"; // close the precedence "scope" for "*".
781
782 // Now, emit the argument types (if any).
783 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
784 Getr += "(";
785 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
786 if (i) Getr += ", ";
787 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +0000788 Context->getPrintingPolicy());
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000789 Getr += ParamStr;
790 }
791 if (FT->isVariadic()) {
792 if (FT->getNumArgs()) Getr += ", ";
793 Getr += "...";
794 }
795 Getr += ")";
796 } else
797 Getr += "()";
798 }
799 Getr += ";\n";
800 Getr += "return (_TYPE)";
801 Getr += "objc_getProperty(self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000802 RewriteIvarOffsetComputation(OID, Getr);
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000803 Getr += ", 1)";
804 }
805 else
806 Getr += "return " + getIvarAccessString(OID);
807 Getr += "; }";
808 InsertText(onePastSemiLoc, Getr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000809 }
Fariborz Jahanianec3683b2010-10-19 23:47:54 +0000810
811 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
Steve Naroffeb0646c2008-12-02 15:48:25 +0000812 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000813
Steve Naroffeb0646c2008-12-02 15:48:25 +0000814 // Generate the 'setter' function.
815 std::string Setr;
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000816 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
817 ObjCPropertyDecl::OBJC_PR_copy);
818 if (GenSetProperty && !objcSetPropertyDefined) {
819 objcSetPropertyDefined = true;
820 // FIXME. Is this attribute correct in all cases?
821 Setr = "\nextern \"C\" __declspec(dllimport) "
822 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
823 }
824
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000825 RewriteObjCMethodDecl(OID->getContainingInterface(),
826 PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000827 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000828 // Synthesize an explicit cast to initialize the ivar.
Steve Naroff15f081d2008-12-03 00:56:33 +0000829 // See objc-act.c:objc_synthesize_new_setter() for details.
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000830 if (GenSetProperty) {
831 Setr += "objc_setProperty (self, _cmd, ";
Fariborz Jahanian58457172011-12-05 18:43:13 +0000832 RewriteIvarOffsetComputation(OID, Setr);
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000833 Setr += ", (id)";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000834 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000835 Setr += ", ";
836 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
837 Setr += "0, ";
838 else
839 Setr += "1, ";
840 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
841 Setr += "1)";
842 else
843 Setr += "0)";
844 }
845 else {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +0000846 Setr += getIvarAccessString(OID) + " = ";
Daniel Dunbar4087f272010-08-17 22:39:59 +0000847 Setr += PD->getName();
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +0000848 }
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000849 Setr += "; }";
Benjamin Kramerd999b372010-02-14 14:14:16 +0000850 InsertText(onePastSemiLoc, Setr);
Steve Naroffd40910b2008-12-01 20:33:01 +0000851}
Chris Lattner8a12c272007-10-11 18:38:32 +0000852
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000853static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
854 std::string &typedefString) {
855 typedefString += "#ifndef _REWRITER_typedef_";
856 typedefString += ForwardDecl->getNameAsString();
857 typedefString += "\n";
858 typedefString += "#define _REWRITER_typedef_";
859 typedefString += ForwardDecl->getNameAsString();
860 typedefString += "\n";
861 typedefString += "typedef struct objc_object ";
862 typedefString += ForwardDecl->getNameAsString();
863 typedefString += ";\n#endif\n";
864}
865
866void RewriteObjC::RewriteForwardClassEpilogue(ObjCClassDecl *ClassDecl,
867 const std::string &typedefString) {
868 SourceLocation startLoc = ClassDecl->getLocation();
869 const char *startBuf = SM->getCharacterData(startLoc);
870 const char *semiPtr = strchr(startBuf, ';');
871 // Replace the @class with typedefs corresponding to the classes.
872 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
873}
874
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000875void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000876 std::string typedefString;
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000877 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
878 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(*I);
879 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
880 if (I == D.begin()) {
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000881 // Translate to typedef's that forward reference structs with the same name
882 // as the class. As a convenience, we include the original declaration
883 // as a comment.
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000884 typedefString += "// @class ";
885 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000886 typedefString += ";\n";
Fariborz Jahanian95ed7782011-08-27 20:50:59 +0000887 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000888 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Steve Naroff934f2762007-10-24 22:48:43 +0000889 }
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000890 DeclGroupRef::iterator I = D.begin();
891 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(*I), typedefString);
892}
Mike Stump1eb44332009-09-09 15:08:12 +0000893
Fariborz Jahaniana5e2b232011-08-29 22:21:46 +0000894void RewriteObjC::RewriteForwardClassDecl(
895 const llvm::SmallVector<Decl*, 8> &D) {
896 std::string typedefString;
897 for (unsigned i = 0; i < D.size(); i++) {
898 ObjCClassDecl *ClassDecl = cast<ObjCClassDecl>(D[i]);
899 ObjCInterfaceDecl *ForwardDecl = ClassDecl->getForwardInterfaceDecl();
900 if (i == 0) {
901 typedefString += "// @class ";
902 typedefString += ForwardDecl->getNameAsString();
903 typedefString += ";\n";
904 }
905 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
906 }
907 RewriteForwardClassEpilogue(cast<ObjCClassDecl>(D[0]), typedefString);
Chris Lattnerf04da132007-10-24 17:06:59 +0000908}
909
Steve Naroffb29b4272008-04-14 22:03:09 +0000910void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000911 // When method is a synthesized one, such as a getter/setter there is
912 // nothing to rewrite.
Fariborz Jahanian88914802011-09-09 20:35:22 +0000913 if (Method->isImplicit())
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000914 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000915 SourceLocation LocStart = Method->getLocStart();
916 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Chandler Carruth64211622011-07-25 21:09:52 +0000918 if (SM->getExpansionLineNumber(LocEnd) >
919 SM->getExpansionLineNumber(LocStart)) {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000920 InsertText(LocStart, "#if 0\n");
921 ReplaceText(LocEnd, 1, ";\n#endif\n");
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000922 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +0000923 InsertText(LocStart, "// ");
Steve Naroff423cb562007-10-30 13:30:57 +0000924 }
925}
926
Mike Stump1eb44332009-09-09 15:08:12 +0000927void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000928 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000929
Benjamin Kramerd999b372010-02-14 14:14:16 +0000930 ReplaceText(Loc, 0, "// ");
Steve Naroff6327e0d2009-01-11 01:06:09 +0000931 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000932}
933
Steve Naroffb29b4272008-04-14 22:03:09 +0000934void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000935 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000936
Steve Naroff423cb562007-10-30 13:30:57 +0000937 // FIXME: handle category headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000938 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000939
Fariborz Jahanian13751e32010-02-10 01:15:09 +0000940 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
941 E = CatDecl->prop_end(); I != E; ++I)
942 RewriteProperty(*I);
943
Mike Stump1eb44332009-09-09 15:08:12 +0000944 for (ObjCCategoryDecl::instmeth_iterator
945 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000946 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000947 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000948 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000949 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000950 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000951 RewriteMethodDeclaration(*I);
952
Steve Naroff423cb562007-10-30 13:30:57 +0000953 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000954 ReplaceText(CatDecl->getAtEndRange().getBegin(),
955 strlen("@end"), "/* @end */");
Steve Naroff423cb562007-10-30 13:30:57 +0000956}
957
Steve Naroffb29b4272008-04-14 22:03:09 +0000958void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000959 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000960
Steve Naroff752d6ef2007-10-30 16:42:30 +0000961 // FIXME: handle protocol headers that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +0000962 ReplaceText(LocStart, 0, "// ");
Mike Stump1eb44332009-09-09 15:08:12 +0000963
964 for (ObjCProtocolDecl::instmeth_iterator
965 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000966 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000967 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000968 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000969 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000970 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000971 RewriteMethodDeclaration(*I);
972
Fariborz Jahanian07acdf42010-09-24 18:36:58 +0000973 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
974 E = PDecl->prop_end(); I != E; ++I)
975 RewriteProperty(*I);
976
Steve Naroff752d6ef2007-10-30 16:42:30 +0000977 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000978 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +0000979 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
Steve Naroff8cc764c2007-11-14 15:03:57 +0000980
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000981 // Must comment out @optional/@required
982 const char *startBuf = SM->getCharacterData(LocStart);
983 const char *endBuf = SM->getCharacterData(LocEnd);
984 for (const char *p = startBuf; p < endBuf; p++) {
985 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000986 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000987 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
Mike Stump1eb44332009-09-09 15:08:12 +0000988
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000989 }
990 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +0000991 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +0000992 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
Mike Stump1eb44332009-09-09 15:08:12 +0000993
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000994 }
995 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000996}
997
Steve Naroffb29b4272008-04-14 22:03:09 +0000998void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000999 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +00001000 if (LocStart.isInvalid())
David Blaikieb219cfc2011-09-23 05:06:16 +00001001 llvm_unreachable("Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001002 // FIXME: handle forward protocol that are declared across multiple lines.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001003 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +00001004}
1005
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001006void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1007 const FunctionType *&FPRetType) {
1008 if (T->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +00001009 ResultStr += "id";
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001010 else if (T->isFunctionPointerType() ||
1011 T->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001012 // needs special handling, since pointer-to-functions have special
1013 // syntax (where a decaration models use).
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001014 QualType retType = T;
Steve Narofff4312dc2008-12-11 19:29:16 +00001015 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +00001016 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001017 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +00001018 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +00001019 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +00001020 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001021 ResultStr += FPRetType->getResultType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001022 Context->getPrintingPolicy());
Steve Narofff4312dc2008-12-11 19:29:16 +00001023 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +00001024 }
1025 } else
Douglas Gregor30c42402011-09-27 22:38:19 +00001026 ResultStr += T.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001027}
1028
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001029void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1030 ObjCMethodDecl *OMD,
Fariborz Jahanian7c63fdd2010-02-26 01:42:20 +00001031 std::string &ResultStr) {
1032 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1033 const FunctionType *FPRetType = 0;
1034 ResultStr += "\nstatic ";
1035 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001036 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +00001037
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001038 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001039 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001040
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001041 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001042 NameStr += "_I_";
1043 else
1044 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +00001045
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001046 NameStr += IDecl->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001047 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +00001048
1049 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +00001050 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001051 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001052 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001053 }
Mike Stump1eb44332009-09-09 15:08:12 +00001054 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +00001055 {
1056 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001057 int len = selString.size();
1058 for (int i = 0; i < len; i++)
1059 if (selString[i] == ':')
1060 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001061 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001062 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00001063 // Remember this name for metadata emission
1064 MethodInternalNames[OMD] = NameStr;
1065 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +00001066
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001067 // Rewrite arguments
1068 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +00001069
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +00001071 if (OMD->isInstanceMethod()) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001072 QualType selfTy = Context->getObjCInterfaceType(IDecl);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001073 selfTy = Context->getPointerType(selfTy);
Francois Pichet62ec1f22011-09-17 17:15:52 +00001074 if (!LangOpts.MicrosoftExt) {
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001075 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
Steve Naroff05b8c782008-03-12 00:25:36 +00001076 ResultStr += "struct ";
1077 }
1078 // When rewriting for Microsoft, explicitly omit the structure name.
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001079 ResultStr += IDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001080 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001081 }
1082 else
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001083 ResultStr += Context->getObjCClassType().getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001084 Context->getPrintingPolicy());
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 ResultStr += " self, ";
Douglas Gregor30c42402011-09-27 22:38:19 +00001087 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001088 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001089
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001090 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001091 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1092 E = OMD->param_end(); PI != E; ++PI) {
1093 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001094 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001095 if (PDecl->getType()->isObjCQualifiedIdType()) {
1096 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001097 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001098 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001099 std::string Name = PDecl->getNameAsString();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001100 QualType QT = PDecl->getType();
1101 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1102 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00001103 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00001104 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001105 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
Steve Naroff543409e2008-04-18 21:13:19 +00001106 ResultStr += Name;
1107 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001108 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001109 if (OMD->isVariadic())
1110 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001111 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001112
Steve Naroff76e429d2008-07-16 14:40:40 +00001113 if (FPRetType) {
1114 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001115
Steve Naroff76e429d2008-07-16 14:40:40 +00001116 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001117 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001118 ResultStr += "(";
1119 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1120 if (i) ResultStr += ", ";
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00001121 std::string ParamStr = FT->getArgType(i).getAsString(
Douglas Gregor30c42402011-09-27 22:38:19 +00001122 Context->getPrintingPolicy());
Steve Naroff76e429d2008-07-16 14:40:40 +00001123 ResultStr += ParamStr;
1124 }
1125 if (FT->isVariadic()) {
1126 if (FT->getNumArgs()) ResultStr += ", ";
1127 ResultStr += "...";
1128 }
1129 ResultStr += ")";
1130 } else {
1131 ResultStr += "()";
1132 }
1133 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001134}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001135void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001136 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1137 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001138
Fariborz Jahaniana1352162010-02-15 21:11:41 +00001139 InsertText(IMD ? IMD->getLocStart() : CID->getLocStart(), "// ");
Mike Stump1eb44332009-09-09 15:08:12 +00001140
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001141 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001142 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1143 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001144 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001145 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001146 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001147 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001148 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001149 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001150
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001151 const char *startBuf = SM->getCharacterData(LocStart);
1152 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001153 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001154 }
Mike Stump1eb44332009-09-09 15:08:12 +00001155
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001156 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001157 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1158 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001159 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001160 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001161 ObjCMethodDecl *OMD = *I;
Fariborz Jahanian2d8c1fd2010-10-16 00:29:27 +00001162 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001163 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001164 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001165
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001166 const char *startBuf = SM->getCharacterData(LocStart);
1167 const char *endBuf = SM->getCharacterData(LocEnd);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001168 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001169 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001170 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001171 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001172 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001173 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001174 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001175 }
1176
Benjamin Kramerd999b372010-02-14 14:14:16 +00001177 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001178}
1179
Steve Naroffb29b4272008-04-14 22:03:09 +00001180void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001181 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001182 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001183 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001184 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001185 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001186 ResultStr += "\n";
1187 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001188 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001189 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001190 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001191 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001192 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001193 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001194 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001195 }
Fariborz Jahanian58457172011-12-05 18:43:13 +00001196 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001197
1198 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001199 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001200 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001201 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001202 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001203 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001204 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001205 for (ObjCInterfaceDecl::classmeth_iterator
1206 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001207 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001208 RewriteMethodDeclaration(*I);
1209
Steve Naroff2feac5e2007-10-30 03:43:13 +00001210 // Lastly, comment out the @end.
Fariborz Jahanian73d1eb02010-05-24 17:22:38 +00001211 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1212 "/* @end */");
Steve Naroffbef11852007-10-26 20:53:56 +00001213}
1214
John McCall4b9c2d22011-11-06 09:01:30 +00001215Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1216 SourceRange OldRange = PseudoOp->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00001217
John McCall4b9c2d22011-11-06 09:01:30 +00001218 // We just magically know some things about the structure of this
1219 // expression.
1220 ObjCMessageExpr *OldMsg =
1221 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1222 PseudoOp->getNumSemanticExprs() - 1));
Mike Stump1eb44332009-09-09 15:08:12 +00001223
John McCall4b9c2d22011-11-06 09:01:30 +00001224 // Because the rewriter doesn't allow us to rewrite rewritten code,
1225 // we need to suppress rewriting the sub-statements.
1226 Expr *Base, *RHS;
1227 {
1228 DisableReplaceStmtScope S(*this);
1229
1230 // Rebuild the base expression if we have one.
1231 Base = 0;
1232 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1233 Base = OldMsg->getInstanceReceiver();
1234 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1235 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1236 }
1237
1238 // Rebuild the RHS.
1239 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1240 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1241 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1242 }
1243
1244 // TODO: avoid this copy.
1245 SmallVector<SourceLocation, 1> SelLocs;
1246 OldMsg->getSelectorLocs(SelLocs);
1247
1248 ObjCMessageExpr *NewMsg;
1249 switch (OldMsg->getReceiverKind()) {
1250 case ObjCMessageExpr::Class:
1251 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1252 OldMsg->getValueKind(),
1253 OldMsg->getLeftLoc(),
1254 OldMsg->getClassReceiverTypeInfo(),
1255 OldMsg->getSelector(),
1256 SelLocs,
1257 OldMsg->getMethodDecl(),
1258 RHS,
1259 OldMsg->getRightLoc());
1260 break;
1261
1262 case ObjCMessageExpr::Instance:
1263 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1264 OldMsg->getValueKind(),
1265 OldMsg->getLeftLoc(),
1266 Base,
1267 OldMsg->getSelector(),
1268 SelLocs,
1269 OldMsg->getMethodDecl(),
1270 RHS,
1271 OldMsg->getRightLoc());
1272 break;
1273
1274 case ObjCMessageExpr::SuperClass:
1275 case ObjCMessageExpr::SuperInstance:
1276 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1277 OldMsg->getValueKind(),
1278 OldMsg->getLeftLoc(),
1279 OldMsg->getSuperLoc(),
1280 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1281 OldMsg->getSuperType(),
1282 OldMsg->getSelector(),
1283 SelLocs,
1284 OldMsg->getMethodDecl(),
1285 RHS,
1286 OldMsg->getRightLoc());
1287 break;
1288 }
1289
1290 Stmt *Replacement = SynthMessageExpr(NewMsg);
1291 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1292 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001293}
1294
John McCall4b9c2d22011-11-06 09:01:30 +00001295Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1296 SourceRange OldRange = PseudoOp->getSourceRange();
1297
1298 // We just magically know some things about the structure of this
1299 // expression.
1300 ObjCMessageExpr *OldMsg =
1301 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1302
1303 // Because the rewriter doesn't allow us to rewrite rewritten code,
1304 // we need to suppress rewriting the sub-statements.
1305 Expr *Base = 0;
1306 {
1307 DisableReplaceStmtScope S(*this);
1308
1309 // Rebuild the base expression if we have one.
1310 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1311 Base = OldMsg->getInstanceReceiver();
1312 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1313 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
John McCall12f78a62010-12-02 01:19:52 +00001314 }
Fariborz Jahaniane0f83862010-10-20 16:07:20 +00001315 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001316
John McCall4b9c2d22011-11-06 09:01:30 +00001317 // Intentionally empty.
1318 SmallVector<SourceLocation, 1> SelLocs;
1319 SmallVector<Expr*, 1> Args;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001320
John McCall4b9c2d22011-11-06 09:01:30 +00001321 ObjCMessageExpr *NewMsg;
1322 switch (OldMsg->getReceiverKind()) {
1323 case ObjCMessageExpr::Class:
1324 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1325 OldMsg->getValueKind(),
1326 OldMsg->getLeftLoc(),
1327 OldMsg->getClassReceiverTypeInfo(),
1328 OldMsg->getSelector(),
1329 SelLocs,
1330 OldMsg->getMethodDecl(),
1331 Args,
1332 OldMsg->getRightLoc());
1333 break;
1334
1335 case ObjCMessageExpr::Instance:
1336 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1337 OldMsg->getValueKind(),
1338 OldMsg->getLeftLoc(),
1339 Base,
1340 OldMsg->getSelector(),
1341 SelLocs,
1342 OldMsg->getMethodDecl(),
1343 Args,
1344 OldMsg->getRightLoc());
1345 break;
1346
1347 case ObjCMessageExpr::SuperClass:
1348 case ObjCMessageExpr::SuperInstance:
1349 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1350 OldMsg->getValueKind(),
1351 OldMsg->getLeftLoc(),
1352 OldMsg->getSuperLoc(),
1353 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1354 OldMsg->getSuperType(),
1355 OldMsg->getSelector(),
1356 SelLocs,
1357 OldMsg->getMethodDecl(),
1358 Args,
1359 OldMsg->getRightLoc());
1360 break;
Steve Naroff8599e7a2008-12-08 16:43:47 +00001361 }
John McCall4b9c2d22011-11-06 09:01:30 +00001362
1363 Stmt *Replacement = SynthMessageExpr(NewMsg);
1364 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1365 return Replacement;
Steve Naroff15f081d2008-12-03 00:56:33 +00001366}
1367
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001368/// SynthCountByEnumWithState - To print:
1369/// ((unsigned int (*)
1370/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001371/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001372/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001373/// "countByEnumeratingWithState:objects:count:"),
1374/// &enumState,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001375/// (id *)__rw_items, (unsigned int)16)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001376///
Steve Naroffb29b4272008-04-14 22:03:09 +00001377void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001378 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1379 "id *, unsigned int))(void *)objc_msgSend)";
1380 buf += "\n\t\t";
1381 buf += "((id)l_collection,\n\t\t";
1382 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1383 buf += "\n\t\t";
1384 buf += "&enumState, "
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001385 "(id *)__rw_items, (unsigned int)16)";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001386}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001387
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001388/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1389/// statement to exit to its outer synthesized loop.
1390///
Steve Naroffb29b4272008-04-14 22:03:09 +00001391Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001392 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1393 return S;
1394 // replace break with goto __break_label
1395 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001396
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001397 SourceLocation startLoc = S->getLocStart();
1398 buf = "goto __break_label_";
1399 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001400 ReplaceText(startLoc, strlen("break"), buf);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001401
1402 return 0;
1403}
1404
1405/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1406/// statement to continue with its inner synthesized loop.
1407///
Steve Naroffb29b4272008-04-14 22:03:09 +00001408Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001409 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1410 return S;
1411 // replace continue with goto __continue_label
1412 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001413
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001414 SourceLocation startLoc = S->getLocStart();
1415 buf = "goto __continue_label_";
1416 buf += utostr(ObjCBcLabelNo.back());
Benjamin Kramerd999b372010-02-14 14:14:16 +00001417 ReplaceText(startLoc, strlen("continue"), buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001418
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001419 return 0;
1420}
1421
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001422/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001423/// It rewrites:
1424/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001425
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001426/// Into:
1427/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001428/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001429/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001430/// id __rw_items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001431/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001432/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001433/// objects:__rw_items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001434/// if (limit) {
1435/// unsigned long startMutations = *enumState.mutationsPtr;
1436/// do {
1437/// unsigned long counter = 0;
1438/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001439/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001440/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001441/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001442/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001443/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001444/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001445/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001446/// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001447/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001448/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001449/// }
1450/// else
1451/// elem = nil;
1452/// }
1453///
Steve Naroffb29b4272008-04-14 22:03:09 +00001454Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001455 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001456 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001457 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001458 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001459 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001460 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001461
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001462 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001463 const char *startBuf = SM->getCharacterData(startLoc);
Chris Lattner5f9e2722011-07-23 10:55:15 +00001464 StringRef elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001465 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001466 std::string buf;
1467 buf = "\n{\n\t";
1468 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1469 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001470 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001471 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001472 if (ElementType->isObjCQualifiedIdType() ||
1473 ElementType->isObjCQualifiedInterfaceType())
1474 // Simply use 'id' for all qualified types.
1475 elementTypeAsString = "id";
1476 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001477 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001478 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001479 buf += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00001480 elementName = D->getName();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 buf += elementName;
1482 buf += ";\n\t";
1483 }
Chris Lattner06767512008-04-08 05:52:18 +00001484 else {
1485 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Daniel Dunbar4087f272010-08-17 22:39:59 +00001486 elementName = DR->getDecl()->getName();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001487 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1488 if (VD->getType()->isObjCQualifiedIdType() ||
1489 VD->getType()->isObjCQualifiedInterfaceType())
1490 // Simply use 'id' for all qualified types.
1491 elementTypeAsString = "id";
1492 else
Douglas Gregor30c42402011-09-27 22:38:19 +00001493 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001494 }
Mike Stump1eb44332009-09-09 15:08:12 +00001495
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001496 // struct __objcFastEnumerationState enumState = { 0 };
1497 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001498 // id __rw_items[16];
1499 buf += "id __rw_items[16];\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001500 // id l_collection = (id)
1501 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001502 // Find start location of 'collection' the hard way!
1503 const char *startCollectionBuf = startBuf;
1504 startCollectionBuf += 3; // skip 'for'
1505 startCollectionBuf = strchr(startCollectionBuf, '(');
1506 startCollectionBuf++; // skip '('
1507 // find 'in' and skip it.
1508 while (*startCollectionBuf != ' ' ||
1509 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1510 (*(startCollectionBuf+3) != ' ' &&
1511 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1512 startCollectionBuf++;
1513 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001514
1515 // Replace: "for (type element in" with string constructed thus far.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001516 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001517 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001518 SourceLocation rightParenLoc = S->getRParenLoc();
1519 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001520 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001521 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001522
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001523 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001524 // objects:__rw_items count:16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001525 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001526 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001527 // ((unsigned int (*)
1528 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001529 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001530 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001531 // "countByEnumeratingWithState:objects:count:"),
1532 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001533 // (id *)__rw_items, (unsigned int)16);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001534 buf += "unsigned long limit =\n\t\t";
1535 SynthCountByEnumWithState(buf);
1536 buf += ";\n\t";
1537 /// if (limit) {
1538 /// unsigned long startMutations = *enumState.mutationsPtr;
1539 /// do {
1540 /// unsigned long counter = 0;
1541 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001542 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001543 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001544 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001545 buf += "if (limit) {\n\t";
1546 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1547 buf += "do {\n\t\t";
1548 buf += "unsigned long counter = 0;\n\t\t";
1549 buf += "do {\n\t\t\t";
1550 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1551 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1552 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001553 buf += " = (";
1554 buf += elementTypeAsString;
1555 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001556 // Replace ')' in for '(' type elem in collection ')' with all of these.
Benjamin Kramerd999b372010-02-14 14:14:16 +00001557 ReplaceText(lparenLoc, 1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001558
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001559 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001560 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001561 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian108fb142011-11-09 17:41:43 +00001562 /// objects:__rw_items count:16]);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001563 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001564 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001565 /// }
1566 /// else
1567 /// elem = nil;
1568 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001569 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001570 buf = ";\n\t";
1571 buf += "__continue_label_";
1572 buf += utostr(ObjCBcLabelNo.back());
1573 buf += ": ;";
1574 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001575 buf += "} while (counter < limit);\n\t";
1576 buf += "} while (limit = ";
1577 SynthCountByEnumWithState(buf);
1578 buf += ");\n\t";
1579 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001580 buf += " = ((";
1581 buf += elementTypeAsString;
1582 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001583 buf += "__break_label_";
1584 buf += utostr(ObjCBcLabelNo.back());
1585 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001586 buf += "}\n\t";
1587 buf += "else\n\t\t";
1588 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001589 buf += " = ((";
1590 buf += elementTypeAsString;
1591 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001592 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001593
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001594 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001595 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001596 if (isa<CompoundStmt>(S->getBody())) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001597 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001598 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001599 } else {
1600 /* Need to treat single statements specially. For example:
1601 *
1602 * for (A *a in b) if (stuff()) break;
1603 * for (A *a in b) xxxyy;
1604 *
1605 * The following code simply scans ahead to the semi to find the actual end.
1606 */
1607 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1608 const char *semiBuf = strchr(stmtBuf, ';');
1609 assert(semiBuf && "Can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001610 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001611 InsertText(endBodyLoc, buf);
Steve Naroff600e4e82008-07-21 18:26:02 +00001612 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001613 Stmts.pop_back();
1614 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001615 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001616}
1617
Mike Stump1eb44332009-09-09 15:08:12 +00001618/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001619/// This routine rewrites @synchronized(expr) stmt;
1620/// into:
1621/// objc_sync_enter(expr);
1622/// @try stmt @finally { objc_sync_exit(expr); }
1623///
Steve Naroffb29b4272008-04-14 22:03:09 +00001624Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001625 // Get the start location and compute the semi location.
1626 SourceLocation startLoc = S->getLocStart();
1627 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001628
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001629 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001630
1631 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001632 buf = "objc_sync_enter((id)";
1633 const char *lparenBuf = startBuf;
1634 while (*lparenBuf != '(') lparenBuf++;
Benjamin Kramerd999b372010-02-14 14:14:16 +00001635 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001636 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1637 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001638 // been rewritten! (which implies the SourceLocation's are invalid).
1639 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001640 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001641 while (*endBuf != ')') endBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001642 SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001643 buf = ");\n";
1644 // declare a new scope with two variables, _stack and _rethrow.
1645 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1646 buf += "int buf[18/*32-bit i386*/];\n";
1647 buf += "char *pointers[4];} _stack;\n";
1648 buf += "id volatile _rethrow = 0;\n";
1649 buf += "objc_exception_try_enter(&_stack);\n";
1650 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001651 ReplaceText(rparenLoc, 1, buf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001652 startLoc = S->getSynchBody()->getLocEnd();
1653 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001654
Steve Naroffc7089f12008-08-19 13:04:19 +00001655 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001656 SourceLocation lastCurlyLoc = startLoc;
1657 buf = "}\nelse {\n";
1658 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001659 buf += "}\n";
1660 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001661 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001662
1663 std::string syncBuf;
1664 syncBuf += " objc_sync_exit(";
John McCall1d9b3b22011-09-09 05:25:32 +00001665
1666 Expr *syncExpr = S->getSynchExpr();
1667 CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1668 ? CK_BitCast :
1669 syncExpr->getType()->isBlockPointerType()
1670 ? CK_BlockPointerToObjCPointerCast
1671 : CK_CPointerToObjCPointerCast;
1672 syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1673 CK, syncExpr);
Ted Kremeneka95d3752008-09-13 05:16:45 +00001674 std::string syncExprBufS;
1675 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001676 syncExpr->printPretty(syncExprBuf, *Context, 0,
1677 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001678 syncBuf += syncExprBuf.str();
1679 syncBuf += ");";
1680
1681 buf += syncBuf;
1682 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001683 buf += "}\n";
1684 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001685
Benjamin Kramerd999b372010-02-14 14:14:16 +00001686 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001687
1688 bool hasReturns = false;
1689 HasReturnStmts(S->getSynchBody(), hasReturns);
1690 if (hasReturns)
1691 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1692
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001693 return 0;
1694}
1695
Steve Naroffb85e77a2009-12-05 21:43:12 +00001696void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1697{
Steve Naroff8c565152008-12-05 17:03:39 +00001698 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001699 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff8c565152008-12-05 17:03:39 +00001700 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001701 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001702
Steve Naroffb85e77a2009-12-05 21:43:12 +00001703 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001704 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001705 TryFinallyContainsReturnDiag);
1706 }
1707 return;
1708}
1709
Steve Naroffb85e77a2009-12-05 21:43:12 +00001710void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1711{
1712 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001713 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001714 if (*CI)
1715 HasReturnStmts(*CI, hasReturns);
1716
1717 if (isa<ReturnStmt>(S))
1718 hasReturns = true;
1719 return;
1720}
1721
1722void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1723 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001724 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001725 if (*CI) {
1726 RewriteTryReturnStmts(*CI);
1727 }
1728 if (isa<ReturnStmt>(S)) {
1729 SourceLocation startLoc = S->getLocStart();
1730 const char *startBuf = SM->getCharacterData(startLoc);
1731
1732 const char *semiBuf = strchr(startBuf, ';');
1733 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001734 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001735
1736 std::string buf;
1737 buf = "{ objc_exception_try_exit(&_stack); return";
1738
Benjamin Kramerd999b372010-02-14 14:14:16 +00001739 ReplaceText(startLoc, 6, buf);
1740 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001741 }
1742 return;
1743}
1744
1745void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1746 // Perform a bottom up traversal of all children.
John McCall7502c1d2011-02-13 04:07:26 +00001747 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001748 if (*CI) {
1749 RewriteSyncReturnStmts(*CI, syncExitBuf);
1750 }
1751 if (isa<ReturnStmt>(S)) {
1752 SourceLocation startLoc = S->getLocStart();
1753 const char *startBuf = SM->getCharacterData(startLoc);
1754
1755 const char *semiBuf = strchr(startBuf, ';');
1756 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001757 SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001758
1759 std::string buf;
1760 buf = "{ objc_exception_try_exit(&_stack);";
1761 buf += syncExitBuf;
1762 buf += " return";
1763
Benjamin Kramerd999b372010-02-14 14:14:16 +00001764 ReplaceText(startLoc, 6, buf);
1765 InsertText(onePastSemiLoc, "}");
Steve Naroffb85e77a2009-12-05 21:43:12 +00001766 }
1767 return;
1768}
1769
Steve Naroffb29b4272008-04-14 22:03:09 +00001770Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001771 // Get the start location and compute the semi location.
1772 SourceLocation startLoc = S->getLocStart();
1773 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Steve Naroff75730982007-11-07 04:08:17 +00001775 assert((*startBuf == '@') && "bogus @try location");
1776
1777 std::string buf;
1778 // declare a new scope with two variables, _stack and _rethrow.
1779 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1780 buf += "int buf[18/*32-bit i386*/];\n";
1781 buf += "char *pointers[4];} _stack;\n";
1782 buf += "id volatile _rethrow = 0;\n";
1783 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001784 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001785
Benjamin Kramerd999b372010-02-14 14:14:16 +00001786 ReplaceText(startLoc, 4, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Steve Naroff75730982007-11-07 04:08:17 +00001788 startLoc = S->getTryBody()->getLocEnd();
1789 startBuf = SM->getCharacterData(startLoc);
1790
1791 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001792
Steve Naroff75730982007-11-07 04:08:17 +00001793 SourceLocation lastCurlyLoc = startLoc;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001794 if (S->getNumCatchStmts()) {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001795 startLoc = startLoc.getLocWithOffset(1);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001796 buf = " /* @catch begin */ else {\n";
1797 buf += " id _caught = objc_exception_extract(&_stack);\n";
1798 buf += " objc_exception_try_enter (&_stack);\n";
1799 buf += " if (_setjmp(_stack.buf))\n";
1800 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1801 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Benjamin Kramerd999b372010-02-14 14:14:16 +00001803 InsertText(startLoc, buf);
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001804 } else { /* no catch list */
1805 buf = "}\nelse {\n";
1806 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1807 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001808 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffc9ba1722008-07-16 15:31:30 +00001809 }
Steve Naroff75730982007-11-07 04:08:17 +00001810 Stmt *lastCatchBody = 0;
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001811 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1812 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Douglas Gregorc00d8e12010-04-26 16:46:50 +00001813 VarDecl *catchDecl = Catch->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001814
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001815 if (I == 0)
Steve Naroff75730982007-11-07 04:08:17 +00001816 buf = "if ("; // we are generating code for the first catch clause
1817 else
1818 buf = "else if (";
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001819 startLoc = Catch->getLocStart();
Steve Naroff75730982007-11-07 04:08:17 +00001820 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001821
Steve Naroff75730982007-11-07 04:08:17 +00001822 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001823
Steve Naroff75730982007-11-07 04:08:17 +00001824 const char *lParenLoc = strchr(startBuf, '(');
1825
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001826 if (Catch->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001827 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001828 lastCatchBody = Catch->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001829 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1830 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001831 assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
Chris Lattner06767512008-04-08 05:52:18 +00001832 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001833 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001834
Steve Naroffe12e6922008-02-01 20:02:07 +00001835 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001836 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001837 } else if (catchDecl) {
1838 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001839 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001840 buf += "1) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001841 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
John McCall506b57e2010-05-17 21:00:27 +00001842 } else if (const ObjCObjectPointerType *Ptr =
1843 t->getAs<ObjCObjectPointerType>()) {
1844 // Should be a pointer to a class.
1845 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1846 if (IDecl) {
Steve Naroff21867b12007-11-07 18:43:40 +00001847 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
John McCall506b57e2010-05-17 21:00:27 +00001848 buf += IDecl->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001849 buf += "\"), (struct objc_object *)_caught)) { ";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001850 ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
Steve Naroff75730982007-11-07 04:08:17 +00001851 }
1852 }
1853 // Now rewrite the body...
Douglas Gregor8f5e3dd2010-04-23 22:50:49 +00001854 lastCatchBody = Catch->getCatchBody();
1855 SourceLocation rParenLoc = Catch->getRParenLoc();
Steve Naroff75730982007-11-07 04:08:17 +00001856 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1857 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1858 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1859 assert((*rParenBuf == ')') && "bogus @catch paren location");
1860 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Mike Stump1eb44332009-09-09 15:08:12 +00001862 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001863 // declares the @catch parameter).
Benjamin Kramerd999b372010-02-14 14:14:16 +00001864 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
Steve Naroff7ba138a2009-03-03 19:52:17 +00001865 } else {
David Blaikieb219cfc2011-09-23 05:06:16 +00001866 llvm_unreachable("@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001867 }
Steve Naroff75730982007-11-07 04:08:17 +00001868 }
1869 // Complete the catch list...
1870 if (lastCatchBody) {
1871 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001872 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1873 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001874
Steve Naroff378f47a2008-09-11 15:29:03 +00001875 // Insert the last (implicit) else clause *before* the right curly brace.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001876 bodyLoc = bodyLoc.getLocWithOffset(-1);
Steve Naroff378f47a2008-09-11 15:29:03 +00001877 buf = "} /* last catch end */\n";
1878 buf += "else {\n";
1879 buf += " _rethrow = _caught;\n";
1880 buf += " objc_exception_try_exit(&_stack);\n";
1881 buf += "} } /* @catch end */\n";
1882 if (!S->getFinallyStmt())
1883 buf += "}\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001884 InsertText(bodyLoc, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001885
Steve Naroff75730982007-11-07 04:08:17 +00001886 // Set lastCurlyLoc
1887 lastCurlyLoc = lastCatchBody->getLocEnd();
1888 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001889 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001890 startLoc = finalStmt->getLocStart();
1891 startBuf = SM->getCharacterData(startLoc);
1892 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001893
Benjamin Kramerd999b372010-02-14 14:14:16 +00001894 ReplaceText(startLoc, 8, "/* @finally */");
Mike Stump1eb44332009-09-09 15:08:12 +00001895
Steve Naroff75730982007-11-07 04:08:17 +00001896 Stmt *body = finalStmt->getFinallyBody();
1897 SourceLocation startLoc = body->getLocStart();
1898 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001899 assert(*SM->getCharacterData(startLoc) == '{' &&
1900 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001901 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001902 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001903
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001904 startLoc = startLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001905 InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001906 endLoc = endLoc.getLocWithOffset(-1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001907 InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
Mike Stump1eb44332009-09-09 15:08:12 +00001908
Steve Naroff75730982007-11-07 04:08:17 +00001909 // Set lastCurlyLoc
1910 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Steve Naroff8c565152008-12-05 17:03:39 +00001912 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001913 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001914 } else { /* no finally clause - make sure we synthesize an implicit one */
1915 buf = "{ /* implicit finally clause */\n";
1916 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1917 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1918 buf += "}";
Benjamin Kramerd999b372010-02-14 14:14:16 +00001919 ReplaceText(lastCurlyLoc, 1, buf);
Steve Naroffb85e77a2009-12-05 21:43:12 +00001920
1921 // Now check for any return/continue/go statements within the @try.
1922 // The implicit finally clause won't called if the @try contains any
1923 // jump statements.
1924 bool hasReturns = false;
1925 HasReturnStmts(S->getTryBody(), hasReturns);
1926 if (hasReturns)
1927 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001928 }
1929 // Now emit the final closing curly brace...
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001930 lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001931 InsertText(lastCurlyLoc, " } /* @try scope end */\n");
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001932 return 0;
1933}
1934
Mike Stump1eb44332009-09-09 15:08:12 +00001935// This can't be done with ReplaceStmt(S, ThrowExpr), since
1936// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001937// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001938Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001939 // Get the start location and compute the semi location.
1940 SourceLocation startLoc = S->getLocStart();
1941 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Steve Naroff2bd03922007-11-07 15:32:26 +00001943 assert((*startBuf == '@') && "bogus @throw location");
1944
1945 std::string buf;
1946 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001947 if (S->getThrowExpr())
1948 buf = "objc_exception_throw(";
1949 else // add an implicit argument
1950 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001951
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001952 // handle "@ throw" correctly.
1953 const char *wBuf = strchr(startBuf, 'w');
1954 assert((*wBuf == 'w') && "@throw: can't find 'w'");
Benjamin Kramerd999b372010-02-14 14:14:16 +00001955 ReplaceText(startLoc, wBuf-startBuf+1, buf);
Mike Stump1eb44332009-09-09 15:08:12 +00001956
Steve Naroff2bd03922007-11-07 15:32:26 +00001957 const char *semiBuf = strchr(startBuf, ';');
1958 assert((*semiBuf == ';') && "@throw: can't find ';'");
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00001959 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00001960 ReplaceText(semiLoc, 1, ");");
Steve Naroff2bd03922007-11-07 15:32:26 +00001961 return 0;
1962}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001963
Steve Naroffb29b4272008-04-14 22:03:09 +00001964Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001965 // Create a new string expression.
1966 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001967 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001968 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Jay Foad65aa6882011-06-21 15:13:30 +00001969 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
Douglas Gregor5cee1192011-07-27 05:40:30 +00001970 StringLiteral::Ascii, false,
1971 StrType, SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001972 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001973
Chris Lattner07506182007-11-30 22:53:43 +00001974 // Replace this subexpr in the parent.
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001975 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001976 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001977}
1978
Steve Naroffb29b4272008-04-14 22:03:09 +00001979Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001980 if (!SelGetUidFunctionDecl)
1981 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001982 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1983 // Create a call to sel_registerName("selName").
Chris Lattner5f9e2722011-07-23 10:55:15 +00001984 SmallVector<Expr*, 8> SelExprs;
Steve Naroffb42f8412007-11-05 14:50:49 +00001985 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001986 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00001987 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00001988 StringLiteral::Ascii, false,
1989 argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001990 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1991 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001992 ReplaceStmt(Exp, SelExp);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00001993 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001994 return SelExp;
1995}
1996
Steve Naroffb29b4272008-04-14 22:03:09 +00001997CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00001998 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1999 SourceLocation EndLoc) {
Steve Naroffebf2b562007-10-23 23:50:29 +00002000 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00002001 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002002
Steve Naroffebf2b562007-10-23 23:50:29 +00002003 // Create a reference to the objc_msgSend() declaration.
John McCallf89e55a2010-11-18 06:31:45 +00002004 DeclRefExpr *DRE =
2005 new (Context) DeclRefExpr(FD, msgSendType, VK_LValue, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002006
Steve Naroffebf2b562007-10-23 23:50:29 +00002007 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00002008 QualType pToFunc = Context->getPointerType(msgSendType);
Anders Carlsson88465d32010-04-23 22:18:37 +00002009 ImplicitCastExpr *ICE =
John McCalla5bbc502010-11-15 09:46:46 +00002010 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
John McCall5baba9d2010-08-25 10:28:54 +00002011 DRE, 0, VK_RValue);
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCall183700f2009-09-21 23:43:11 +00002013 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00002014
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002015 CallExpr *Exp =
Douglas Gregor5291c3c2010-07-13 08:18:22 +00002016 new (Context) CallExpr(*Context, ICE, args, nargs,
John McCallf89e55a2010-11-18 06:31:45 +00002017 FT->getCallResultType(*Context),
2018 VK_RValue, EndLoc);
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002019 return Exp;
Steve Naroff934f2762007-10-24 22:48:43 +00002020}
2021
Steve Naroffd5255f52007-11-01 13:24:47 +00002022static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2023 const char *&startRef, const char *&endRef) {
2024 while (startBuf < endBuf) {
2025 if (*startBuf == '<')
2026 startRef = startBuf; // mark the start.
2027 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00002028 if (startRef && *startRef == '<') {
2029 endRef = startBuf; // mark the end.
2030 return true;
2031 }
2032 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002033 }
2034 startBuf++;
2035 }
2036 return false;
2037}
2038
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002039static void scanToNextArgument(const char *&argRef) {
2040 int angle = 0;
2041 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2042 if (*argRef == '<')
2043 angle++;
2044 else if (*argRef == '>')
2045 angle--;
2046 argRef++;
2047 }
2048 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2049}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002050
Steve Naroffb29b4272008-04-14 22:03:09 +00002051bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002052 if (T->isObjCQualifiedIdType())
2053 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002054 if (const PointerType *PT = T->getAs<PointerType>()) {
2055 if (PT->getPointeeType()->isObjCQualifiedIdType())
2056 return true;
2057 }
2058 if (T->isObjCObjectPointerType()) {
2059 T = T->getPointeeType();
2060 return T->isObjCQualifiedInterfaceType();
2061 }
Fariborz Jahanian24f9cab2010-09-30 20:41:32 +00002062 if (T->isArrayType()) {
2063 QualType ElemTy = Context->getBaseElementType(T);
2064 return needToScanForQualifiers(ElemTy);
2065 }
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002066 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002067}
2068
Steve Naroff4f95b752008-07-29 18:15:38 +00002069void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2070 QualType Type = E->getType();
2071 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002072 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002073
Steve Naroffcda658e2008-11-19 21:15:47 +00002074 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2075 Loc = ECE->getLParenLoc();
2076 EndLoc = ECE->getRParenLoc();
2077 } else {
2078 Loc = E->getLocStart();
2079 EndLoc = E->getLocEnd();
2080 }
2081 // This will defend against trying to rewrite synthesized expressions.
2082 if (Loc.isInvalid() || EndLoc.isInvalid())
2083 return;
2084
Steve Naroff4f95b752008-07-29 18:15:38 +00002085 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002086 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002087 const char *startRef = 0, *endRef = 0;
2088 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2089 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002090 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2091 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
Steve Naroff4f95b752008-07-29 18:15:38 +00002092 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002093 InsertText(LessLoc, "/*");
2094 InsertText(GreaterLoc, "*/");
Steve Naroff4f95b752008-07-29 18:15:38 +00002095 }
2096 }
2097}
2098
Steve Naroffb29b4272008-04-14 22:03:09 +00002099void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002100 SourceLocation Loc;
2101 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002102 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002103 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2104 Loc = VD->getLocation();
2105 Type = VD->getType();
2106 }
2107 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2108 Loc = FD->getLocation();
2109 // Check for ObjC 'id' and class types that have been adorned with protocol
2110 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002111 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002112 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002113 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002114 if (!proto)
2115 return;
2116 Type = proto->getResultType();
2117 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002118 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2119 Loc = FD->getLocation();
2120 Type = FD->getType();
2121 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002122 else
2123 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002124
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002125 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002126 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002127
Steve Naroffd5255f52007-11-01 13:24:47 +00002128 const char *endBuf = SM->getCharacterData(Loc);
2129 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002130 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002131 startBuf--; // scan backward (from the decl location) for return type.
2132 const char *startRef = 0, *endRef = 0;
2133 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2134 // Get the locations of the startRef, endRef.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002135 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2136 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002137 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002138 InsertText(LessLoc, "/*");
2139 InsertText(GreaterLoc, "*/");
Steve Naroff9165ad32007-10-31 04:38:33 +00002140 }
2141 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002142 if (!proto)
2143 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002144 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002145 const char *startBuf = SM->getCharacterData(Loc);
2146 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002147 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2148 if (needToScanForQualifiers(proto->getArgType(i))) {
2149 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002150
Steve Naroffd5255f52007-11-01 13:24:47 +00002151 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002152 // scan forward (from the decl location) for argument types.
2153 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002154 const char *startRef = 0, *endRef = 0;
2155 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2156 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002157 SourceLocation LessLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002158 Loc.getLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002159 SourceLocation GreaterLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00002160 Loc.getLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002161 // Comment out the protocol references.
Benjamin Kramerd999b372010-02-14 14:14:16 +00002162 InsertText(LessLoc, "/*");
2163 InsertText(GreaterLoc, "*/");
Steve Naroffd5255f52007-11-01 13:24:47 +00002164 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002165 startBuf = ++endBuf;
2166 }
2167 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002168 // If the function name is derived from a macro expansion, then the
2169 // argument buffer will not follow the name. Need to speak with Chris.
2170 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002171 startBuf++; // scan forward (from the decl location) for argument types.
2172 startBuf++;
2173 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002174 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002175}
2176
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002177void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2178 QualType QT = ND->getType();
2179 const Type* TypePtr = QT->getAs<Type>();
2180 if (!isa<TypeOfExprType>(TypePtr))
2181 return;
2182 while (isa<TypeOfExprType>(TypePtr)) {
2183 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2184 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2185 TypePtr = QT->getAs<Type>();
2186 }
2187 // FIXME. This will not work for multiple declarators; as in:
2188 // __typeof__(a) b,c,d;
Douglas Gregor30c42402011-09-27 22:38:19 +00002189 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002190 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2191 const char *startBuf = SM->getCharacterData(DeclLoc);
2192 if (ND->getInit()) {
2193 std::string Name(ND->getNameAsString());
2194 TypeAsString += " " + Name + " = ";
2195 Expr *E = ND->getInit();
2196 SourceLocation startLoc;
2197 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2198 startLoc = ECE->getLParenLoc();
2199 else
2200 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00002201 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002202 const char *endBuf = SM->getCharacterData(startLoc);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002203 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002204 }
2205 else {
2206 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00002207 X = SM->getExpansionLoc(X);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002208 const char *endBuf = SM->getCharacterData(X);
Benjamin Kramerd999b372010-02-14 14:14:16 +00002209 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00002210 }
2211}
2212
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002213// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002214void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002215 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002216 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002217 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002218 QualType getFuncType =
2219 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002220 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002221 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002222 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002223 SelGetUidIdent, getFuncType, 0,
John McCalld931b082010-08-26 03:08:43 +00002224 SC_Extern,
2225 SC_None, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002226}
2227
Steve Naroffb29b4272008-04-14 22:03:09 +00002228void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002229 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002230 if (FD->getIdentifier() &&
Daniel Dunbar4087f272010-08-17 22:39:59 +00002231 FD->getName() == "sel_registerName") {
Steve Naroff09b266e2007-10-30 23:14:51 +00002232 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002233 return;
2234 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002235 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002236}
2237
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002238void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
Douglas Gregor30c42402011-09-27 22:38:19 +00002239 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002240 const char *argPtr = TypeString.c_str();
2241 if (!strchr(argPtr, '^')) {
2242 Str += TypeString;
2243 return;
2244 }
2245 while (*argPtr) {
2246 Str += (*argPtr == '^' ? '*' : *argPtr);
2247 argPtr++;
2248 }
2249}
2250
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002251// FIXME. Consolidate this routine with RewriteBlockPointerType.
Daniel Dunbarfa297fb2010-06-30 19:16:53 +00002252void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2253 ValueDecl *VD) {
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002254 QualType Type = VD->getType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002255 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00002256 const char *argPtr = TypeString.c_str();
2257 int paren = 0;
2258 while (*argPtr) {
2259 switch (*argPtr) {
2260 case '(':
2261 Str += *argPtr;
2262 paren++;
2263 break;
2264 case ')':
2265 Str += *argPtr;
2266 paren--;
2267 break;
2268 case '^':
2269 Str += '*';
2270 if (paren == 1)
2271 Str += VD->getNameAsString();
2272 break;
2273 default:
2274 Str += *argPtr;
2275 break;
2276 }
2277 argPtr++;
2278 }
2279}
2280
2281
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002282void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2283 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2284 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2285 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2286 if (!proto)
2287 return;
2288 QualType Type = proto->getResultType();
Douglas Gregor30c42402011-09-27 22:38:19 +00002289 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002290 FdStr += " ";
Daniel Dunbar4087f272010-08-17 22:39:59 +00002291 FdStr += FD->getName();
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002292 FdStr += "(";
2293 unsigned numArgs = proto->getNumArgs();
2294 for (unsigned i = 0; i < numArgs; i++) {
2295 QualType ArgType = proto->getArgType(i);
Fariborz Jahanian52b2e1e2010-02-12 17:52:31 +00002296 RewriteBlockPointerType(FdStr, ArgType);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002297 if (i+1 < numArgs)
2298 FdStr += ", ";
2299 }
2300 FdStr += ");\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00002301 InsertText(FunLocStart, FdStr);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002302 CurFunctionDeclToDeclareForBlock = 0;
2303}
2304
Steve Naroffc0a123c2008-03-11 17:37:02 +00002305// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002306void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002307 if (SuperContructorFunctionDecl)
2308 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002309 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002310 SmallVector<QualType, 16> ArgTys;
Steve Naroffc0a123c2008-03-11 17:37:02 +00002311 QualType argT = Context->getObjCIdType();
2312 assert(!argT.isNull() && "Can't find 'id' type");
2313 ArgTys.push_back(argT);
2314 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2316 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002317 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002318 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002319 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002320 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002321 SC_Extern,
2322 SC_None, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002323}
2324
Steve Naroff09b266e2007-10-30 23:14:51 +00002325// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002326void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002327 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002328 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002329 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002330 assert(!argT.isNull() && "Can't find 'id' type");
2331 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002332 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002333 assert(!argT.isNull() && "Can't find 'SEL' type");
2334 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002335 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2336 &ArgTys[0], ArgTys.size(),
2337 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002338 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002339 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002340 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002341 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002342 SC_Extern,
2343 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002344}
2345
Steve Naroff874e2322007-11-15 10:28:18 +00002346// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002347void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002348 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002349 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002350 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002351 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002352 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002353 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2354 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2355 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002356 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002357 assert(!argT.isNull() && "Can't find 'SEL' type");
2358 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002359 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2360 &ArgTys[0], ArgTys.size(),
2361 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002362 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002363 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002364 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002365 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002366 SC_Extern,
2367 SC_None, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002368}
2369
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002370// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002371void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002372 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002373 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002374 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002375 assert(!argT.isNull() && "Can't find 'id' type");
2376 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002377 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002378 assert(!argT.isNull() && "Can't find 'SEL' type");
2379 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002380 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002381 &ArgTys[0], ArgTys.size(),
2382 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002383 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002384 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002385 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002386 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002387 SC_Extern,
2388 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002389}
2390
Mike Stump1eb44332009-09-09 15:08:12 +00002391// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002392// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002393void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002394 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002395 &Context->Idents.get("objc_msgSendSuper_stret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002396 SmallVector<QualType, 16> ArgTys;
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002397 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002398 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002399 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002400 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2401 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2402 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002403 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002404 assert(!argT.isNull() && "Can't find 'SEL' type");
2405 ArgTys.push_back(argT);
Fariborz Jahanian336c8f72011-10-11 23:02:37 +00002406 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
John McCalle23cf432010-12-14 08:05:40 +00002407 &ArgTys[0], ArgTys.size(),
2408 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002409 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002410 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002411 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002412 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002413 SC_Extern,
2414 SC_None, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002415}
2416
Steve Naroff1284db82008-05-08 22:02:18 +00002417// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002418void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002419 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002420 SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002421 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002422 assert(!argT.isNull() && "Can't find 'id' type");
2423 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002424 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002425 assert(!argT.isNull() && "Can't find 'SEL' type");
2426 ArgTys.push_back(argT);
John McCalle23cf432010-12-14 08:05:40 +00002427 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2428 &ArgTys[0], ArgTys.size(),
2429 true /*isVariadic*/);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002430 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002431 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002432 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002433 msgSendIdent, msgSendType, 0,
John McCalld931b082010-08-26 03:08:43 +00002434 SC_Extern,
2435 SC_None, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002436}
2437
Steve Naroff09b266e2007-10-30 23:14:51 +00002438// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002439void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002440 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002441 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002442 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002443 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2444 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002445 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002446 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002447 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002448 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002449 SC_Extern,
2450 SC_None, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002451}
2452
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002453// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2454void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2455 IdentifierInfo *getSuperClassIdent =
2456 &Context->Idents.get("class_getSuperclass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002457 SmallVector<QualType, 16> ArgTys;
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002458 ArgTys.push_back(Context->getObjCClassType());
John McCalle23cf432010-12-14 08:05:40 +00002459 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2460 &ArgTys[0], ArgTys.size());
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002461 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002462 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002463 SourceLocation(),
Douglas Gregor16573fa2010-04-19 22:54:31 +00002464 getSuperClassIdent,
2465 getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002466 SC_Extern,
2467 SC_None,
Douglas Gregor16573fa2010-04-19 22:54:31 +00002468 false);
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002469}
2470
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002471// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002472void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002473 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
Chris Lattner5f9e2722011-07-23 10:55:15 +00002474 SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002475 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
John McCalle23cf432010-12-14 08:05:40 +00002476 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2477 &ArgTys[0], ArgTys.size());
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002478 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002479 SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002480 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002481 getClassIdent, getClassType, 0,
John McCalld931b082010-08-26 03:08:43 +00002482 SC_Extern,
2483 SC_None, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002484}
2485
Steve Naroffb29b4272008-04-14 22:03:09 +00002486Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002487 QualType strType = getConstantStringStructType();
2488
2489 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002490
2491 std::string tmpName = InFileName;
2492 unsigned i;
2493 for (i=0; i < tmpName.length(); i++) {
2494 char c = tmpName.at(i);
2495 // replace any non alphanumeric characters with '_'.
2496 if (!isalpha(c) && (c < '0' || c > '9'))
2497 tmpName[i] = '_';
2498 }
2499 S += tmpName;
2500 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002501 S += utostr(NumObjCStringLiterals++);
2502
Steve Naroffba92b2e2008-03-27 22:29:16 +00002503 Preamble += "static __NSConstantStringImpl " + S;
2504 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2505 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002506 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002507 std::string prettyBufS;
2508 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002509 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2510 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002511 Preamble += prettyBuf.str();
2512 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002513 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002514
2515 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002516 SourceLocation(), &Context->Idents.get(S),
2517 strType, 0, SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00002518 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, VK_LValue,
2519 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00002520 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002521 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002522 VK_RValue, OK_Ordinary,
2523 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002524 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002525 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002526 CK_CPointerToObjCPointerCast, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002527 ReplaceStmt(Exp, cast);
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002528 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002529 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002530}
2531
Steve Naroff874e2322007-11-15 10:28:18 +00002532// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002533QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002534 if (!SuperStructDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002535 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002536 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002537 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002538 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002539
Steve Naroff874e2322007-11-15 10:28:18 +00002540 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002541 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002542 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002543 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002544
Steve Naroff874e2322007-11-15 10:28:18 +00002545 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002546 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002547 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002548 SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00002549 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002550 FieldTypes[i], 0,
2551 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002552 /*Mutable=*/false,
2553 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002554 }
Mike Stump1eb44332009-09-09 15:08:12 +00002555
Douglas Gregor838db382010-02-11 01:19:42 +00002556 SuperStructDecl->completeDefinition();
Steve Naroff874e2322007-11-15 10:28:18 +00002557 }
2558 return Context->getTagDeclType(SuperStructDecl);
2559}
2560
Steve Naroffb29b4272008-04-14 22:03:09 +00002561QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002562 if (!ConstantStringDecl) {
Abramo Bagnara465d41b2010-05-11 21:36:43 +00002563 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00002564 SourceLocation(), SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002565 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002566 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002567
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002568 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002569 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002570 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002571 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002572 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002573 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002574 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002575 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002576
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002577 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002578 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002579 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2580 ConstantStringDecl,
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00002581 SourceLocation(),
Douglas Gregor44b43212008-12-11 16:49:14 +00002582 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002583 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002584 /*BitWidth=*/0,
Richard Smith7a614d82011-06-11 17:19:42 +00002585 /*Mutable=*/true,
2586 /*HasInit=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002587 }
2588
Douglas Gregor838db382010-02-11 01:19:42 +00002589 ConstantStringDecl->completeDefinition();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002590 }
2591 return Context->getTagDeclType(ConstantStringDecl);
2592}
2593
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002594Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2595 SourceLocation StartLoc,
2596 SourceLocation EndLoc) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002597 if (!SelGetUidFunctionDecl)
2598 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002599 if (!MsgSendFunctionDecl)
2600 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002601 if (!MsgSendSuperFunctionDecl)
2602 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002603 if (!MsgSendStretFunctionDecl)
2604 SynthMsgSendStretFunctionDecl();
2605 if (!MsgSendSuperStretFunctionDecl)
2606 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002607 if (!MsgSendFpretFunctionDecl)
2608 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002609 if (!GetClassFunctionDecl)
2610 SynthGetClassFunctionDecl();
Fariborz Jahaniand314e9e2010-03-10 21:17:41 +00002611 if (!GetSuperClassFunctionDecl)
2612 SynthGetSuperClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002613 if (!GetMetaClassFunctionDecl)
2614 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002615
Steve Naroff874e2322007-11-15 10:28:18 +00002616 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002617 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2618 // May need to use objc_msgSend_stret() as well.
2619 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002620 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2621 QualType resultType = mDecl->getResultType();
Douglas Gregorfb87b892010-04-26 21:31:17 +00002622 if (resultType->isRecordType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002623 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002624 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002625 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002626 }
Mike Stump1eb44332009-09-09 15:08:12 +00002627
Steve Naroff934f2762007-10-24 22:48:43 +00002628 // Synthesize a call to objc_msgSend().
Chris Lattner5f9e2722011-07-23 10:55:15 +00002629 SmallVector<Expr*, 8> MsgExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002630 switch (Exp->getReceiverKind()) {
2631 case ObjCMessageExpr::SuperClass: {
2632 MsgSendFlavor = MsgSendSuperFunctionDecl;
2633 if (MsgSendStretFlavor)
2634 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2635 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002636
Douglas Gregor04badcf2010-04-21 00:45:42 +00002637 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00002638
Chris Lattner5f9e2722011-07-23 10:55:15 +00002639 SmallVector<Expr*, 4> InitExprs;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002640
Douglas Gregor04badcf2010-04-21 00:45:42 +00002641 // set the receiver to self, the first argument to all methods.
2642 InitExprs.push_back(
2643 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002644 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002645 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002646 Context->getObjCIdType(),
2647 VK_RValue,
2648 SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002649 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Douglas Gregor04badcf2010-04-21 00:45:42 +00002651 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002652 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002653 QualType argType = Context->getPointerType(Context->CharTy);
2654 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002655 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002656 StringLiteral::Ascii, false,
2657 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002658 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2659 &ClsExprs[0],
2660 ClsExprs.size(),
2661 StartLoc,
2662 EndLoc);
2663 // (Class)objc_getClass("CurrentClass")
2664 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2665 Context->getObjCClassType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002666 CK_CPointerToObjCPointerCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002667 ClsExprs.clear();
2668 ClsExprs.push_back(ArgExpr);
2669 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2670 &ClsExprs[0], ClsExprs.size(),
2671 StartLoc, EndLoc);
2672
2673 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2674 // To turn off a warning, type-cast to 'id'
2675 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2676 NoTypeInfoCStyleCastExpr(Context,
2677 Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002678 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002679 // struct objc_super
2680 QualType superType = getSuperStructType();
2681 Expr *SuperRep;
Steve Naroff621edce2009-04-29 16:37:50 +00002682
Francois Pichet62ec1f22011-09-17 17:15:52 +00002683 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002684 SynthSuperContructorFunctionDecl();
2685 // Simulate a contructor call...
2686 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002687 superType, VK_LValue,
2688 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002689 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2690 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002691 superType, VK_LValue,
2692 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002693 // The code for super is a little tricky to prevent collision with
2694 // the structure definition in the header. The rewriter has it's own
2695 // internal definition (__rw_objc_super) that is uses. This is why
2696 // we need the cast below. For example:
2697 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2698 //
John McCall2de56d12010-08-25 11:45:40 +00002699 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002700 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002701 VK_RValue, OK_Ordinary,
2702 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002703 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2704 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002705 CK_BitCast, SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002706 } else {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002707 // (struct objc_super) { <exprs from above> }
2708 InitListExpr *ILE =
2709 new (Context) InitListExpr(*Context, SourceLocation(),
2710 &InitExprs[0], InitExprs.size(),
2711 SourceLocation());
2712 TypeSourceInfo *superTInfo
2713 = Context->getTrivialTypeSourceInfo(superType);
2714 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002715 superType, VK_LValue,
2716 ILE, false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002717 // struct objc_super *
John McCall2de56d12010-08-25 11:45:40 +00002718 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002719 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002720 VK_RValue, OK_Ordinary,
2721 SourceLocation());
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002722 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002723 MsgExprs.push_back(SuperRep);
2724 break;
Steve Naroff6568d4d2007-11-14 23:54:14 +00002725 }
Douglas Gregor04badcf2010-04-21 00:45:42 +00002726
2727 case ObjCMessageExpr::Class: {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002728 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002729 QualType argType = Context->getPointerType(Context->CharTy);
2730 ObjCInterfaceDecl *Class
John McCall506b57e2010-05-17 21:00:27 +00002731 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
Douglas Gregor04badcf2010-04-21 00:45:42 +00002732 IdentifierInfo *clsName = Class->getIdentifier();
2733 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002734 clsName->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002735 StringLiteral::Ascii, false,
Anders Carlsson3e2193c2011-04-14 00:40:03 +00002736 argType, SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002737 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2738 &ClsExprs[0],
2739 ClsExprs.size(),
2740 StartLoc, EndLoc);
2741 MsgExprs.push_back(Cls);
2742 break;
2743 }
2744
2745 case ObjCMessageExpr::SuperInstance:{
2746 MsgSendFlavor = MsgSendSuperFunctionDecl;
2747 if (MsgSendStretFlavor)
2748 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2749 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2750 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
Chris Lattner5f9e2722011-07-23 10:55:15 +00002751 SmallVector<Expr*, 4> InitExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002752
2753 InitExprs.push_back(
2754 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002755 CK_BitCast,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002756 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf89e55a2010-11-18 06:31:45 +00002757 Context->getObjCIdType(),
2758 VK_RValue, SourceLocation()))
Douglas Gregor04badcf2010-04-21 00:45:42 +00002759 ); // set the 'receiver'.
2760
2761 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
Chris Lattner5f9e2722011-07-23 10:55:15 +00002762 SmallVector<Expr*, 8> ClsExprs;
Douglas Gregor04badcf2010-04-21 00:45:42 +00002763 QualType argType = Context->getPointerType(Context->CharTy);
2764 ClsExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002765 ClassDecl->getIdentifier()->getName(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002766 StringLiteral::Ascii, false, argType,
2767 SourceLocation()));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002768 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2769 &ClsExprs[0],
2770 ClsExprs.size(),
2771 StartLoc, EndLoc);
2772 // (Class)objc_getClass("CurrentClass")
2773 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2774 Context->getObjCClassType(),
John McCalla5bbc502010-11-15 09:46:46 +00002775 CK_BitCast, Cls);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002776 ClsExprs.clear();
2777 ClsExprs.push_back(ArgExpr);
2778 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2779 &ClsExprs[0], ClsExprs.size(),
2780 StartLoc, EndLoc);
2781
2782 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2783 // To turn off a warning, type-cast to 'id'
2784 InitExprs.push_back(
2785 // set 'super class', using class_getSuperclass().
2786 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCalla5bbc502010-11-15 09:46:46 +00002787 CK_BitCast, Cls));
Douglas Gregor04badcf2010-04-21 00:45:42 +00002788 // struct objc_super
2789 QualType superType = getSuperStructType();
2790 Expr *SuperRep;
2791
Francois Pichet62ec1f22011-09-17 17:15:52 +00002792 if (LangOpts.MicrosoftExt) {
Douglas Gregor04badcf2010-04-21 00:45:42 +00002793 SynthSuperContructorFunctionDecl();
2794 // Simulate a contructor call...
2795 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf89e55a2010-11-18 06:31:45 +00002796 superType, VK_LValue,
2797 SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002798 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2799 InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002800 superType, VK_LValue, SourceLocation());
Douglas Gregor04badcf2010-04-21 00:45:42 +00002801 // The code for super is a little tricky to prevent collision with
2802 // the structure definition in the header. The rewriter has it's own
2803 // internal definition (__rw_objc_super) that is uses. This is why
2804 // we need the cast below. For example:
2805 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2806 //
John McCall2de56d12010-08-25 11:45:40 +00002807 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002808 Context->getPointerType(SuperRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00002809 VK_RValue, OK_Ordinary,
Douglas Gregor04badcf2010-04-21 00:45:42 +00002810 SourceLocation());
2811 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2812 Context->getPointerType(superType),
John McCalla5bbc502010-11-15 09:46:46 +00002813 CK_BitCast, SuperRep);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002814 } else {
2815 // (struct objc_super) { <exprs from above> }
2816 InitListExpr *ILE =
2817 new (Context) InitListExpr(*Context, SourceLocation(),
2818 &InitExprs[0], InitExprs.size(),
2819 SourceLocation());
2820 TypeSourceInfo *superTInfo
2821 = Context->getTrivialTypeSourceInfo(superType);
2822 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
John McCallf89e55a2010-11-18 06:31:45 +00002823 superType, VK_RValue, ILE,
2824 false);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002825 }
2826 MsgExprs.push_back(SuperRep);
2827 break;
2828 }
2829
2830 case ObjCMessageExpr::Instance: {
2831 // Remove all type-casts because it may contain objc-style types; e.g.
2832 // Foo<Proto> *.
2833 Expr *recExpr = Exp->getInstanceReceiver();
2834 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2835 recExpr = CE->getSubExpr();
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002836 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2837 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2838 ? CK_BlockPointerToObjCPointerCast
2839 : CK_CPointerToObjCPointerCast;
2840
Douglas Gregor04badcf2010-04-21 00:45:42 +00002841 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
Fariborz Jahanianbaac1ea2011-10-07 17:17:45 +00002842 CK, recExpr);
Douglas Gregor04badcf2010-04-21 00:45:42 +00002843 MsgExprs.push_back(recExpr);
2844 break;
2845 }
2846 }
2847
Steve Naroffbeaf2992007-11-03 11:27:19 +00002848 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002849 SmallVector<Expr*, 8> SelExprs;
Steve Naroff934f2762007-10-24 22:48:43 +00002850 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002851 SelExprs.push_back(StringLiteral::Create(*Context,
Jay Foad65aa6882011-06-21 15:13:30 +00002852 Exp->getSelector().getAsString(),
Douglas Gregor5cee1192011-07-27 05:40:30 +00002853 StringLiteral::Ascii, false,
2854 argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002855 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002856 &SelExprs[0], SelExprs.size(),
2857 StartLoc,
2858 EndLoc);
Steve Naroff934f2762007-10-24 22:48:43 +00002859 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002860
Steve Naroff934f2762007-10-24 22:48:43 +00002861 // Now push any user supplied arguments.
2862 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002863 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002864 // Make all implicit casts explicit...ICE comes in handy:-)
2865 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2866 // Reuse the ICE type, it is exactly what the doctor ordered.
Fariborz Jahaniandff3f012011-02-26 01:31:36 +00002867 QualType type = ICE->getType();
2868 if (needToScanForQualifiers(type))
2869 type = Context->getObjCIdType();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00002870 // Make sure we convert "type (^)(...)" to "type (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002871 (void)convertBlockPointerToFunctionPointer(type);
Fariborz Jahanian1a38b462011-08-04 23:58:03 +00002872 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
John McCall1d9b3b22011-09-09 05:25:32 +00002873 CastKind CK;
2874 if (SubExpr->getType()->isIntegralType(*Context) &&
2875 type->isBooleanType()) {
2876 CK = CK_IntegralToBoolean;
2877 } else if (type->isObjCObjectPointerType()) {
2878 if (SubExpr->getType()->isBlockPointerType()) {
2879 CK = CK_BlockPointerToObjCPointerCast;
2880 } else if (SubExpr->getType()->isPointerType()) {
2881 CK = CK_CPointerToObjCPointerCast;
2882 } else {
2883 CK = CK_BitCast;
2884 }
2885 } else {
2886 CK = CK_BitCast;
2887 }
2888
2889 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002890 }
2891 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002892 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002893 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002894 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002895 userExpr = CE->getSubExpr();
John McCall1d9b3b22011-09-09 05:25:32 +00002896 CastKind CK;
2897 if (userExpr->getType()->isIntegralType(*Context)) {
2898 CK = CK_IntegralToPointer;
2899 } else if (userExpr->getType()->isBlockPointerType()) {
2900 CK = CK_BlockPointerToObjCPointerCast;
2901 } else if (userExpr->getType()->isPointerType()) {
2902 CK = CK_CPointerToObjCPointerCast;
2903 } else {
2904 CK = CK_BitCast;
2905 }
John McCall9d125032010-01-15 18:39:57 +00002906 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
John McCall1d9b3b22011-09-09 05:25:32 +00002907 CK, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002908 }
Mike Stump1eb44332009-09-09 15:08:12 +00002909 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002910 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002911 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2912 // out the argument in the original expression (since we aren't deleting
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00002913 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002914 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002915 }
Steve Naroffab972d32007-11-04 22:37:50 +00002916 // Generate the funky cast.
2917 CastExpr *cast;
Chris Lattner5f9e2722011-07-23 10:55:15 +00002918 SmallVector<QualType, 8> ArgTypes;
Steve Naroffab972d32007-11-04 22:37:50 +00002919 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002920
Steve Naroffab972d32007-11-04 22:37:50 +00002921 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002922 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2923 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2924 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002925 ArgTypes.push_back(Context->getObjCIdType());
2926 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002927 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002928 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002929 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2930 E = OMD->param_end(); PI != E; ++PI) {
2931 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002932 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002933 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002934 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002935 (void)convertBlockPointerToFunctionPointer(t);
Steve Naroff352336b2007-11-05 14:36:37 +00002936 ArgTypes.push_back(t);
2937 }
Fariborz Jahanian3a448fb2011-09-10 17:01:56 +00002938 returnType = Exp->getType();
2939 convertToUnqualifiedObjCType(returnType);
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00002940 (void)convertBlockPointerToFunctionPointer(returnType);
Steve Naroffab972d32007-11-04 22:37:50 +00002941 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002942 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002943 }
2944 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002945 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002946
Steve Naroffab972d32007-11-04 22:37:50 +00002947 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002948 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002949 VK_LValue, SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002950
Mike Stump1eb44332009-09-09 15:08:12 +00002951 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002952 // If we don't do this cast, we get the following bizarre warning/note:
2953 // xx.m:13: warning: function called through a non-compatible type
2954 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002955 cast = NoTypeInfoCStyleCastExpr(Context,
2956 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002957 CK_BitCast, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002958
Steve Naroffab972d32007-11-04 22:37:50 +00002959 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00002960 QualType castType =
2961 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2962 // If we don't have a method decl, force a variadic cast.
2963 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
Steve Naroffab972d32007-11-04 22:37:50 +00002964 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00002965 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002966 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002967
2968 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00002969 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002970
John McCall183700f2009-09-21 23:43:11 +00002971 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002972 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002973 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00002974 FT->getResultType(), VK_RValue,
2975 EndLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002976 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002977 if (MsgSendStretFlavor) {
2978 // We have the method which returns a struct/union. Must also generate
2979 // call to objc_msgSend_stret and hang both varieties on a conditional
2980 // expression which dictate which one to envoke depending on size of
2981 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002982
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002983 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002984 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
John McCallf89e55a2010-11-18 06:31:45 +00002985 VK_LValue, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002986 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002987 cast = NoTypeInfoCStyleCastExpr(Context,
2988 Context->getPointerType(Context->VoidTy),
John McCalla5bbc502010-11-15 09:46:46 +00002989 CK_BitCast, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002990 // Now do the "normal" pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00002991 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2992 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002993 castType = Context->getPointerType(castType);
John McCalla5bbc502010-11-15 09:46:46 +00002994 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00002995 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002996
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002997 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002998 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002999
John McCall183700f2009-09-21 23:43:11 +00003000 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00003001 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00003002 MsgExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003003 FT->getResultType(), VK_RValue,
3004 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00003005
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003006 // Build sizeof(returnType)
Peter Collingbournef4e3cfb2011-03-11 19:24:49 +00003007 UnaryExprOrTypeTraitExpr *sizeofExpr =
3008 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3009 Context->getTrivialTypeSourceInfo(returnType),
3010 Context->getSizeType(), SourceLocation(),
3011 SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003012 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3013 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3014 // For X86 it is more complicated and some kind of target specific routine
3015 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00003016 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00003017 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00003018 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3019 llvm::APInt(IntSize, 8),
3020 Context->IntTy,
3021 SourceLocation());
John McCallf89e55a2010-11-18 06:31:45 +00003022 BinaryOperator *lessThanExpr =
3023 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3024 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003025 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00003026 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00003027 new (Context) ConditionalOperator(lessThanExpr,
3028 SourceLocation(), CE,
John McCall56ca35d2011-02-17 10:25:35 +00003029 SourceLocation(), STCE,
John McCall09431682010-11-18 19:01:18 +00003030 returnType, VK_RValue, OK_Ordinary);
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003031 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3032 CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00003033 }
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003034 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003035 return ReplacingStmt;
3036}
3037
Steve Naroffb29b4272008-04-14 22:03:09 +00003038Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian1d35b162010-02-22 20:48:10 +00003039 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3040 Exp->getLocEnd());
Mike Stump1eb44332009-09-09 15:08:12 +00003041
Steve Naroff934f2762007-10-24 22:48:43 +00003042 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00003043 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00003044
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003045 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00003046 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00003047}
3048
Steve Naroff621edce2009-04-29 16:37:50 +00003049// typedef struct objc_object Protocol;
3050QualType RewriteObjC::getProtocolType() {
3051 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00003052 TypeSourceInfo *TInfo
3053 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00003054 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Abramo Bagnara344577e2011-03-06 15:48:19 +00003055 SourceLocation(), SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00003056 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00003057 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00003058 }
3059 return Context->getTypeDeclType(ProtocolTypeDecl);
3060}
3061
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003062/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00003063/// a synthesized/forward data reference (to the protocol's metadata).
3064/// The forward references (and metadata) are generated in
3065/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00003066Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00003067 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3068 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00003069 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003070 SourceLocation(), ID, getProtocolType(), 0,
John McCalld931b082010-08-26 03:08:43 +00003071 SC_Extern, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00003072 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), VK_LValue,
3073 SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00003074 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
Steve Naroff621edce2009-04-29 16:37:50 +00003075 Context->getPointerType(DRE->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00003076 VK_RValue, OK_Ordinary, SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00003077 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
John McCalla5bbc502010-11-15 09:46:46 +00003078 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003079 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00003080 ReplaceStmt(Exp, castExpr);
3081 ProtocolExprDecls.insert(Exp->getProtocol());
Fariborz Jahanianf2ad2c92010-10-11 21:29:12 +00003082 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00003083 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00003084
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00003085}
3086
Mike Stump1eb44332009-09-09 15:08:12 +00003087bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00003088 const char *endBuf) {
3089 while (startBuf < endBuf) {
3090 if (*startBuf == '#') {
3091 // Skip whitespace.
3092 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3093 ;
3094 if (!strncmp(startBuf, "if", strlen("if")) ||
3095 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3096 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3097 !strncmp(startBuf, "define", strlen("define")) ||
3098 !strncmp(startBuf, "undef", strlen("undef")) ||
3099 !strncmp(startBuf, "else", strlen("else")) ||
3100 !strncmp(startBuf, "elif", strlen("elif")) ||
3101 !strncmp(startBuf, "endif", strlen("endif")) ||
3102 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3103 !strncmp(startBuf, "include", strlen("include")) ||
3104 !strncmp(startBuf, "import", strlen("import")) ||
3105 !strncmp(startBuf, "include_next", strlen("include_next")))
3106 return true;
3107 }
3108 startBuf++;
3109 }
3110 return false;
3111}
3112
Fariborz Jahanian58457172011-12-05 18:43:13 +00003113/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003114/// an objective-c class with ivars.
Fariborz Jahanian58457172011-12-05 18:43:13 +00003115void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003116 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003117 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Daniel Dunbar4087f272010-08-17 22:39:59 +00003118 assert(CDecl->getName() != "" &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00003119 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003120 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003121 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00003122 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003123 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003124 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00003125 SourceLocation LocStart = CDecl->getLocStart();
3126 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00003127
Steve Narofffea763e82007-11-14 19:25:57 +00003128 const char *startBuf = SM->getCharacterData(LocStart);
3129 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00003130
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003131 // If no ivars and no root or if its root, directly or indirectly,
3132 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003133 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
3134 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00003135 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003136 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003137 return;
3138 }
Mike Stump1eb44332009-09-09 15:08:12 +00003139
3140 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003141 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00003142 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003143 Result += CDecl->getNameAsString();
Francois Pichet62ec1f22011-09-17 17:15:52 +00003144 if (LangOpts.MicrosoftExt)
Steve Naroff61ed9ca2008-03-10 23:16:54 +00003145 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00003146
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003147 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00003148 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00003149 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003150 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00003151 // If the buffer contains preprocessor directives, we do more fine-grained
3152 // rewrites. This is intended to fix code that looks like (which occurs in
3153 // NSURL.h, for example):
3154 //
3155 // #ifdef XYZ
3156 // @interface Foo : NSObject
3157 // #else
3158 // @interface FooBar : NSObject
3159 // #endif
3160 // {
3161 // int i;
3162 // }
3163 // @end
3164 //
3165 // This clause is segregated to avoid breaking the common case.
3166 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003167 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Argyrios Kyrtzidis1711fc92011-10-04 04:48:02 +00003168 CDecl->getAtStartLoc();
Steve Naroffbaf58c32008-05-31 14:15:04 +00003169 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00003170 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003171
Chris Lattnercafeb352009-02-20 18:18:36 +00003172 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00003173 // advance to the end of the referenced protocols.
3174 while (endHeader < cursor && *endHeader != '>') endHeader++;
3175 endHeader++;
3176 }
3177 // rewrite the original header
Benjamin Kramerd999b372010-02-14 14:14:16 +00003178 ReplaceText(LocStart, endHeader-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003179 } else {
3180 // rewrite the original header *without* disturbing the '{'
Benjamin Kramerd999b372010-02-14 14:14:16 +00003181 ReplaceText(LocStart, cursor-startBuf, Result);
Steve Naroffbaf58c32008-05-31 14:15:04 +00003182 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003183 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00003184 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003185 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003186 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003187 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003188 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003189
Steve Narofffea763e82007-11-14 19:25:57 +00003190 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003191 SourceLocation OnePastCurly =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003192 LocStart.getLocWithOffset(cursor-startBuf+1);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003193 InsertText(OnePastCurly, Result);
Steve Narofffea763e82007-11-14 19:25:57 +00003194 }
3195 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00003196
Steve Narofffea763e82007-11-14 19:25:57 +00003197 // Now comment out any visibility specifiers.
3198 while (cursor < endBuf) {
3199 if (*cursor == '@') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003200 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00003201 // Skip whitespace.
3202 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
3203 /*scan*/;
3204
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003205 // FIXME: presence of @public, etc. inside comment results in
3206 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00003207 if (!strncmp(cursor, "public", strlen("public")) ||
3208 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00003209 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00003210 !strncmp(cursor, "protected", strlen("protected")))
Benjamin Kramerd999b372010-02-14 14:14:16 +00003211 InsertText(atLoc, "// ");
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003212 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00003213 // FIXME: If there are cases where '<' is used in ivar declaration part
3214 // of user code, then scan the ivar list and use needToScanForQualifiers
3215 // for type checking.
3216 else if (*cursor == '<') {
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003217 SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003218 InsertText(atLoc, "/* ");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003219 cursor = strchr(cursor, '>');
3220 cursor++;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003221 atLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003222 InsertText(atLoc, " */");
Steve Naroffced80a82008-10-30 12:09:33 +00003223 } else if (*cursor == '^') { // rewrite block specifier.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003224 SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003225 ReplaceText(caretLoc, 1, "*");
Fariborz Jahanian95673922007-11-14 22:26:25 +00003226 }
Steve Narofffea763e82007-11-14 19:25:57 +00003227 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003228 }
Steve Narofffea763e82007-11-14 19:25:57 +00003229 // Don't forget to add a ';'!!
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003230 InsertText(LocEnd.getLocWithOffset(1), ";");
Steve Narofffea763e82007-11-14 19:25:57 +00003231 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003232 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003233 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003234 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003235 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003236 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003237 Result += "_IVARS;\n};\n";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003238 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003239 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003240 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003241 if (!ObjCSynthesizedStructs.insert(CDecl))
David Blaikieb219cfc2011-09-23 05:06:16 +00003242 llvm_unreachable("struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003243}
3244
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003245//===----------------------------------------------------------------------===//
3246// Meta Data Emission
3247//===----------------------------------------------------------------------===//
3248
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003249
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003250/// RewriteImplementations - This routine rewrites all method implementations
3251/// and emits meta-data.
3252
Steve Narofface66252008-11-13 20:07:04 +00003253void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003254 int ClsDefCount = ClassImplementation.size();
3255 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003256
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003257 // Rewrite implemented methods
3258 for (int i = 0; i < ClsDefCount; i++)
3259 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003260
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003261 for (int i = 0; i < CatDefCount; i++)
3262 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003263}
Mike Stump1eb44332009-09-09 15:08:12 +00003264
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003265void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3266 const std::string &Name,
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003267 ValueDecl *VD, bool def) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003268 assert(BlockByRefDeclNo.count(VD) &&
3269 "RewriteByRefString: ByRef decl missing");
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00003270 if (def)
3271 ResultStr += "struct ";
3272 ResultStr += "__Block_byref_" + Name +
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003273 "_" + utostr(BlockByRefDeclNo[VD]) ;
3274}
3275
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003276static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3277 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3278 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3279 return false;
3280}
3281
Steve Naroff54055232008-10-27 17:20:55 +00003282std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003283 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003284 std::string Tag) {
3285 const FunctionType *AFT = CE->getFunctionType();
3286 QualType RT = AFT->getResultType();
3287 std::string StructRef = "struct " + Tag;
Douglas Gregor30c42402011-09-27 22:38:19 +00003288 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Daniel Dunbar4087f272010-08-17 22:39:59 +00003289 funcName.str() + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003290
Steve Naroff54055232008-10-27 17:20:55 +00003291 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003292
Douglas Gregor72564e72009-02-26 23:50:07 +00003293 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003294 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003295 // block (to reference imported block decl refs).
3296 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003297 } else if (BD->param_empty()) {
3298 S += "(" + StructRef + " *__cself)";
3299 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003300 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003301 assert(FT && "SynthesizeBlockFunc: No function proto");
3302 S += '(';
3303 // first add the implicit argument.
3304 S += StructRef + " *__cself, ";
3305 std::string ParamStr;
3306 for (BlockDecl::param_iterator AI = BD->param_begin(),
3307 E = BD->param_end(); AI != E; ++AI) {
3308 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003309 ParamStr = (*AI)->getNameAsString();
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003310 QualType QT = (*AI)->getType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003311 if (convertBlockPointerToFunctionPointer(QT))
Douglas Gregor30c42402011-09-27 22:38:19 +00003312 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003313 else
Douglas Gregor30c42402011-09-27 22:38:19 +00003314 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003315 S += ParamStr;
3316 }
3317 if (FT->isVariadic()) {
3318 if (!BD->param_empty()) S += ", ";
3319 S += "...";
3320 }
3321 S += ')';
3322 }
3323 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Steve Naroff54055232008-10-27 17:20:55 +00003325 // Create local declarations to avoid rewriting all closure decl ref exprs.
3326 // First, emit a declaration for all "by ref" decls.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003327 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003328 E = BlockByRefDecls.end(); I != E; ++I) {
3329 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003330 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003331 std::string TypeString;
3332 RewriteByRefString(TypeString, Name, (*I));
3333 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003334 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003335 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003336 }
Steve Naroff54055232008-10-27 17:20:55 +00003337 // Next, emit a declaration for all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003338 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003339 E = BlockByCopyDecls.end(); I != E; ++I) {
3340 S += " ";
Steve Naroff54055232008-10-27 17:20:55 +00003341 // Handle nested closure invocation. For example:
3342 //
3343 // void (^myImportedClosure)(void);
3344 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003345 //
Steve Naroff54055232008-10-27 17:20:55 +00003346 // void (^anotherClosure)(void);
3347 // anotherClosure = ^(void) {
3348 // myImportedClosure(); // import and invoke the closure
3349 // };
3350 //
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003351 if (isTopLevelBlockPointerType((*I)->getType())) {
3352 RewriteBlockPointerTypeVariable(S, (*I));
3353 S += " = (";
3354 RewriteBlockPointerType(S, (*I)->getType());
3355 S += ")";
3356 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3357 }
3358 else {
Fariborz Jahanian210c2482010-02-16 17:26:03 +00003359 std::string Name = (*I)->getNameAsString();
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003360 QualType QT = (*I)->getType();
3361 if (HasLocalVariableExternalStorage(*I))
3362 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003363 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahaniane8c28df2010-02-16 16:21:26 +00003364 S += Name + " = __cself->" +
3365 (*I)->getNameAsString() + "; // bound by copy\n";
3366 }
Steve Naroff54055232008-10-27 17:20:55 +00003367 }
3368 std::string RewrittenStr = RewrittenBlockExprs[CE];
3369 const char *cstr = RewrittenStr.c_str();
3370 while (*cstr++ != '{') ;
3371 S += cstr;
3372 S += "\n";
3373 return S;
3374}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003375
Steve Naroff54055232008-10-27 17:20:55 +00003376std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003377 StringRef funcName,
Steve Naroff54055232008-10-27 17:20:55 +00003378 std::string Tag) {
3379 std::string StructRef = "struct " + Tag;
3380 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003381
Steve Naroff54055232008-10-27 17:20:55 +00003382 S += funcName;
3383 S += "_block_copy_" + utostr(i);
3384 S += "(" + StructRef;
3385 S += "*dst, " + StructRef;
3386 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003387 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003388 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003389 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003390 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003391 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003392 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003393 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003394 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003395 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003396 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003397 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003398 else
3399 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003400 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003401 S += "}\n";
3402
Steve Naroff54055232008-10-27 17:20:55 +00003403 S += "\nstatic void __";
3404 S += funcName;
3405 S += "_block_dispose_" + utostr(i);
3406 S += "(" + StructRef;
3407 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003408 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003409 E = ImportedBlockDecls.end(); I != E; ++I) {
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003410 ValueDecl *VD = (*I);
Steve Naroff5bc60d02008-12-16 15:50:30 +00003411 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003412 S += (*I)->getNameAsString();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003413 if (BlockByRefDeclsPtrSet.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003414 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003415 else if (VD->getType()->isBlockPointerType())
Fariborz Jahanian06433c62011-07-30 01:07:55 +00003416 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
Fariborz Jahaniana3f61ae2011-07-30 01:21:41 +00003417 else
3418 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003419 }
Mike Stump1eb44332009-09-09 15:08:12 +00003420 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003421 return S;
3422}
3423
Steve Naroff01aec112009-12-06 21:14:13 +00003424std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3425 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003426 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003427 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003428
Steve Naroff54055232008-10-27 17:20:55 +00003429 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003430 S += " struct " + Desc;
3431 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003432
Steve Naroff01aec112009-12-06 21:14:13 +00003433 Constructor += "(void *fp, "; // Invoke function pointer.
3434 Constructor += "struct " + Desc; // Descriptor pointer.
3435 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003436
Steve Naroff54055232008-10-27 17:20:55 +00003437 if (BlockDeclRefs.size()) {
3438 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003439 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003440 E = BlockByCopyDecls.end(); I != E; ++I) {
3441 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003442 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003443 std::string ArgName = "_" + FieldName;
3444 // Handle nested closure invocation. For example:
3445 //
3446 // void (^myImportedBlock)(void);
3447 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003448 //
Steve Naroff54055232008-10-27 17:20:55 +00003449 // void (^anotherBlock)(void);
3450 // anotherBlock = ^(void) {
3451 // myImportedBlock(); // import and invoke the closure
3452 // };
3453 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003454 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003455 S += "struct __block_impl *";
3456 Constructor += ", void *" + ArgName;
3457 } else {
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003458 QualType QT = (*I)->getType();
3459 if (HasLocalVariableExternalStorage(*I))
3460 QT = Context->getPointerType(QT);
Douglas Gregor30c42402011-09-27 22:38:19 +00003461 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3462 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
Steve Naroff54055232008-10-27 17:20:55 +00003463 Constructor += ", " + ArgName;
3464 }
3465 S += FieldName + ";\n";
3466 }
3467 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003468 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003469 E = BlockByRefDecls.end(); I != E; ++I) {
3470 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003471 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003472 std::string ArgName = "_" + FieldName;
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003473 {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003474 std::string TypeString;
3475 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003476 TypeString += " *";
3477 FieldName = TypeString + FieldName;
3478 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003479 Constructor += ", " + ArgName;
3480 }
3481 S += FieldName + "; // by ref\n";
3482 }
3483 // Finish writing the constructor.
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003484 Constructor += ", int flags=0)";
3485 // Initialize all "by copy" arguments.
3486 bool firsTime = true;
Chris Lattner5f9e2722011-07-23 10:55:15 +00003487 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003488 E = BlockByCopyDecls.end(); I != E; ++I) {
3489 std::string Name = (*I)->getNameAsString();
3490 if (firsTime) {
3491 Constructor += " : ";
3492 firsTime = false;
3493 }
3494 else
3495 Constructor += ", ";
3496 if (isTopLevelBlockPointerType((*I)->getType()))
3497 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3498 else
3499 Constructor += Name + "(_" + Name + ")";
3500 }
3501 // Initialize all "by ref" arguments.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003502 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003503 E = BlockByRefDecls.end(); I != E; ++I) {
3504 std::string Name = (*I)->getNameAsString();
3505 if (firsTime) {
3506 Constructor += " : ";
3507 firsTime = false;
3508 }
3509 else
3510 Constructor += ", ";
Fariborz Jahanian651ba522011-04-01 23:08:13 +00003511 Constructor += Name + "(_" + Name + "->__forwarding)";
Fariborz Jahanian20432ef2010-07-28 23:27:30 +00003512 }
3513
3514 Constructor += " {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003515 if (GlobalVarDecl)
3516 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3517 else
3518 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003519 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003520
Steve Naroff01aec112009-12-06 21:14:13 +00003521 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003522 } else {
3523 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003524 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003525 if (GlobalVarDecl)
3526 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3527 else
3528 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003529 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3530 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00003531 }
3532 Constructor += " ";
3533 Constructor += "}\n";
3534 S += Constructor;
3535 S += "};\n";
3536 return S;
3537}
3538
Steve Naroff01aec112009-12-06 21:14:13 +00003539std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3540 std::string ImplTag, int i,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003541 StringRef FunName,
Steve Naroff01aec112009-12-06 21:14:13 +00003542 unsigned hasCopy) {
3543 std::string S = "\nstatic struct " + DescTag;
3544
3545 S += " {\n unsigned long reserved;\n";
3546 S += " unsigned long Block_size;\n";
3547 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00003548 S += " void (*copy)(struct ";
3549 S += ImplTag; S += "*, struct ";
3550 S += ImplTag; S += "*);\n";
3551
3552 S += " void (*dispose)(struct ";
3553 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003554 }
3555 S += "} ";
3556
3557 S += DescTag + "_DATA = { 0, sizeof(struct ";
3558 S += ImplTag + ")";
3559 if (hasCopy) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00003560 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3561 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
Steve Naroff01aec112009-12-06 21:14:13 +00003562 }
3563 S += "};\n";
3564 return S;
3565}
3566
Steve Naroff54055232008-10-27 17:20:55 +00003567void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003568 StringRef FunName) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003569 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00003570 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00003571 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003572 bool RewriteSC = (GlobalVarDecl &&
3573 !Blocks.empty() &&
John McCalld931b082010-08-26 03:08:43 +00003574 GlobalVarDecl->getStorageClass() == SC_Static &&
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003575 GlobalVarDecl->getType().getCVRQualifiers());
3576 if (RewriteSC) {
3577 std::string SC(" void __");
3578 SC += GlobalVarDecl->getNameAsString();
3579 SC += "() {}";
3580 InsertText(FunLocStart, SC);
3581 }
3582
Steve Naroff54055232008-10-27 17:20:55 +00003583 // Insert closures that were part of the function.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003584 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3585 CollectBlockDeclRefInfo(Blocks[i]);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003586 // Need to copy-in the inner copied-in variables not actually used in this
3587 // block.
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003588 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
3589 BlockDeclRefExpr *Exp = InnerDeclRefs[count++];
3590 ValueDecl *VD = Exp->getDecl();
3591 BlockDeclRefs.push_back(Exp);
3592 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
3593 BlockByCopyDeclsPtrSet.insert(VD);
3594 BlockByCopyDecls.push_back(VD);
3595 }
3596 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
3597 BlockByRefDeclsPtrSet.insert(VD);
3598 BlockByRefDecls.push_back(VD);
3599 }
Fariborz Jahanian92c85682010-10-05 18:05:06 +00003600 // imported objects in the inner blocks not used in the outer
3601 // blocks must be copied/disposed in the outer block as well.
3602 if (Exp->isByRef() ||
3603 VD->getType()->isObjCObjectPointerType() ||
3604 VD->getType()->isBlockPointerType())
3605 ImportedBlockDecls.insert(VD);
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003606 }
Steve Naroff54055232008-10-27 17:20:55 +00003607
Daniel Dunbar4087f272010-08-17 22:39:59 +00003608 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3609 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00003610
Steve Naroff01aec112009-12-06 21:14:13 +00003611 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00003612
Benjamin Kramerd999b372010-02-14 14:14:16 +00003613 InsertText(FunLocStart, CI);
Steve Naroff54055232008-10-27 17:20:55 +00003614
Steve Naroff01aec112009-12-06 21:14:13 +00003615 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00003616
Benjamin Kramerd999b372010-02-14 14:14:16 +00003617 InsertText(FunLocStart, CF);
Steve Naroff54055232008-10-27 17:20:55 +00003618
3619 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00003620 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003621 InsertText(FunLocStart, HF);
Steve Naroff54055232008-10-27 17:20:55 +00003622 }
Steve Naroff01aec112009-12-06 21:14:13 +00003623 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3624 ImportedBlockDecls.size() > 0);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003625 InsertText(FunLocStart, BD);
Mike Stump1eb44332009-09-09 15:08:12 +00003626
Steve Naroff54055232008-10-27 17:20:55 +00003627 BlockDeclRefs.clear();
3628 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003629 BlockByRefDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003630 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00003631 BlockByCopyDeclsPtrSet.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003632 ImportedBlockDecls.clear();
3633 }
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003634 if (RewriteSC) {
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003635 // Must insert any 'const/volatile/static here. Since it has been
3636 // removed as result of rewriting of block literals.
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003637 std::string SC;
John McCalld931b082010-08-26 03:08:43 +00003638 if (GlobalVarDecl->getStorageClass() == SC_Static)
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003639 SC = "static ";
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003640 if (GlobalVarDecl->getType().isConstQualified())
3641 SC += "const ";
3642 if (GlobalVarDecl->getType().isVolatileQualified())
3643 SC += "volatile ";
Fariborz Jahanian8611eb02010-03-04 21:35:37 +00003644 if (GlobalVarDecl->getType().isRestrictQualified())
3645 SC += "restrict ";
3646 InsertText(FunLocStart, SC);
Fariborz Jahanian61b82e32010-03-04 18:54:29 +00003647 }
3648
Steve Naroff54055232008-10-27 17:20:55 +00003649 Blocks.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003650 InnerDeclRefsCount.clear();
3651 InnerDeclRefs.clear();
Steve Naroff54055232008-10-27 17:20:55 +00003652 RewrittenBlockExprs.clear();
3653}
3654
3655void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3656 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner5f9e2722011-07-23 10:55:15 +00003657 StringRef FuncName = FD->getName();
Mike Stump1eb44332009-09-09 15:08:12 +00003658
Steve Naroff54055232008-10-27 17:20:55 +00003659 SynthesizeBlockLiterals(FunLocStart, FuncName);
3660}
3661
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003662static void BuildUniqueMethodName(std::string &Name,
3663 ObjCMethodDecl *MD) {
3664 ObjCInterfaceDecl *IFace = MD->getClassInterface();
Daniel Dunbar4087f272010-08-17 22:39:59 +00003665 Name = IFace->getName();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003666 Name += "__" + MD->getSelector().getAsString();
3667 // Convert colons to underscores.
3668 std::string::size_type loc = 0;
3669 while ((loc = Name.find(":", loc)) != std::string::npos)
3670 Name.replace(loc, 1, "_");
3671}
3672
Steve Naroff54055232008-10-27 17:20:55 +00003673void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00003674 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3675 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00003676 SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00003677 std::string FuncName;
3678 BuildUniqueMethodName(FuncName, MD);
Daniel Dunbar4087f272010-08-17 22:39:59 +00003679 SynthesizeBlockLiterals(FunLocStart, FuncName);
Steve Naroff54055232008-10-27 17:20:55 +00003680}
3681
3682void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
John McCall7502c1d2011-02-13 04:07:26 +00003683 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Naroff54055232008-10-27 17:20:55 +00003684 if (*CI) {
3685 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3686 GetBlockDeclRefExprs(CBE->getBody());
3687 else
3688 GetBlockDeclRefExprs(*CI);
3689 }
3690 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003691 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Steve Naroff54055232008-10-27 17:20:55 +00003692 // FIXME: Handle enums.
3693 if (!isa<FunctionDecl>(CDRE->getDecl()))
3694 BlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003695 }
3696 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3697 if (HasLocalVariableExternalStorage(DRE->getDecl())) {
3698 BlockDeclRefExpr *BDRE =
John McCall6b5a61b2011-02-07 10:33:21 +00003699 new (Context)BlockDeclRefExpr(cast<VarDecl>(DRE->getDecl()),
3700 DRE->getType(),
John McCallf89e55a2010-11-18 06:31:45 +00003701 VK_LValue, DRE->getLocation(), false);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003702 BlockDeclRefs.push_back(BDRE);
3703 }
3704
Steve Naroff54055232008-10-27 17:20:55 +00003705 return;
3706}
3707
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003708void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
Chris Lattner5f9e2722011-07-23 10:55:15 +00003709 SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003710 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
John McCall7502c1d2011-02-13 04:07:26 +00003711 for (Stmt::child_range CI = S->children(); CI; ++CI)
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003712 if (*CI) {
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003713 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3714 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003715 GetInnerBlockDeclRefExprs(CBE->getBody(),
3716 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003717 InnerContexts);
3718 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003719 else
3720 GetInnerBlockDeclRefExprs(*CI,
3721 InnerBlockDeclRefs,
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003722 InnerContexts);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003723
3724 }
3725 // Handle specific things.
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003726 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003727 if (!isa<FunctionDecl>(CDRE->getDecl()) &&
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003728 !InnerContexts.count(CDRE->getDecl()->getDeclContext()))
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003729 InnerBlockDeclRefs.push_back(CDRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003730 }
3731 else if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3732 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3733 if (Var->isFunctionOrMethodVarDecl())
3734 ImportedLocalExternalDecls.insert(Var);
3735 }
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00003736
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00003737 return;
3738}
3739
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003740/// convertFunctionTypeOfBlocks - This routine converts a function type
3741/// whose result type may be a block pointer or whose argument type(s)
Chris Lattnerfc8f0e12011-04-15 05:22:18 +00003742/// might be block pointers to an equivalent function type replacing
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003743/// all block pointers to function pointers.
3744QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3745 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3746 // FTP will be null for closures that don't take arguments.
3747 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003748 SmallVector<QualType, 8> ArgTypes;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003749 QualType Res = FT->getResultType();
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003750 bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003751
3752 if (FTP) {
3753 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3754 E = FTP->arg_type_end(); I && (I != E); ++I) {
3755 QualType t = *I;
3756 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian4fc84532010-05-25 17:12:52 +00003757 if (convertBlockPointerToFunctionPointer(t))
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003758 HasBlockType = true;
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003759 ArgTypes.push_back(t);
3760 }
3761 }
3762 QualType FuncType;
3763 // FIXME. Does this work if block takes no argument but has a return type
3764 // which is of block type?
3765 if (HasBlockType)
John McCalle23cf432010-12-14 08:05:40 +00003766 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
Fariborz Jahanian1f906222010-05-25 15:56:08 +00003767 else FuncType = QualType(FT, 0);
3768 return FuncType;
3769}
3770
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003771Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00003772 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00003773 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003774
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003775 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003776 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003777 } else if (const BlockDeclRefExpr *CDRE =
3778 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003779 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003780 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00003781 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003782 }
3783 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3784 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3785 }
3786 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3787 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3788 else if (const ConditionalOperator *CEXPR =
3789 dyn_cast<ConditionalOperator>(BlockExp)) {
3790 Expr *LHSExp = CEXPR->getLHS();
3791 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3792 Expr *RHSExp = CEXPR->getRHS();
3793 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3794 Expr *CONDExp = CEXPR->getCond();
3795 ConditionalOperator *CondExpr =
3796 new (Context) ConditionalOperator(CONDExp,
3797 SourceLocation(), cast<Expr>(LHSStmt),
Fariborz Jahanianf9b949f2010-08-31 18:02:20 +00003798 SourceLocation(), cast<Expr>(RHSStmt),
John McCall09431682010-11-18 19:01:18 +00003799 Exp->getType(), VK_RValue, OK_Ordinary);
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00003800 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00003801 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3802 CPT = IRE->getType()->getAs<BlockPointerType>();
John McCall4b9c2d22011-11-06 09:01:30 +00003803 } else if (const PseudoObjectExpr *POE
3804 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3805 CPT = POE->getType()->castAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00003806 } else {
3807 assert(1 && "RewriteBlockClass: Bad type");
3808 }
3809 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00003810 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00003811 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00003812 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00003813 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003814
Abramo Bagnara465d41b2010-05-11 21:36:43 +00003815 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00003816 SourceLocation(), SourceLocation(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003817 &Context->Idents.get("__block_impl"));
3818 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00003819
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003820 // Generate a funky cast.
Chris Lattner5f9e2722011-07-23 10:55:15 +00003821 SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00003822
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003823 // Push the block argument type.
3824 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00003825 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00003826 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003827 E = FTP->arg_type_end(); I && (I != E); ++I) {
3828 QualType t = *I;
3829 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003830 if (!convertBlockPointerToFunctionPointer(t))
3831 convertToUnqualifiedObjCType(t);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003832 ArgTypes.push_back(t);
3833 }
Steve Naroff54055232008-10-27 17:20:55 +00003834 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003835 // Now do the pointer to function cast.
John McCalle23cf432010-12-14 08:05:40 +00003836 QualType PtrToFuncCastType
3837 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
Mike Stump1eb44332009-09-09 15:08:12 +00003838
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003839 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00003840
John McCall9d125032010-01-15 18:39:57 +00003841 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
John McCalla5bbc502010-11-15 09:46:46 +00003842 CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00003843 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003844 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00003845 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3846 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003847 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00003848
Douglas Gregor44b43212008-12-11 16:49:14 +00003849 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003850 SourceLocation(),
3851 &Context->Idents.get("FuncPtr"),
3852 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003853 /*BitWidth=*/0, /*Mutable=*/true,
3854 /*HasInit=*/false);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003855 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003856 FD->getType(), VK_LValue,
3857 OK_Ordinary);
Mike Stump1eb44332009-09-09 15:08:12 +00003858
Fariborz Jahanian8188e5f2010-11-05 18:34:46 +00003859
John McCall9d125032010-01-15 18:39:57 +00003860 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
John McCalla5bbc502010-11-15 09:46:46 +00003861 CK_BitCast, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00003862 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00003863
Chris Lattner5f9e2722011-07-23 10:55:15 +00003864 SmallVector<Expr*, 8> BlkExprs;
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003865 // Add the implicit argument.
3866 BlkExprs.push_back(BlkCast);
3867 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00003868 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003869 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003870 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00003871 }
Ted Kremenek668bf912009-02-09 20:51:47 +00003872 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3873 BlkExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00003874 Exp->getType(), VK_RValue,
3875 SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00003876 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00003877}
3878
Steve Naroff621edce2009-04-29 16:37:50 +00003879// We need to return the rewritten expression to handle cases where the
3880// BlockDeclRefExpr is embedded in another expression being rewritten.
3881// For example:
3882//
3883// int main() {
3884// __block Foo *f;
3885// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00003886//
Steve Naroff621edce2009-04-29 16:37:50 +00003887// void (^myblock)() = ^() {
3888// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3889// i = 77;
3890// };
3891//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003892Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00003893 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003894 // for each DeclRefExp where BYREFVAR is name of the variable.
3895 ValueDecl *VD;
3896 bool isArrow = true;
3897 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
3898 VD = BDRE->getDecl();
3899 else {
3900 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
3901 isArrow = false;
3902 }
3903
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003904 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003905 SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003906 &Context->Idents.get("__forwarding"),
3907 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003908 /*BitWidth=*/0, /*Mutable=*/true,
3909 /*HasInit=*/false);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003910 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3911 FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003912 FD->getType(), VK_LValue,
3913 OK_Ordinary);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003914
Chris Lattner5f9e2722011-07-23 10:55:15 +00003915 StringRef Name = VD->getName();
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00003916 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003917 &Context->Idents.get(Name),
3918 Context->VoidPtrTy, 0,
Richard Smith7a614d82011-06-11 17:19:42 +00003919 /*BitWidth=*/0, /*Mutable=*/true,
3920 /*HasInit=*/false);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003921 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
John McCallf89e55a2010-11-18 06:31:45 +00003922 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003923
3924
3925
Steve Naroffdf8570d2009-02-02 17:19:26 +00003926 // Need parens to enforce precedence.
Fariborz Jahanian380ee502011-04-01 19:19:28 +00003927 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3928 DeclRefExp->getExprLoc(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00003929 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00003930 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00003931 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00003932}
3933
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003934// Rewrites the imported local variable V with external storage
3935// (static, extern, etc.) as *V
3936//
3937Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3938 ValueDecl *VD = DRE->getDecl();
3939 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3940 if (!ImportedLocalExternalDecls.count(Var))
3941 return DRE;
John McCallf89e55a2010-11-18 06:31:45 +00003942 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3943 VK_LValue, OK_Ordinary,
3944 DRE->getLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00003945 // Need parens to enforce precedence.
3946 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3947 Exp);
3948 ReplaceStmt(DRE, PE);
3949 return PE;
3950}
3951
Steve Naroffb2f9e512008-11-03 23:29:32 +00003952void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3953 SourceLocation LocStart = CE->getLParenLoc();
3954 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00003955
3956 // Need to avoid trying to rewrite synthesized casts.
3957 if (LocStart.isInvalid())
3958 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00003959 // Need to avoid trying to rewrite casts contained in macros.
3960 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3961 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003962
Steve Naroff54055232008-10-27 17:20:55 +00003963 const char *startBuf = SM->getCharacterData(LocStart);
3964 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003965 QualType QT = CE->getType();
3966 const Type* TypePtr = QT->getAs<Type>();
3967 if (isa<TypeOfExprType>(TypePtr)) {
3968 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3969 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3970 std::string TypeAsString = "(";
Fariborz Jahanianafad76f2010-02-18 01:20:22 +00003971 RewriteBlockPointerType(TypeAsString, QT);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003972 TypeAsString += ")";
Benjamin Kramerd999b372010-02-14 14:14:16 +00003973 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00003974 return;
3975 }
Steve Naroff54055232008-10-27 17:20:55 +00003976 // advance the location to startArgList.
3977 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00003978
Steve Naroff54055232008-10-27 17:20:55 +00003979 while (*argPtr++ && (argPtr < endBuf)) {
3980 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00003981 case '^':
3982 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00003983 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
Benjamin Kramerd999b372010-02-14 14:14:16 +00003984 ReplaceText(LocStart, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00003985 break;
Steve Naroff54055232008-10-27 17:20:55 +00003986 }
3987 }
3988 return;
3989}
3990
3991void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3992 SourceLocation DeclLoc = FD->getLocation();
3993 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00003994
Steve Naroff54055232008-10-27 17:20:55 +00003995 // We have 1 or more arguments that have closure pointers.
3996 const char *startBuf = SM->getCharacterData(DeclLoc);
3997 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00003998
Steve Naroff54055232008-10-27 17:20:55 +00003999 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004000
Steve Naroff54055232008-10-27 17:20:55 +00004001 parenCount++;
4002 // advance the location to startArgList.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004003 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
Steve Naroff54055232008-10-27 17:20:55 +00004004 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004005
Steve Naroff54055232008-10-27 17:20:55 +00004006 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004007
Steve Naroff54055232008-10-27 17:20:55 +00004008 while (*argPtr++ && parenCount) {
4009 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004010 case '^':
4011 // Replace the '^' with '*'.
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004012 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
Benjamin Kramerd999b372010-02-14 14:14:16 +00004013 ReplaceText(DeclLoc, 1, "*");
Mike Stumpb7166332010-01-20 02:03:14 +00004014 break;
4015 case '(':
4016 parenCount++;
4017 break;
4018 case ')':
4019 parenCount--;
4020 break;
Steve Naroff54055232008-10-27 17:20:55 +00004021 }
4022 }
4023 return;
4024}
4025
4026bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004027 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004028 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004029 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004030 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004031 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004032 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004033 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004034 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004035 }
4036 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004037 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004038 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004039 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004040 return true;
4041 }
4042 return false;
4043}
4044
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004045bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4046 const FunctionProtoType *FTP;
4047 const PointerType *PT = QT->getAs<PointerType>();
4048 if (PT) {
4049 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4050 } else {
4051 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4052 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4053 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4054 }
4055 if (FTP) {
4056 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004057 E = FTP->arg_type_end(); I != E; ++I) {
4058 if ((*I)->isObjCQualifiedIdType())
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004059 return true;
Fariborz Jahanian06de2cf2010-11-03 23:50:34 +00004060 if ((*I)->isObjCObjectPointerType() &&
4061 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4062 return true;
4063 }
4064
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004065 }
4066 return false;
4067}
4068
Ted Kremenek8189cde2009-02-07 01:47:29 +00004069void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4070 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004071 const char *argPtr = strchr(Name, '(');
4072 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004073
Steve Naroff54055232008-10-27 17:20:55 +00004074 LParen = argPtr; // output the start.
4075 argPtr++; // skip past the left paren.
4076 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004077
Steve Naroff54055232008-10-27 17:20:55 +00004078 while (*argPtr && parenCount) {
4079 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004080 case '(': parenCount++; break;
4081 case ')': parenCount--; break;
4082 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004083 }
4084 if (parenCount) argPtr++;
4085 }
4086 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4087 RParen = argPtr; // output the end
4088}
4089
4090void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4091 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4092 RewriteBlockPointerFunctionArgs(FD);
4093 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004094 }
Steve Naroff54055232008-10-27 17:20:55 +00004095 // Handle Variables and Typedefs.
4096 SourceLocation DeclLoc = ND->getLocation();
4097 QualType DeclT;
4098 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4099 DeclT = VD->getType();
Richard Smith162e1c12011-04-15 14:24:37 +00004100 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
Steve Naroff54055232008-10-27 17:20:55 +00004101 DeclT = TDD->getUnderlyingType();
4102 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4103 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004104 else
David Blaikieb219cfc2011-09-23 05:06:16 +00004105 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004106
Steve Naroff54055232008-10-27 17:20:55 +00004107 const char *startBuf = SM->getCharacterData(DeclLoc);
4108 const char *endBuf = startBuf;
4109 // scan backward (from the decl location) for the end of the previous decl.
4110 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4111 startBuf--;
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004112 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004113 std::string buf;
4114 unsigned OrigLength=0;
Steve Naroff54055232008-10-27 17:20:55 +00004115 // *startBuf != '^' if we are dealing with a pointer to function that
4116 // may take block argument types (which will be handled below).
4117 if (*startBuf == '^') {
4118 // Replace the '^' with '*', computing a negative offset.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004119 buf = '*';
4120 startBuf++;
4121 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004122 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004123 while (*startBuf != ')') {
4124 buf += *startBuf;
4125 startBuf++;
4126 OrigLength++;
4127 }
4128 buf += ')';
4129 OrigLength++;
4130
4131 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4132 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
Steve Naroff54055232008-10-27 17:20:55 +00004133 // Replace the '^' with '*' for arguments.
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004134 // Replace id<P> with id/*<>*/
Steve Naroff54055232008-10-27 17:20:55 +00004135 DeclLoc = ND->getLocation();
4136 startBuf = SM->getCharacterData(DeclLoc);
4137 const char *argListBegin, *argListEnd;
4138 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4139 while (argListBegin < argListEnd) {
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004140 if (*argListBegin == '^')
4141 buf += '*';
4142 else if (*argListBegin == '<') {
4143 buf += "/*";
4144 buf += *argListBegin++;
4145 OrigLength++;;
4146 while (*argListBegin != '>') {
4147 buf += *argListBegin++;
4148 OrigLength++;
4149 }
4150 buf += *argListBegin;
4151 buf += "*/";
Steve Naroff54055232008-10-27 17:20:55 +00004152 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004153 else
4154 buf += *argListBegin;
Steve Naroff54055232008-10-27 17:20:55 +00004155 argListBegin++;
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004156 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004157 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004158 buf += ')';
4159 OrigLength++;
Steve Naroff54055232008-10-27 17:20:55 +00004160 }
Fariborz Jahaniane985d012010-11-03 23:29:24 +00004161 ReplaceText(Start, OrigLength, buf);
4162
Steve Naroff54055232008-10-27 17:20:55 +00004163 return;
4164}
4165
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004166
4167/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4168/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4169/// struct Block_byref_id_object *src) {
4170/// _Block_object_assign (&_dest->object, _src->object,
4171/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4172/// [|BLOCK_FIELD_IS_WEAK]) // object
4173/// _Block_object_assign(&_dest->object, _src->object,
4174/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4175/// [|BLOCK_FIELD_IS_WEAK]) // block
4176/// }
4177/// And:
4178/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4179/// _Block_object_dispose(_src->object,
4180/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4181/// [|BLOCK_FIELD_IS_WEAK]) // object
4182/// _Block_object_dispose(_src->object,
4183/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4184/// [|BLOCK_FIELD_IS_WEAK]) // block
4185/// }
4186
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004187std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4188 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004189 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004190 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004191 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004192 CopyDestroyCache.insert(flag);
4193 S = "static void __Block_byref_id_object_copy_";
4194 S += utostr(flag);
4195 S += "(void *dst, void *src) {\n";
4196
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004197 // offset into the object pointer is computed as:
4198 // void * + void* + int + int + void* + void *
4199 unsigned IntSize =
4200 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4201 unsigned VoidPtrSize =
4202 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4203
Ken Dyck0c4e5d62011-04-30 16:08:27 +00004204 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004205 S += " _Block_object_assign((char*)dst + ";
4206 S += utostr(offset);
4207 S += ", *(void * *) ((char*)src + ";
4208 S += utostr(offset);
4209 S += "), ";
4210 S += utostr(flag);
4211 S += ");\n}\n";
4212
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004213 S += "static void __Block_byref_id_object_dispose_";
4214 S += utostr(flag);
4215 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004216 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4217 S += utostr(offset);
4218 S += "), ";
4219 S += utostr(flag);
4220 S += ");\n}\n";
4221 return S;
4222}
4223
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004224/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4225/// the declaration into:
4226/// struct __Block_byref_ND {
4227/// void *__isa; // NULL for everything except __weak pointers
4228/// struct __Block_byref_ND *__forwarding;
4229/// int32_t __flags;
4230/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004231/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4232/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004233/// typex ND;
4234/// };
4235///
4236/// It then replaces declaration of ND variable with:
4237/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4238/// __size=sizeof(struct __Block_byref_ND),
4239/// ND=initializer-if-any};
4240///
4241///
4242void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004243 // Insert declaration for the function in which block literal is
4244 // used.
4245 if (CurFunctionDeclToDeclareForBlock)
4246 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004247 int flag = 0;
4248 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004249 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
Fariborz Jahaniand64a4f42010-02-26 22:49:11 +00004250 if (DeclLoc.isInvalid())
4251 // If type location is missing, it is because of missing type (a warning).
4252 // Use variable's location which is good for this case.
4253 DeclLoc = ND->getLocation();
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004254 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004255 SourceLocation X = ND->getLocEnd();
Chandler Carruth40278532011-07-25 16:49:02 +00004256 X = SM->getExpansionLoc(X);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004257 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004258 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004259 std::string ByrefType;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004260 RewriteByRefString(ByrefType, Name, ND, true);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004261 ByrefType += " {\n";
4262 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004263 RewriteByRefString(ByrefType, Name, ND);
4264 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004265 ByrefType += " int __flags;\n";
4266 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004267 // Add void *__Block_byref_id_object_copy;
4268 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004269 QualType Ty = ND->getType();
4270 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4271 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004272 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4273 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004274 }
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004275
4276 QualType T = Ty;
4277 (void)convertBlockPointerToFunctionPointer(T);
Douglas Gregor30c42402011-09-27 22:38:19 +00004278 T.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004279
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004280 ByrefType += " " + Name + ";\n";
4281 ByrefType += "};\n";
4282 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004283 SourceLocation FunLocStart;
4284 if (CurFunctionDef)
4285 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4286 else {
4287 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4288 FunLocStart = CurMethodDef->getLocStart();
4289 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004290 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004291 if (Ty.isObjCGCWeak()) {
4292 flag |= BLOCK_FIELD_IS_WEAK;
4293 isa = 1;
4294 }
4295
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004296 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004297 flag = BLOCK_BYREF_CALLER;
4298 QualType Ty = ND->getType();
4299 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4300 if (Ty->isBlockPointerType())
4301 flag |= BLOCK_FIELD_IS_BLOCK;
4302 else
4303 flag |= BLOCK_FIELD_IS_OBJECT;
4304 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004305 if (!HF.empty())
Benjamin Kramerd999b372010-02-14 14:14:16 +00004306 InsertText(FunLocStart, HF);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004307 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004308
4309 // struct __Block_byref_ND ND =
4310 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4311 // initializer-if-any};
4312 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004313 unsigned flags = 0;
4314 if (HasCopyAndDispose)
4315 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004316 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004317 ByrefType.clear();
4318 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004319 std::string ForwardingCastType("(");
4320 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004321 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004322 ByrefType += " " + Name + " = {(void*)";
4323 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004324 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004325 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004326 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004327 ByrefType += "sizeof(";
4328 RewriteByRefString(ByrefType, Name, ND);
4329 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004330 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004331 ByrefType += ", __Block_byref_id_object_copy_";
4332 ByrefType += utostr(flag);
4333 ByrefType += ", __Block_byref_id_object_dispose_";
4334 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004335 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004336 ByrefType += "};\n";
Fariborz Jahanian822ac872011-03-31 22:49:32 +00004337 unsigned nameSize = Name.size();
4338 // for block or function pointer declaration. Name is aleady
4339 // part of the declaration.
4340 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4341 nameSize = 1;
4342 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004343 }
4344 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004345 SourceLocation startLoc;
4346 Expr *E = ND->getInit();
4347 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4348 startLoc = ECE->getLParenLoc();
4349 else
4350 startLoc = E->getLocStart();
Chandler Carruth40278532011-07-25 16:49:02 +00004351 startLoc = SM->getExpansionLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004352 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004353 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004354 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004355 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004356 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004357 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004358 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004359 ByrefType += "sizeof(";
4360 RewriteByRefString(ByrefType, Name, ND);
4361 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004362 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004363 ByrefType += "__Block_byref_id_object_copy_";
4364 ByrefType += utostr(flag);
4365 ByrefType += ", __Block_byref_id_object_dispose_";
4366 ByrefType += utostr(flag);
4367 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004368 }
Benjamin Kramerd999b372010-02-14 14:14:16 +00004369 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Steve Naroffc5143c52009-12-23 17:24:33 +00004370
4371 // Complete the newly synthesized compound expression by inserting a right
4372 // curly brace before the end of the declaration.
4373 // FIXME: This approach avoids rewriting the initializer expression. It
4374 // also assumes there is only one declarator. For example, the following
4375 // isn't currently supported by this routine (in general):
4376 //
4377 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4378 //
Fariborz Jahanian5f371ee2010-07-21 17:36:39 +00004379 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4380 const char *semiBuf = strchr(startInitializerBuf, ';');
Steve Naroffc5143c52009-12-23 17:24:33 +00004381 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4382 SourceLocation semiLoc =
Argyrios Kyrtzidisa64ccef2011-09-19 20:40:19 +00004383 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
Steve Naroffc5143c52009-12-23 17:24:33 +00004384
Benjamin Kramerd999b372010-02-14 14:14:16 +00004385 InsertText(semiLoc, "}");
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004386 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004387 return;
4388}
4389
Mike Stump1eb44332009-09-09 15:08:12 +00004390void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004391 // Add initializers for any closure decl refs.
4392 GetBlockDeclRefExprs(Exp->getBody());
4393 if (BlockDeclRefs.size()) {
4394 // Unique all "by copy" declarations.
4395 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004396 if (!BlockDeclRefs[i]->isByRef()) {
4397 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4398 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4399 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4400 }
4401 }
Steve Naroff54055232008-10-27 17:20:55 +00004402 // Unique all "by ref" declarations.
4403 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4404 if (BlockDeclRefs[i]->isByRef()) {
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004405 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4406 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4407 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4408 }
Steve Naroff54055232008-10-27 17:20:55 +00004409 }
4410 // Find any imported blocks...they will need special attention.
4411 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004412 if (BlockDeclRefs[i]->isByRef() ||
4413 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian5b011b02010-02-26 21:46:27 +00004414 BlockDeclRefs[i]->getType()->isBlockPointerType())
Steve Naroff54055232008-10-27 17:20:55 +00004415 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
Steve Naroff54055232008-10-27 17:20:55 +00004416 }
4417}
4418
Chris Lattner5f9e2722011-07-23 10:55:15 +00004419FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004420 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004421 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004422 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4423 SourceLocation(), ID, FType, 0, SC_Extern,
John McCalld931b082010-08-26 03:08:43 +00004424 SC_None, false, false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004425}
4426
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004427Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
Chris Lattner5f9e2722011-07-23 10:55:15 +00004428 const SmallVector<BlockDeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004429 const BlockDecl *block = Exp->getBlockDecl();
Steve Narofffa15fd92008-10-28 20:29:00 +00004430 Blocks.push_back(Exp);
4431
4432 CollectBlockDeclRefInfo(Exp);
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004433
4434 // Add inner imported variables now used in current block.
4435 int countOfInnerDecls = 0;
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004436 if (!InnerBlockDeclRefs.empty()) {
4437 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
4438 BlockDeclRefExpr *Exp = InnerBlockDeclRefs[i];
4439 ValueDecl *VD = Exp->getDecl();
4440 if (!Exp->isByRef() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004441 // We need to save the copied-in variables in nested
4442 // blocks because it is needed at the end for some of the API generations.
4443 // See SynthesizeBlockLiterals routine.
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004444 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4445 BlockDeclRefs.push_back(Exp);
4446 BlockByCopyDeclsPtrSet.insert(VD);
4447 BlockByCopyDecls.push_back(VD);
4448 }
4449 if (Exp->isByRef() && !BlockByRefDeclsPtrSet.count(VD)) {
4450 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4451 BlockDeclRefs.push_back(Exp);
4452 BlockByRefDeclsPtrSet.insert(VD);
4453 BlockByRefDecls.push_back(VD);
4454 }
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004455 }
Fariborz Jahanian1276bfe2010-02-26 22:36:30 +00004456 // Find any imported blocks...they will need special attention.
4457 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
4458 if (InnerBlockDeclRefs[i]->isByRef() ||
4459 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4460 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4461 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004462 }
4463 InnerDeclRefsCount.push_back(countOfInnerDecls);
4464
Steve Narofffa15fd92008-10-28 20:29:00 +00004465 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004466
Steve Narofffa15fd92008-10-28 20:29:00 +00004467 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004468 FuncName = CurFunctionDef->getNameAsString();
Fariborz Jahaniane61a1d42010-02-10 20:18:25 +00004469 else if (CurMethodDef)
4470 BuildUniqueMethodName(FuncName, CurMethodDef);
4471 else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004472 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004473
Steve Narofffa15fd92008-10-28 20:29:00 +00004474 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004475
Steve Narofffa15fd92008-10-28 20:29:00 +00004476 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4477 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004478
Steve Narofffa15fd92008-10-28 20:29:00 +00004479 // Get a pointer to the function type so we can cast appropriately.
Fariborz Jahanian1f906222010-05-25 15:56:08 +00004480 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4481 QualType FType = Context->getPointerType(BFT);
Steve Narofffa15fd92008-10-28 20:29:00 +00004482
4483 FunctionDecl *FD;
4484 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004485
Steve Narofffa15fd92008-10-28 20:29:00 +00004486 // Simulate a contructor call...
Daniel Dunbar4087f272010-08-17 22:39:59 +00004487 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf89e55a2010-11-18 06:31:45 +00004488 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, VK_RValue,
4489 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004490
Chris Lattner5f9e2722011-07-23 10:55:15 +00004491 SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004492
Steve Narofffdc03722008-10-29 21:23:59 +00004493 // Initialize the block function.
Daniel Dunbar4087f272010-08-17 22:39:59 +00004494 FD = SynthBlockInitFunctionDecl(Func);
John McCallf89e55a2010-11-18 06:31:45 +00004495 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
Ted Kremenek8189cde2009-02-07 01:47:29 +00004496 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004497 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004498 CK_BitCast, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004499 InitExprs.push_back(castExpr);
4500
Steve Naroff01aec112009-12-06 21:14:13 +00004501 // Initialize the block descriptor.
4502 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004503
Abramo Bagnaraff676cb2011-03-08 08:55:46 +00004504 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4505 SourceLocation(), SourceLocation(),
4506 &Context->Idents.get(DescData.c_str()),
4507 Context->VoidPtrTy, 0,
4508 SC_Static, SC_None);
John McCallf89e55a2010-11-18 06:31:45 +00004509 UnaryOperator *DescRefExpr =
4510 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD,
4511 Context->VoidPtrTy,
4512 VK_LValue,
4513 SourceLocation()),
4514 UO_AddrOf,
4515 Context->getPointerType(Context->VoidPtrTy),
4516 VK_RValue, OK_Ordinary,
4517 SourceLocation());
Steve Naroff01aec112009-12-06 21:14:13 +00004518 InitExprs.push_back(DescRefExpr);
4519
Steve Narofffa15fd92008-10-28 20:29:00 +00004520 // Add initializers for any closure decl refs.
4521 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004522 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004523 // Output all "by copy" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004524 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004525 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004526 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004527 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Daniel Dunbar4087f272010-08-17 22:39:59 +00004528 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004529 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4530 SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004531 if (HasLocalVariableExternalStorage(*I)) {
4532 QualType QT = (*I)->getType();
4533 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004534 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4535 OK_Ordinary, SourceLocation());
Fariborz Jahaniana5a79872010-05-24 18:32:56 +00004536 }
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004537 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004538 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004539 Arg = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4540 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004541 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
John McCalla5bbc502010-11-15 09:46:46 +00004542 CK_BitCast, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004543 } else {
Daniel Dunbar4087f272010-08-17 22:39:59 +00004544 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004545 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4546 SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004547 if (HasLocalVariableExternalStorage(*I)) {
4548 QualType QT = (*I)->getType();
4549 QT = Context->getPointerType(QT);
John McCallf89e55a2010-11-18 06:31:45 +00004550 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4551 OK_Ordinary, SourceLocation());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004552 }
4553
Steve Narofffa15fd92008-10-28 20:29:00 +00004554 }
Mike Stump1eb44332009-09-09 15:08:12 +00004555 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004556 }
4557 // Output all "by ref" declarations.
Chris Lattner5f9e2722011-07-23 10:55:15 +00004558 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004559 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004560 ValueDecl *ND = (*I);
4561 std::string Name(ND->getNameAsString());
4562 std::string RecName;
Fariborz Jahanian1e8011e2011-01-27 23:18:15 +00004563 RewriteByRefString(RecName, Name, ND, true);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004564 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4565 + sizeof("struct"));
Abramo Bagnara465d41b2010-05-11 21:36:43 +00004566 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
Abramo Bagnaraba877ad2011-03-09 14:09:51 +00004567 SourceLocation(), SourceLocation(),
4568 II);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004569 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4570 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4571
Daniel Dunbar4087f272010-08-17 22:39:59 +00004572 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf89e55a2010-11-18 06:31:45 +00004573 Exp = new (Context) DeclRefExpr(FD, FD->getType(), VK_LValue,
4574 SourceLocation());
Fariborz Jahanian05318d82011-02-16 22:37:10 +00004575 bool isNestedCapturedVar = false;
4576 if (block)
4577 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4578 ce = block->capture_end(); ci != ce; ++ci) {
4579 const VarDecl *variable = ci->getVariable();
4580 if (variable == ND && ci->isNested()) {
4581 assert (ci->isByRef() &&
4582 "SynthBlockInitExpr - captured block variable is not byref");
4583 isNestedCapturedVar = true;
4584 break;
4585 }
4586 }
4587 // captured nested byref variable has its address passed. Do not take
4588 // its address again.
4589 if (!isNestedCapturedVar)
4590 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
John McCallf89e55a2010-11-18 06:31:45 +00004591 Context->getPointerType(Exp->getType()),
4592 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004593 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004594 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004595 }
4596 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004597 if (ImportedBlockDecls.size()) {
4598 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4599 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004600 unsigned IntSize =
4601 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Argyrios Kyrtzidis9996a7f2010-08-28 09:06:06 +00004602 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4603 Context->IntTy, SourceLocation());
Fariborz Jahanianff127882009-12-23 21:52:32 +00004604 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004605 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004606 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
John McCallf89e55a2010-11-18 06:31:45 +00004607 FType, VK_LValue, SourceLocation());
John McCall2de56d12010-08-25 11:45:40 +00004608 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004609 Context->getPointerType(NewRep->getType()),
John McCallf89e55a2010-11-18 06:31:45 +00004610 VK_RValue, OK_Ordinary, SourceLocation());
John McCalla5bbc502010-11-15 09:46:46 +00004611 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
John McCall9d125032010-01-15 18:39:57 +00004612 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004613 BlockDeclRefs.clear();
4614 BlockByRefDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004615 BlockByRefDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004616 BlockByCopyDecls.clear();
Fariborz Jahanianbab71682010-02-11 23:35:57 +00004617 BlockByCopyDeclsPtrSet.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004618 ImportedBlockDecls.clear();
4619 return NewRep;
4620}
4621
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004622bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4623 if (const ObjCForCollectionStmt * CS =
4624 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4625 return CS->getElement() == DS;
4626 return false;
4627}
4628
Steve Narofffa15fd92008-10-28 20:29:00 +00004629//===----------------------------------------------------------------------===//
4630// Function Body / Expression rewriting
4631//===----------------------------------------------------------------------===//
4632
4633Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004634 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004635 isa<DoStmt>(S) || isa<ForStmt>(S))
4636 Stmts.push_back(S);
4637 else if (isa<ObjCForCollectionStmt>(S)) {
4638 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004639 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004640 }
Mike Stump1eb44332009-09-09 15:08:12 +00004641
John McCall4b9c2d22011-11-06 09:01:30 +00004642 // Pseudo-object operations and ivar references need special
4643 // treatment because we're going to recursively rewrite them.
4644 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4645 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4646 return RewritePropertyOrImplicitSetter(PseudoOp);
4647 } else {
4648 return RewritePropertyOrImplicitGetter(PseudoOp);
4649 }
4650 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4651 return RewriteObjCIvarRefExpr(IvarRefExpr);
4652 }
4653
Steve Narofffa15fd92008-10-28 20:29:00 +00004654 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004655
Steve Narofffa15fd92008-10-28 20:29:00 +00004656 // Perform a bottom up rewrite of all children.
John McCall7502c1d2011-02-13 04:07:26 +00004657 for (Stmt::child_range CI = S->children(); CI; ++CI)
Steve Narofffa15fd92008-10-28 20:29:00 +00004658 if (*CI) {
John McCall4b9c2d22011-11-06 09:01:30 +00004659 Stmt *childStmt = (*CI);
4660 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004661 if (newStmt) {
John McCall4b9c2d22011-11-06 09:01:30 +00004662 *CI = newStmt;
Fariborz Jahanian1d015312011-04-11 21:17:02 +00004663 }
Nick Lewycky7e749242010-10-31 21:07:24 +00004664 }
Mike Stump1eb44332009-09-09 15:08:12 +00004665
Steve Narofffa15fd92008-10-28 20:29:00 +00004666 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00004667 SmallVector<BlockDeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004668 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4669 InnerContexts.insert(BE->getBlockDecl());
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004670 ImportedLocalExternalDecls.clear();
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004671 GetInnerBlockDeclRefExprs(BE->getBody(),
Fariborz Jahanian72952fc2010-03-01 23:36:21 +00004672 InnerBlockDeclRefs, InnerContexts);
Steve Narofffa15fd92008-10-28 20:29:00 +00004673 // Rewrite the block body in place.
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004674 Stmt *SaveCurrentBody = CurrentBody;
4675 CurrentBody = BE->getBody();
4676 PropParentMap = 0;
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004677 // block literal on rhs of a property-dot-sytax assignment
4678 // must be replaced by its synthesize ast so getRewrittenText
4679 // works as expected. In this case, what actually ends up on RHS
4680 // is the blockTranscribed which is the helper function for the
4681 // block literal; as in: self.c = ^() {[ace ARR];};
4682 bool saveDisableReplaceStmt = DisableReplaceStmt;
4683 DisableReplaceStmt = false;
Steve Narofffa15fd92008-10-28 20:29:00 +00004684 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004685 DisableReplaceStmt = saveDisableReplaceStmt;
Fariborz Jahanianda4ad9f2010-11-08 18:37:50 +00004686 CurrentBody = SaveCurrentBody;
4687 PropParentMap = 0;
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004688 ImportedLocalExternalDecls.clear();
Steve Narofffa15fd92008-10-28 20:29:00 +00004689 // Now we snarf the rewritten text and stash it away for later use.
Fariborz Jahanianf23a0ff2011-08-02 20:28:46 +00004690 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004691 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004692
Fariborz Jahanian5e49b2f2010-02-24 22:48:18 +00004693 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4694
Steve Narofffa15fd92008-10-28 20:29:00 +00004695 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004696 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004697 return blockTranscribed;
4698 }
4699 // Handle specific things.
4700 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4701 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004702
Steve Narofffa15fd92008-10-28 20:29:00 +00004703 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4704 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004705
Steve Narofffa15fd92008-10-28 20:29:00 +00004706 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4707 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004708
Steve Narofffa15fd92008-10-28 20:29:00 +00004709 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004710#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004711 // Before we rewrite it, put the original message expression in a comment.
4712 SourceLocation startLoc = MessExpr->getLocStart();
4713 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004714
Steve Narofffa15fd92008-10-28 20:29:00 +00004715 const char *startBuf = SM->getCharacterData(startLoc);
4716 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004717
Steve Narofffa15fd92008-10-28 20:29:00 +00004718 std::string messString;
4719 messString += "// ";
4720 messString.append(startBuf, endBuf-startBuf+1);
4721 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004722
4723 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00004724 // InsertText(clang::SourceLocation, char const*, unsigned int).
4725 // InsertText(startLoc, messString.c_str(), messString.size());
4726 // Tried this, but it didn't work either...
4727 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00004728#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00004729 return RewriteMessageExpr(MessExpr);
4730 }
Mike Stump1eb44332009-09-09 15:08:12 +00004731
Steve Narofffa15fd92008-10-28 20:29:00 +00004732 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4733 return RewriteObjCTryStmt(StmtTry);
4734
4735 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4736 return RewriteObjCSynchronizedStmt(StmtTry);
4737
4738 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4739 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00004740
Steve Narofffa15fd92008-10-28 20:29:00 +00004741 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4742 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00004743
4744 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00004745 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00004746 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00004747 OrigStmtRange.getEnd());
4748 if (BreakStmt *StmtBreakStmt =
4749 dyn_cast<BreakStmt>(S))
4750 return RewriteBreakStmt(StmtBreakStmt);
4751 if (ContinueStmt *StmtContinueStmt =
4752 dyn_cast<ContinueStmt>(S))
4753 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00004754
4755 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00004756 // and cast exprs.
4757 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4758 // FIXME: What we're doing here is modifying the type-specifier that
4759 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00004760 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00004761 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4762 // the context of an ObjCForCollectionStmt. For example:
4763 // NSArray *someArray;
4764 // for (id <FooProtocol> index in someArray) ;
4765 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4766 // and it depends on the original text locations/positions.
Fariborz Jahanian42f1e652011-02-24 21:29:21 +00004767 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
Steve Naroff3d7e7862009-12-05 15:55:59 +00004768 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00004769
Steve Narofffa15fd92008-10-28 20:29:00 +00004770 // Blocks rewrite rules.
4771 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4772 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004773 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00004774 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004775 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004776 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00004777 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004778 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004779 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004780 if (VD->hasAttr<BlocksAttr>()) {
4781 static unsigned uniqueByrefDeclCount = 0;
4782 assert(!BlockByRefDeclNo.count(ND) &&
4783 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4784 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004785 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004786 }
Fariborz Jahanian4c863ef2010-02-10 18:54:22 +00004787 else
4788 RewriteTypeOfDecl(VD);
4789 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004790 }
Richard Smith162e1c12011-04-15 14:24:37 +00004791 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004792 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004793 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00004794 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00004795 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4796 }
4797 }
4798 }
Mike Stump1eb44332009-09-09 15:08:12 +00004799
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4801 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00004802
4803 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004804 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4805 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00004806 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4807 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00004808 && "Statement stack mismatch");
4809 Stmts.pop_back();
4810 }
4811 // Handle blocks rewriting.
4812 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4813 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00004814 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004815 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004816 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4817 ValueDecl *VD = DRE->getDecl();
4818 if (VD->hasAttr<BlocksAttr>())
4819 return RewriteBlockDeclRefExpr(DRE);
Fariborz Jahanian6cb6eb42010-03-11 18:20:03 +00004820 if (HasLocalVariableExternalStorage(VD))
4821 return RewriteLocalVariableExternalStorage(DRE);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004822 }
4823
Steve Narofffa15fd92008-10-28 20:29:00 +00004824 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004825 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004826 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004827 ReplaceStmt(S, BlockCall);
4828 return BlockCall;
4829 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004830 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00004831 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004832 RewriteCastExpr(CE);
4833 }
4834#if 0
4835 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Sebastian Redl906082e2010-07-20 04:20:21 +00004836 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4837 ICE->getSubExpr(),
4838 SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004839 // Get the new text.
4840 std::string SStr;
4841 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00004842 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00004843 const std::string &Str = Buf.str();
4844
4845 printf("CAST = %s\n", &Str[0]);
4846 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4847 delete S;
4848 return Replacement;
4849 }
4850#endif
4851 // Return this stmt unmodified.
4852 return S;
4853}
4854
Steve Naroff3d7e7862009-12-05 15:55:59 +00004855void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4856 for (RecordDecl::field_iterator i = RD->field_begin(),
4857 e = RD->field_end(); i != e; ++i) {
4858 FieldDecl *FD = *i;
4859 if (isTopLevelBlockPointerType(FD->getType()))
4860 RewriteBlockPointerDecl(FD);
4861 if (FD->getType()->isObjCQualifiedIdType() ||
4862 FD->getType()->isObjCQualifiedInterfaceType())
4863 RewriteObjCQualifiedInterfaceTypes(FD);
4864 }
4865}
4866
Steve Narofffa15fd92008-10-28 20:29:00 +00004867/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4868/// main file of the input.
4869void RewriteObjC::HandleDeclInMainFile(Decl *D) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004870 switch (D->getKind()) {
4871 case Decl::Function: {
4872 FunctionDecl *FD = cast<FunctionDecl>(D);
4873 if (FD->isOverloadedOperator())
4874 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004875
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004876 // Since function prototypes don't have ParmDecl's, we check the function
4877 // prototype. This enables us to rewrite function declarations and
4878 // definitions using the same code.
4879 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00004880
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004881 // FIXME: If this should support Obj-C++, support CXXTryStmt
4882 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4883 CurFunctionDef = FD;
4884 CurFunctionDeclToDeclareForBlock = FD;
4885 CurrentBody = Body;
4886 Body =
4887 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4888 FD->setBody(Body);
4889 CurrentBody = 0;
4890 if (PropParentMap) {
4891 delete PropParentMap;
4892 PropParentMap = 0;
4893 }
4894 // This synthesizes and inserts the block "impl" struct, invoke function,
4895 // and any copy/dispose helper functions.
4896 InsertBlockLiteralsWithinFunction(FD);
4897 CurFunctionDef = 0;
4898 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004899 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004900 break;
Mike Stump1eb44332009-09-09 15:08:12 +00004901 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004902 case Decl::ObjCMethod: {
4903 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4904 if (CompoundStmt *Body = MD->getCompoundBody()) {
4905 CurMethodDef = MD;
4906 CurrentBody = Body;
4907 Body =
4908 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4909 MD->setBody(Body);
4910 CurrentBody = 0;
4911 if (PropParentMap) {
4912 delete PropParentMap;
4913 PropParentMap = 0;
4914 }
4915 InsertBlockLiteralsWithinMethod(MD);
4916 CurMethodDef = 0;
Steve Naroff8599e7a2008-12-08 16:43:47 +00004917 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004918 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004919 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004920 case Decl::ObjCImplementation: {
4921 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4922 ClassImplementation.push_back(CI);
4923 break;
4924 }
4925 case Decl::ObjCCategoryImpl: {
4926 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4927 CategoryImplementation.push_back(CI);
4928 break;
4929 }
4930 case Decl::Var: {
4931 VarDecl *VD = cast<VarDecl>(D);
4932 RewriteObjCQualifiedInterfaceTypes(VD);
4933 if (isTopLevelBlockPointerType(VD->getType()))
4934 RewriteBlockPointerDecl(VD);
4935 else if (VD->getType()->isFunctionPointerType()) {
4936 CheckFunctionPointerDecl(VD->getType(), VD);
4937 if (VD->getInit()) {
4938 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4939 RewriteCastExpr(CE);
4940 }
4941 }
4942 } else if (VD->getType()->isRecordType()) {
4943 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4944 if (RD->isCompleteDefinition())
4945 RewriteRecordBody(RD);
4946 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004947 if (VD->getInit()) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004948 GlobalVarDecl = VD;
4949 CurrentBody = VD->getInit();
4950 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4951 CurrentBody = 0;
4952 if (PropParentMap) {
4953 delete PropParentMap;
4954 PropParentMap = 0;
4955 }
4956 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4957 GlobalVarDecl = 0;
4958
4959 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00004960 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004961 RewriteCastExpr(CE);
Steve Narofffa15fd92008-10-28 20:29:00 +00004962 }
4963 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004964 break;
4965 }
4966 case Decl::TypeAlias:
4967 case Decl::Typedef: {
4968 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4969 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4970 RewriteBlockPointerDecl(TD);
4971 else if (TD->getUnderlyingType()->isFunctionPointerType())
4972 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4973 }
4974 break;
4975 }
4976 case Decl::CXXRecord:
4977 case Decl::Record: {
4978 RecordDecl *RD = cast<RecordDecl>(D);
4979 if (RD->isCompleteDefinition())
Steve Naroff3d7e7862009-12-05 15:55:59 +00004980 RewriteRecordBody(RD);
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004981 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004982 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004983 case Decl::ObjCClass: {
4984 llvm_unreachable("RewriteObjC::HandleDeclInMainFile - ObjCClassDecl");
4985 break;
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004986 }
Fariborz Jahanian02f83962011-12-05 22:59:54 +00004987 default:
4988 break;
Steve Narofffa15fd92008-10-28 20:29:00 +00004989 }
4990 // Nothing yet.
4991}
4992
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00004993void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004994 if (Diags.hasErrorOccurred())
4995 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004996
Steve Narofffa15fd92008-10-28 20:29:00 +00004997 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00004998
Steve Naroff621edce2009-04-29 16:37:50 +00004999 // Here's a great place to add any extra declarations that may be needed.
5000 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005001 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005002 E = ProtocolExprDecls.end(); I != E; ++I)
5003 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5004
Benjamin Kramerd999b372010-02-14 14:14:16 +00005005 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005006 if (ClassImplementation.size() || CategoryImplementation.size())
5007 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005008
Steve Narofffa15fd92008-10-28 20:29:00 +00005009 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5010 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005011 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005012 Rewrite.getRewriteBufferFor(MainFileID)) {
5013 //printf("Changed:\n");
5014 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5015 } else {
Benjamin Kramerd999b372010-02-14 14:14:16 +00005016 llvm::errs() << "No changes\n";
Steve Narofffa15fd92008-10-28 20:29:00 +00005017 }
Steve Narofface66252008-11-13 20:07:04 +00005018
Steve Naroff621edce2009-04-29 16:37:50 +00005019 if (ClassImplementation.size() || CategoryImplementation.size() ||
5020 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005021 // Rewrite Objective-c meta data*
5022 std::string ResultStr;
Fariborz Jahanian58457172011-12-05 18:43:13 +00005023 RewriteMetaDataIntoBuffer(ResultStr);
Steve Naroff0aab7962008-11-14 14:10:01 +00005024 // Emit metadata.
5025 *OutFile << ResultStr;
5026 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005027 OutFile->flush();
5028}
Fariborz Jahaniand5c3fa22011-12-08 18:25:15 +00005029
5030void RewriteObjCFragileABI::Initialize(ASTContext &context) {
5031 InitializeCommon(context);
5032
5033 // declaring objc_selector outside the parameter list removes a silly
5034 // scope related warning...
5035 if (IsHeader)
5036 Preamble = "#pragma once\n";
5037 Preamble += "struct objc_selector; struct objc_class;\n";
5038 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5039 Preamble += "struct objc_object *superClass; ";
5040 if (LangOpts.MicrosoftExt) {
5041 // Add a constructor for creating temporary objects.
5042 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5043 ": ";
5044 Preamble += "object(o), superClass(s) {} ";
5045 }
5046 Preamble += "};\n";
5047 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5048 Preamble += "typedef struct objc_object Protocol;\n";
5049 Preamble += "#define _REWRITER_typedef_Protocol\n";
5050 Preamble += "#endif\n";
5051 if (LangOpts.MicrosoftExt) {
5052 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5053 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5054 } else
5055 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5056 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5057 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5058 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5059 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5060 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5061 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5062 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5063 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5064 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5065 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5066 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5067 Preamble += "(const char *);\n";
5068 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5069 Preamble += "(struct objc_class *);\n";
5070 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5071 Preamble += "(const char *);\n";
5072 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
5073 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
5074 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
5075 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
5076 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
5077 Preamble += "(struct objc_class *, struct objc_object *);\n";
5078 // @synchronized hooks.
5079 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
5080 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
5081 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5082 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5083 Preamble += "struct __objcFastEnumerationState {\n\t";
5084 Preamble += "unsigned long state;\n\t";
5085 Preamble += "void **itemsPtr;\n\t";
5086 Preamble += "unsigned long *mutationsPtr;\n\t";
5087 Preamble += "unsigned long extra[5];\n};\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5089 Preamble += "#define __FASTENUMERATIONSTATE\n";
5090 Preamble += "#endif\n";
5091 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5092 Preamble += "struct __NSConstantStringImpl {\n";
5093 Preamble += " int *isa;\n";
5094 Preamble += " int flags;\n";
5095 Preamble += " char *str;\n";
5096 Preamble += " long length;\n";
5097 Preamble += "};\n";
5098 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5099 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5100 Preamble += "#else\n";
5101 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5102 Preamble += "#endif\n";
5103 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5104 Preamble += "#endif\n";
5105 // Blocks preamble.
5106 Preamble += "#ifndef BLOCK_IMPL\n";
5107 Preamble += "#define BLOCK_IMPL\n";
5108 Preamble += "struct __block_impl {\n";
5109 Preamble += " void *isa;\n";
5110 Preamble += " int Flags;\n";
5111 Preamble += " int Reserved;\n";
5112 Preamble += " void *FuncPtr;\n";
5113 Preamble += "};\n";
5114 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5115 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5116 Preamble += "extern \"C\" __declspec(dllexport) "
5117 "void _Block_object_assign(void *, const void *, const int);\n";
5118 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5119 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5120 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5121 Preamble += "#else\n";
5122 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5123 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5124 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5125 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5126 Preamble += "#endif\n";
5127 Preamble += "#endif\n";
5128 if (LangOpts.MicrosoftExt) {
5129 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5130 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5131 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5132 Preamble += "#define __attribute__(X)\n";
5133 Preamble += "#endif\n";
5134 Preamble += "#define __weak\n";
5135 }
5136 else {
5137 Preamble += "#define __block\n";
5138 Preamble += "#define __weak\n";
5139 }
5140 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5141 // as this avoids warning in any 64bit/32bit compilation model.
5142 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5143}
5144
5145/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5146/// ivar offset.
5147void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5148 std::string &Result) {
5149 if (ivar->isBitField()) {
5150 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5151 // place all bitfields at offset 0.
5152 Result += "0";
5153 } else {
5154 Result += "__OFFSETOFIVAR__(struct ";
5155 Result += ivar->getContainingInterface()->getNameAsString();
5156 if (LangOpts.MicrosoftExt)
5157 Result += "_IMPL";
5158 Result += ", ";
5159 Result += ivar->getNameAsString();
5160 Result += ")";
5161 }
5162}
5163
5164/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
5165void RewriteObjCFragileABI::RewriteObjCProtocolMetaData(
5166 ObjCProtocolDecl *PDecl, StringRef prefix,
5167 StringRef ClassName, std::string &Result) {
5168 static bool objc_protocol_methods = false;
5169
5170 // Output struct protocol_methods holder of method selector and type.
5171 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
5172 /* struct protocol_methods {
5173 SEL _cmd;
5174 char *method_types;
5175 }
5176 */
5177 Result += "\nstruct _protocol_methods {\n";
5178 Result += "\tstruct objc_selector *_cmd;\n";
5179 Result += "\tchar *method_types;\n";
5180 Result += "};\n";
5181
5182 objc_protocol_methods = true;
5183 }
5184 // Do not synthesize the protocol more than once.
5185 if (ObjCSynthesizedProtocols.count(PDecl))
5186 return;
5187
5188 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5189 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
5190 PDecl->instmeth_end());
5191 /* struct _objc_protocol_method_list {
5192 int protocol_method_count;
5193 struct protocol_methods protocols[];
5194 }
5195 */
5196 Result += "\nstatic struct {\n";
5197 Result += "\tint protocol_method_count;\n";
5198 Result += "\tstruct _protocol_methods protocol_methods[";
5199 Result += utostr(NumMethods);
5200 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
5201 Result += PDecl->getNameAsString();
5202 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
5203 "{\n\t" + utostr(NumMethods) + "\n";
5204
5205 // Output instance methods declared in this protocol.
5206 for (ObjCProtocolDecl::instmeth_iterator
5207 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5208 I != E; ++I) {
5209 if (I == PDecl->instmeth_begin())
5210 Result += "\t ,{{(struct objc_selector *)\"";
5211 else
5212 Result += "\t ,{(struct objc_selector *)\"";
5213 Result += (*I)->getSelector().getAsString();
5214 std::string MethodTypeString;
5215 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5216 Result += "\", \"";
5217 Result += MethodTypeString;
5218 Result += "\"}\n";
5219 }
5220 Result += "\t }\n};\n";
5221 }
5222
5223 // Output class methods declared in this protocol.
5224 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
5225 PDecl->classmeth_end());
5226 if (NumMethods > 0) {
5227 /* struct _objc_protocol_method_list {
5228 int protocol_method_count;
5229 struct protocol_methods protocols[];
5230 }
5231 */
5232 Result += "\nstatic struct {\n";
5233 Result += "\tint protocol_method_count;\n";
5234 Result += "\tstruct _protocol_methods protocol_methods[";
5235 Result += utostr(NumMethods);
5236 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
5237 Result += PDecl->getNameAsString();
5238 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5239 "{\n\t";
5240 Result += utostr(NumMethods);
5241 Result += "\n";
5242
5243 // Output instance methods declared in this protocol.
5244 for (ObjCProtocolDecl::classmeth_iterator
5245 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5246 I != E; ++I) {
5247 if (I == PDecl->classmeth_begin())
5248 Result += "\t ,{{(struct objc_selector *)\"";
5249 else
5250 Result += "\t ,{(struct objc_selector *)\"";
5251 Result += (*I)->getSelector().getAsString();
5252 std::string MethodTypeString;
5253 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
5254 Result += "\", \"";
5255 Result += MethodTypeString;
5256 Result += "\"}\n";
5257 }
5258 Result += "\t }\n};\n";
5259 }
5260
5261 // Output:
5262 /* struct _objc_protocol {
5263 // Objective-C 1.0 extensions
5264 struct _objc_protocol_extension *isa;
5265 char *protocol_name;
5266 struct _objc_protocol **protocol_list;
5267 struct _objc_protocol_method_list *instance_methods;
5268 struct _objc_protocol_method_list *class_methods;
5269 };
5270 */
5271 static bool objc_protocol = false;
5272 if (!objc_protocol) {
5273 Result += "\nstruct _objc_protocol {\n";
5274 Result += "\tstruct _objc_protocol_extension *isa;\n";
5275 Result += "\tchar *protocol_name;\n";
5276 Result += "\tstruct _objc_protocol **protocol_list;\n";
5277 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
5278 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
5279 Result += "};\n";
5280
5281 objc_protocol = true;
5282 }
5283
5284 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
5285 Result += PDecl->getNameAsString();
5286 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
5287 "{\n\t0, \"";
5288 Result += PDecl->getNameAsString();
5289 Result += "\", 0, ";
5290 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
5291 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5292 Result += PDecl->getNameAsString();
5293 Result += ", ";
5294 }
5295 else
5296 Result += "0, ";
5297 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
5298 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5299 Result += PDecl->getNameAsString();
5300 Result += "\n";
5301 }
5302 else
5303 Result += "0\n";
5304 Result += "};\n";
5305
5306 // Mark this protocol as having been generated.
5307 if (!ObjCSynthesizedProtocols.insert(PDecl))
5308 llvm_unreachable("protocol already synthesized");
5309
5310}
5311
5312void RewriteObjCFragileABI::RewriteObjCProtocolListMetaData(
5313 const ObjCList<ObjCProtocolDecl> &Protocols,
5314 StringRef prefix, StringRef ClassName,
5315 std::string &Result) {
5316 if (Protocols.empty()) return;
5317
5318 for (unsigned i = 0; i != Protocols.size(); i++)
5319 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
5320
5321 // Output the top lovel protocol meta-data for the class.
5322 /* struct _objc_protocol_list {
5323 struct _objc_protocol_list *next;
5324 int protocol_count;
5325 struct _objc_protocol *class_protocols[];
5326 }
5327 */
5328 Result += "\nstatic struct {\n";
5329 Result += "\tstruct _objc_protocol_list *next;\n";
5330 Result += "\tint protocol_count;\n";
5331 Result += "\tstruct _objc_protocol *class_protocols[";
5332 Result += utostr(Protocols.size());
5333 Result += "];\n} _OBJC_";
5334 Result += prefix;
5335 Result += "_PROTOCOLS_";
5336 Result += ClassName;
5337 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
5338 "{\n\t0, ";
5339 Result += utostr(Protocols.size());
5340 Result += "\n";
5341
5342 Result += "\t,{&_OBJC_PROTOCOL_";
5343 Result += Protocols[0]->getNameAsString();
5344 Result += " \n";
5345
5346 for (unsigned i = 1; i != Protocols.size(); i++) {
5347 Result += "\t ,&_OBJC_PROTOCOL_";
5348 Result += Protocols[i]->getNameAsString();
5349 Result += "\n";
5350 }
5351 Result += "\t }\n};\n";
5352}
5353
5354void RewriteObjCFragileABI::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
5355 std::string &Result) {
5356 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
5357
5358 // Explicitly declared @interface's are already synthesized.
5359 if (CDecl->isImplicitInterfaceDecl()) {
5360 // FIXME: Implementation of a class with no @interface (legacy) doese not
5361 // produce correct synthesis as yet.
5362 RewriteObjCInternalStruct(CDecl, Result);
5363 }
5364
5365 // Build _objc_ivar_list metadata for classes ivars if needed
5366 unsigned NumIvars = !IDecl->ivar_empty()
5367 ? IDecl->ivar_size()
5368 : (CDecl ? CDecl->ivar_size() : 0);
5369 if (NumIvars > 0) {
5370 static bool objc_ivar = false;
5371 if (!objc_ivar) {
5372 /* struct _objc_ivar {
5373 char *ivar_name;
5374 char *ivar_type;
5375 int ivar_offset;
5376 };
5377 */
5378 Result += "\nstruct _objc_ivar {\n";
5379 Result += "\tchar *ivar_name;\n";
5380 Result += "\tchar *ivar_type;\n";
5381 Result += "\tint ivar_offset;\n";
5382 Result += "};\n";
5383
5384 objc_ivar = true;
5385 }
5386
5387 /* struct {
5388 int ivar_count;
5389 struct _objc_ivar ivar_list[nIvars];
5390 };
5391 */
5392 Result += "\nstatic struct {\n";
5393 Result += "\tint ivar_count;\n";
5394 Result += "\tstruct _objc_ivar ivar_list[";
5395 Result += utostr(NumIvars);
5396 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
5397 Result += IDecl->getNameAsString();
5398 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
5399 "{\n\t";
5400 Result += utostr(NumIvars);
5401 Result += "\n";
5402
5403 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
5404 SmallVector<ObjCIvarDecl *, 8> IVars;
5405 if (!IDecl->ivar_empty()) {
5406 for (ObjCInterfaceDecl::ivar_iterator
5407 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
5408 IV != IVEnd; ++IV)
5409 IVars.push_back(*IV);
5410 IVI = IDecl->ivar_begin();
5411 IVE = IDecl->ivar_end();
5412 } else {
5413 IVI = CDecl->ivar_begin();
5414 IVE = CDecl->ivar_end();
5415 }
5416 Result += "\t,{{\"";
5417 Result += (*IVI)->getNameAsString();
5418 Result += "\", \"";
5419 std::string TmpString, StrEncoding;
5420 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5421 QuoteDoublequotes(TmpString, StrEncoding);
5422 Result += StrEncoding;
5423 Result += "\", ";
5424 RewriteIvarOffsetComputation(*IVI, Result);
5425 Result += "}\n";
5426 for (++IVI; IVI != IVE; ++IVI) {
5427 Result += "\t ,{\"";
5428 Result += (*IVI)->getNameAsString();
5429 Result += "\", \"";
5430 std::string TmpString, StrEncoding;
5431 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
5432 QuoteDoublequotes(TmpString, StrEncoding);
5433 Result += StrEncoding;
5434 Result += "\", ";
5435 RewriteIvarOffsetComputation((*IVI), Result);
5436 Result += "}\n";
5437 }
5438
5439 Result += "\t }\n};\n";
5440 }
5441
5442 // Build _objc_method_list for class's instance methods if needed
5443 SmallVector<ObjCMethodDecl *, 32>
5444 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5445
5446 // If any of our property implementations have associated getters or
5447 // setters, produce metadata for them as well.
5448 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5449 PropEnd = IDecl->propimpl_end();
5450 Prop != PropEnd; ++Prop) {
5451 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5452 continue;
5453 if (!(*Prop)->getPropertyIvarDecl())
5454 continue;
5455 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5456 if (!PD)
5457 continue;
5458 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5459 if (!Getter->isDefined())
5460 InstanceMethods.push_back(Getter);
5461 if (PD->isReadOnly())
5462 continue;
5463 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5464 if (!Setter->isDefined())
5465 InstanceMethods.push_back(Setter);
5466 }
5467 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5468 true, "", IDecl->getName(), Result);
5469
5470 // Build _objc_method_list for class's class methods if needed
5471 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5472 false, "", IDecl->getName(), Result);
5473
5474 // Protocols referenced in class declaration?
5475 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
5476 "CLASS", CDecl->getName(), Result);
5477
5478 // Declaration of class/meta-class metadata
5479 /* struct _objc_class {
5480 struct _objc_class *isa; // or const char *root_class_name when metadata
5481 const char *super_class_name;
5482 char *name;
5483 long version;
5484 long info;
5485 long instance_size;
5486 struct _objc_ivar_list *ivars;
5487 struct _objc_method_list *methods;
5488 struct objc_cache *cache;
5489 struct objc_protocol_list *protocols;
5490 const char *ivar_layout;
5491 struct _objc_class_ext *ext;
5492 };
5493 */
5494 static bool objc_class = false;
5495 if (!objc_class) {
5496 Result += "\nstruct _objc_class {\n";
5497 Result += "\tstruct _objc_class *isa;\n";
5498 Result += "\tconst char *super_class_name;\n";
5499 Result += "\tchar *name;\n";
5500 Result += "\tlong version;\n";
5501 Result += "\tlong info;\n";
5502 Result += "\tlong instance_size;\n";
5503 Result += "\tstruct _objc_ivar_list *ivars;\n";
5504 Result += "\tstruct _objc_method_list *methods;\n";
5505 Result += "\tstruct objc_cache *cache;\n";
5506 Result += "\tstruct _objc_protocol_list *protocols;\n";
5507 Result += "\tconst char *ivar_layout;\n";
5508 Result += "\tstruct _objc_class_ext *ext;\n";
5509 Result += "};\n";
5510 objc_class = true;
5511 }
5512
5513 // Meta-class metadata generation.
5514 ObjCInterfaceDecl *RootClass = 0;
5515 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
5516 while (SuperClass) {
5517 RootClass = SuperClass;
5518 SuperClass = SuperClass->getSuperClass();
5519 }
5520 SuperClass = CDecl->getSuperClass();
5521
5522 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
5523 Result += CDecl->getNameAsString();
5524 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
5525 "{\n\t(struct _objc_class *)\"";
5526 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
5527 Result += "\"";
5528
5529 if (SuperClass) {
5530 Result += ", \"";
5531 Result += SuperClass->getNameAsString();
5532 Result += "\", \"";
5533 Result += CDecl->getNameAsString();
5534 Result += "\"";
5535 }
5536 else {
5537 Result += ", 0, \"";
5538 Result += CDecl->getNameAsString();
5539 Result += "\"";
5540 }
5541 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
5542 // 'info' field is initialized to CLS_META(2) for metaclass
5543 Result += ", 0,2, sizeof(struct _objc_class), 0";
5544 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5545 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
5546 Result += IDecl->getNameAsString();
5547 Result += "\n";
5548 }
5549 else
5550 Result += ", 0\n";
5551 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5552 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
5553 Result += CDecl->getNameAsString();
5554 Result += ",0,0\n";
5555 }
5556 else
5557 Result += "\t,0,0,0,0\n";
5558 Result += "};\n";
5559
5560 // class metadata generation.
5561 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
5562 Result += CDecl->getNameAsString();
5563 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
5564 "{\n\t&_OBJC_METACLASS_";
5565 Result += CDecl->getNameAsString();
5566 if (SuperClass) {
5567 Result += ", \"";
5568 Result += SuperClass->getNameAsString();
5569 Result += "\", \"";
5570 Result += CDecl->getNameAsString();
5571 Result += "\"";
5572 }
5573 else {
5574 Result += ", 0, \"";
5575 Result += CDecl->getNameAsString();
5576 Result += "\"";
5577 }
5578 // 'info' field is initialized to CLS_CLASS(1) for class
5579 Result += ", 0,1";
5580 if (!ObjCSynthesizedStructs.count(CDecl))
5581 Result += ",0";
5582 else {
5583 // class has size. Must synthesize its size.
5584 Result += ",sizeof(struct ";
5585 Result += CDecl->getNameAsString();
5586 if (LangOpts.MicrosoftExt)
5587 Result += "_IMPL";
5588 Result += ")";
5589 }
5590 if (NumIvars > 0) {
5591 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
5592 Result += CDecl->getNameAsString();
5593 Result += "\n\t";
5594 }
5595 else
5596 Result += ",0";
5597 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5598 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
5599 Result += CDecl->getNameAsString();
5600 Result += ", 0\n\t";
5601 }
5602 else
5603 Result += ",0,0";
5604 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
5605 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
5606 Result += CDecl->getNameAsString();
5607 Result += ", 0,0\n";
5608 }
5609 else
5610 Result += ",0,0,0\n";
5611 Result += "};\n";
5612}
5613
5614void RewriteObjCFragileABI::RewriteMetaDataIntoBuffer(std::string &Result) {
5615 int ClsDefCount = ClassImplementation.size();
5616 int CatDefCount = CategoryImplementation.size();
5617
5618 // For each implemented class, write out all its meta data.
5619 for (int i = 0; i < ClsDefCount; i++)
5620 RewriteObjCClassMetaData(ClassImplementation[i], Result);
5621
5622 // For each implemented category, write out all its meta data.
5623 for (int i = 0; i < CatDefCount; i++)
5624 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
5625
5626 // Write objc_symtab metadata
5627 /*
5628 struct _objc_symtab
5629 {
5630 long sel_ref_cnt;
5631 SEL *refs;
5632 short cls_def_cnt;
5633 short cat_def_cnt;
5634 void *defs[cls_def_cnt + cat_def_cnt];
5635 };
5636 */
5637
5638 Result += "\nstruct _objc_symtab {\n";
5639 Result += "\tlong sel_ref_cnt;\n";
5640 Result += "\tSEL *refs;\n";
5641 Result += "\tshort cls_def_cnt;\n";
5642 Result += "\tshort cat_def_cnt;\n";
5643 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
5644 Result += "};\n\n";
5645
5646 Result += "static struct _objc_symtab "
5647 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
5648 Result += "\t0, 0, " + utostr(ClsDefCount)
5649 + ", " + utostr(CatDefCount) + "\n";
5650 for (int i = 0; i < ClsDefCount; i++) {
5651 Result += "\t,&_OBJC_CLASS_";
5652 Result += ClassImplementation[i]->getNameAsString();
5653 Result += "\n";
5654 }
5655
5656 for (int i = 0; i < CatDefCount; i++) {
5657 Result += "\t,&_OBJC_CATEGORY_";
5658 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
5659 Result += "_";
5660 Result += CategoryImplementation[i]->getNameAsString();
5661 Result += "\n";
5662 }
5663
5664 Result += "};\n\n";
5665
5666 // Write objc_module metadata
5667
5668 /*
5669 struct _objc_module {
5670 long version;
5671 long size;
5672 const char *name;
5673 struct _objc_symtab *symtab;
5674 }
5675 */
5676
5677 Result += "\nstruct _objc_module {\n";
5678 Result += "\tlong version;\n";
5679 Result += "\tlong size;\n";
5680 Result += "\tconst char *name;\n";
5681 Result += "\tstruct _objc_symtab *symtab;\n";
5682 Result += "};\n\n";
5683 Result += "static struct _objc_module "
5684 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
5685 Result += "\t" + utostr(OBJC_ABI_VERSION) +
5686 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
5687 Result += "};\n\n";
5688
5689 if (LangOpts.MicrosoftExt) {
5690 if (ProtocolExprDecls.size()) {
5691 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
5692 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
5693 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
5694 E = ProtocolExprDecls.end(); I != E; ++I) {
5695 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
5696 Result += (*I)->getNameAsString();
5697 Result += " = &_OBJC_PROTOCOL_";
5698 Result += (*I)->getNameAsString();
5699 Result += ";\n";
5700 }
5701 Result += "#pragma data_seg(pop)\n\n";
5702 }
5703 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
5704 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
5705 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
5706 Result += "&_OBJC_MODULES;\n";
5707 Result += "#pragma data_seg(pop)\n\n";
5708 }
5709}
5710
5711/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
5712/// implementation.
5713void RewriteObjCFragileABI::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
5714 std::string &Result) {
5715 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
5716 // Find category declaration for this implementation.
5717 ObjCCategoryDecl *CDecl;
5718 for (CDecl = ClassDecl->getCategoryList(); CDecl;
5719 CDecl = CDecl->getNextClassCategory())
5720 if (CDecl->getIdentifier() == IDecl->getIdentifier())
5721 break;
5722
5723 std::string FullCategoryName = ClassDecl->getNameAsString();
5724 FullCategoryName += '_';
5725 FullCategoryName += IDecl->getNameAsString();
5726
5727 // Build _objc_method_list for class's instance methods if needed
5728 SmallVector<ObjCMethodDecl *, 32>
5729 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
5730
5731 // If any of our property implementations have associated getters or
5732 // setters, produce metadata for them as well.
5733 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
5734 PropEnd = IDecl->propimpl_end();
5735 Prop != PropEnd; ++Prop) {
5736 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
5737 continue;
5738 if (!(*Prop)->getPropertyIvarDecl())
5739 continue;
5740 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
5741 if (!PD)
5742 continue;
5743 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
5744 InstanceMethods.push_back(Getter);
5745 if (PD->isReadOnly())
5746 continue;
5747 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
5748 InstanceMethods.push_back(Setter);
5749 }
5750 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
5751 true, "CATEGORY_", FullCategoryName.c_str(),
5752 Result);
5753
5754 // Build _objc_method_list for class's class methods if needed
5755 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
5756 false, "CATEGORY_", FullCategoryName.c_str(),
5757 Result);
5758
5759 // Protocols referenced in class declaration?
5760 // Null CDecl is case of a category implementation with no category interface
5761 if (CDecl)
5762 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
5763 FullCategoryName, Result);
5764 /* struct _objc_category {
5765 char *category_name;
5766 char *class_name;
5767 struct _objc_method_list *instance_methods;
5768 struct _objc_method_list *class_methods;
5769 struct _objc_protocol_list *protocols;
5770 // Objective-C 1.0 extensions
5771 uint32_t size; // sizeof (struct _objc_category)
5772 struct _objc_property_list *instance_properties; // category's own
5773 // @property decl.
5774 };
5775 */
5776
5777 static bool objc_category = false;
5778 if (!objc_category) {
5779 Result += "\nstruct _objc_category {\n";
5780 Result += "\tchar *category_name;\n";
5781 Result += "\tchar *class_name;\n";
5782 Result += "\tstruct _objc_method_list *instance_methods;\n";
5783 Result += "\tstruct _objc_method_list *class_methods;\n";
5784 Result += "\tstruct _objc_protocol_list *protocols;\n";
5785 Result += "\tunsigned int size;\n";
5786 Result += "\tstruct _objc_property_list *instance_properties;\n";
5787 Result += "};\n";
5788 objc_category = true;
5789 }
5790 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
5791 Result += FullCategoryName;
5792 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
5793 Result += IDecl->getNameAsString();
5794 Result += "\"\n\t, \"";
5795 Result += ClassDecl->getNameAsString();
5796 Result += "\"\n";
5797
5798 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
5799 Result += "\t, (struct _objc_method_list *)"
5800 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
5801 Result += FullCategoryName;
5802 Result += "\n";
5803 }
5804 else
5805 Result += "\t, 0\n";
5806 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
5807 Result += "\t, (struct _objc_method_list *)"
5808 "&_OBJC_CATEGORY_CLASS_METHODS_";
5809 Result += FullCategoryName;
5810 Result += "\n";
5811 }
5812 else
5813 Result += "\t, 0\n";
5814
5815 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
5816 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
5817 Result += FullCategoryName;
5818 Result += "\n";
5819 }
5820 else
5821 Result += "\t, 0\n";
5822 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
5823}
5824
5825// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
5826/// class methods.
5827template<typename MethodIterator>
5828void RewriteObjCFragileABI::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
5829 MethodIterator MethodEnd,
5830 bool IsInstanceMethod,
5831 StringRef prefix,
5832 StringRef ClassName,
5833 std::string &Result) {
5834 if (MethodBegin == MethodEnd) return;
5835
5836 if (!objc_impl_method) {
5837 /* struct _objc_method {
5838 SEL _cmd;
5839 char *method_types;
5840 void *_imp;
5841 }
5842 */
5843 Result += "\nstruct _objc_method {\n";
5844 Result += "\tSEL _cmd;\n";
5845 Result += "\tchar *method_types;\n";
5846 Result += "\tvoid *_imp;\n";
5847 Result += "};\n";
5848
5849 objc_impl_method = true;
5850 }
5851
5852 // Build _objc_method_list for class's methods if needed
5853
5854 /* struct {
5855 struct _objc_method_list *next_method;
5856 int method_count;
5857 struct _objc_method method_list[];
5858 }
5859 */
5860 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
5861 Result += "\nstatic struct {\n";
5862 Result += "\tstruct _objc_method_list *next_method;\n";
5863 Result += "\tint method_count;\n";
5864 Result += "\tstruct _objc_method method_list[";
5865 Result += utostr(NumMethods);
5866 Result += "];\n} _OBJC_";
5867 Result += prefix;
5868 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
5869 Result += "_METHODS_";
5870 Result += ClassName;
5871 Result += " __attribute__ ((used, section (\"__OBJC, __";
5872 Result += IsInstanceMethod ? "inst" : "cls";
5873 Result += "_meth\")))= ";
5874 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
5875
5876 Result += "\t,{{(SEL)\"";
5877 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5878 std::string MethodTypeString;
5879 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5880 Result += "\", \"";
5881 Result += MethodTypeString;
5882 Result += "\", (void *)";
5883 Result += MethodInternalNames[*MethodBegin];
5884 Result += "}\n";
5885 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
5886 Result += "\t ,{(SEL)\"";
5887 Result += (*MethodBegin)->getSelector().getAsString().c_str();
5888 std::string MethodTypeString;
5889 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
5890 Result += "\", \"";
5891 Result += MethodTypeString;
5892 Result += "\", (void *)";
5893 Result += MethodInternalNames[*MethodBegin];
5894 Result += "}\n";
5895 }
5896 Result += "\t }\n};\n";
5897}
5898
5899Stmt *RewriteObjCFragileABI::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
5900 SourceRange OldRange = IV->getSourceRange();
5901 Expr *BaseExpr = IV->getBase();
5902
5903 // Rewrite the base, but without actually doing replaces.
5904 {
5905 DisableReplaceStmtScope S(*this);
5906 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
5907 IV->setBase(BaseExpr);
5908 }
5909
5910 ObjCIvarDecl *D = IV->getDecl();
5911
5912 Expr *Replacement = IV;
5913 if (CurMethodDef) {
5914 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5915 const ObjCInterfaceType *iFaceDecl =
5916 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5917 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
5918 // lookup which class implements the instance variable.
5919 ObjCInterfaceDecl *clsDeclared = 0;
5920 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5921 clsDeclared);
5922 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5923
5924 // Synthesize an explicit cast to gain access to the ivar.
5925 std::string RecName = clsDeclared->getIdentifier()->getName();
5926 RecName += "_IMPL";
5927 IdentifierInfo *II = &Context->Idents.get(RecName);
5928 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5929 SourceLocation(), SourceLocation(),
5930 II);
5931 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5932 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5933 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5934 CK_BitCast,
5935 IV->getBase());
5936 // Don't forget the parens to enforce the proper binding.
5937 ParenExpr *PE = new (Context) ParenExpr(OldRange.getBegin(),
5938 OldRange.getEnd(),
5939 castExpr);
5940 if (IV->isFreeIvar() &&
5941 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
5942 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
5943 IV->getLocation(),
5944 D->getType(),
5945 VK_LValue, OK_Ordinary);
5946 Replacement = ME;
5947 } else {
5948 IV->setBase(PE);
5949 }
5950 }
5951 } else { // we are outside a method.
5952 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
5953
5954 // Explicit ivar refs need to have a cast inserted.
5955 // FIXME: consider sharing some of this code with the code above.
5956 if (BaseExpr->getType()->isObjCObjectPointerType()) {
5957 const ObjCInterfaceType *iFaceDecl =
5958 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
5959 // lookup which class implements the instance variable.
5960 ObjCInterfaceDecl *clsDeclared = 0;
5961 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
5962 clsDeclared);
5963 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
5964
5965 // Synthesize an explicit cast to gain access to the ivar.
5966 std::string RecName = clsDeclared->getIdentifier()->getName();
5967 RecName += "_IMPL";
5968 IdentifierInfo *II = &Context->Idents.get(RecName);
5969 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5970 SourceLocation(), SourceLocation(),
5971 II);
5972 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
5973 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5974 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
5975 CK_BitCast,
5976 IV->getBase());
5977 // Don't forget the parens to enforce the proper binding.
5978 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
5979 IV->getBase()->getLocEnd(), castExpr);
5980 // Cannot delete IV->getBase(), since PE points to it.
5981 // Replace the old base with the cast. This is important when doing
5982 // embedded rewrites. For example, [newInv->_container addObject:0].
5983 IV->setBase(PE);
5984 }
5985 }
5986
5987 ReplaceStmtWithRange(IV, Replacement, OldRange);
5988 return Replacement;
5989}
5990