blob: b90babda5c522194c8e26765ea4f3134af13e0ff [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
Eli Friedman39d7c4d2009-05-18 22:50:54 +000014#include "clang/Frontend/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"
Chris Lattner77cd2a02007-10-11 00:43:27 +000029using namespace clang;
Chris Lattner158ecb92007-10-25 17:07:24 +000030using llvm::utostr;
Chris Lattner77cd2a02007-10-11 00:43:27 +000031
Chris Lattner77cd2a02007-10-11 00:43:27 +000032namespace {
Steve Naroffb29b4272008-04-14 22:03:09 +000033 class RewriteObjC : public ASTConsumer {
Fariborz Jahanian73e437b2009-12-23 21:18:41 +000034 enum {
35 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
36 block, ... */
37 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
38 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
39 __block variable */
40 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
41 helpers */
42 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
43 support routines */
44 BLOCK_BYREF_CURRENT_MAX = 256
45 };
46
47 enum {
48 BLOCK_NEEDS_FREE = (1 << 24),
49 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
50 BLOCK_HAS_CXX_OBJ = (1 << 26),
51 BLOCK_IS_GC = (1 << 27),
52 BLOCK_IS_GLOBAL = (1 << 28),
53 BLOCK_HAS_DESCRIPTOR = (1 << 29)
54 };
55
Chris Lattner2c64b7b2007-10-16 21:07:07 +000056 Rewriter Rewrite;
Chris Lattnere365c502007-11-30 22:25:36 +000057 Diagnostic &Diags;
Steve Naroff4f943c22008-03-10 20:43:59 +000058 const LangOptions &LangOpts;
Steve Narofff69cc5d2008-01-30 19:17:43 +000059 unsigned RewriteFailedDiag;
Steve Naroff8c565152008-12-05 17:03:39 +000060 unsigned TryFinallyContainsReturnDiag;
Mike Stump1eb44332009-09-09 15:08:12 +000061
Chris Lattner01c57482007-10-17 22:35:30 +000062 ASTContext *Context;
Chris Lattner77cd2a02007-10-11 00:43:27 +000063 SourceManager *SM;
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +000064 TranslationUnitDecl *TUDecl;
Chris Lattner2b2453a2009-01-17 06:22:33 +000065 FileID MainFileID;
Chris Lattner26de4652007-12-02 01:13:47 +000066 const char *MainFileStart, *MainFileEnd;
Chris Lattner2c64b7b2007-10-16 21:07:07 +000067 SourceLocation LastIncLoc;
Mike Stump1eb44332009-09-09 15:08:12 +000068
Ted Kremeneka526c5c2008-01-07 19:49:32 +000069 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
70 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
71 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Narofffbfe8252008-05-06 18:26:51 +000072 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremeneka526c5c2008-01-07 19:49:32 +000073 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
74 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +000075 llvm::SmallVector<Stmt *, 32> Stmts;
76 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroff621edce2009-04-29 16:37:50 +000077 // Remember all the @protocol(<expr>) expressions.
78 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +000079
80 llvm::DenseSet<uint64_t> CopyDestroyCache;
81
Steve Naroffd82a9ab2008-03-15 00:55:56 +000082 unsigned NumObjCStringLiterals;
Mike Stump1eb44332009-09-09 15:08:12 +000083
Steve Naroffebf2b562007-10-23 23:50:29 +000084 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +000085 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +000086 FunctionDecl *MsgSendStretFunctionDecl;
87 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanianacb49772007-12-03 21:26:48 +000088 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffebf2b562007-10-23 23:50:29 +000089 FunctionDecl *GetClassFunctionDecl;
Steve Naroff9bcb5fc2007-12-07 03:50:46 +000090 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff934f2762007-10-24 22:48:43 +000091 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff96984642007-11-08 14:30:50 +000092 FunctionDecl *CFStringFunctionDecl;
Steve Naroffc0a123c2008-03-11 17:37:02 +000093 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump1eb44332009-09-09 15:08:12 +000094
Steve Naroffbeaf2992007-11-03 11:27:19 +000095 // ObjC string constant support.
Steve Naroff248a7532008-04-15 22:42:06 +000096 VarDecl *ConstantStringClassReference;
Steve Naroffbeaf2992007-11-03 11:27:19 +000097 RecordDecl *NSStringRecord;
Mike Stump1eb44332009-09-09 15:08:12 +000098
Fariborz Jahanianb586cce2008-01-16 00:09:11 +000099 // ObjC foreach break/continue generation support.
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000100 int BcLabelCount;
Mike Stump1eb44332009-09-09 15:08:12 +0000101
Steve Naroff874e2322007-11-15 10:28:18 +0000102 // Needed for super.
Steve Naroff54055232008-10-27 17:20:55 +0000103 ObjCMethodDecl *CurMethodDef;
Steve Naroff874e2322007-11-15 10:28:18 +0000104 RecordDecl *SuperStructDecl;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000105 RecordDecl *ConstantStringDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000106
Steve Naroff621edce2009-04-29 16:37:50 +0000107 TypeDecl *ProtocolTypeDecl;
108 QualType getProtocolType();
Mike Stump1eb44332009-09-09 15:08:12 +0000109
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000110 // Needed for header files being rewritten
111 bool IsHeader;
Mike Stump1eb44332009-09-09 15:08:12 +0000112
Steve Naroffa7b402d2008-03-28 22:26:09 +0000113 std::string InFileName;
Eli Friedman66d6f042009-05-18 22:20:00 +0000114 llvm::raw_ostream* OutFile;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000115
116 bool SilenceRewriteMacroWarning;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000117 bool objc_impl_method;
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000118
Steve Naroffba92b2e2008-03-27 22:29:16 +0000119 std::string Preamble;
Steve Naroff54055232008-10-27 17:20:55 +0000120
121 // Block expressions.
122 llvm::SmallVector<BlockExpr *, 32> Blocks;
123 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
124 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump1eb44332009-09-09 15:08:12 +0000125
Steve Naroff54055232008-10-27 17:20:55 +0000126 // Block related declarations.
127 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
128 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000129 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
Steve Naroff54055232008-10-27 17:20:55 +0000130 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
131
132 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
133
Steve Naroffc77a6362008-12-04 16:24:46 +0000134 // This maps a property to it's assignment statement.
135 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff8599e7a2008-12-08 16:43:47 +0000136 // This maps a property to it's synthesied message expression.
137 // This allows us to rewrite chained getters (e.g. o.a.b.c).
138 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump1eb44332009-09-09 15:08:12 +0000139
Steve Naroff4c3580e2008-12-04 23:50:32 +0000140 // This maps an original source AST to it's rewritten form. This allows
141 // us to avoid rewriting the same node twice (which is very uncommon).
142 // This is needed to support some of the exotic property rewriting.
143 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Naroff15f081d2008-12-03 00:56:33 +0000144
Steve Naroff54055232008-10-27 17:20:55 +0000145 FunctionDecl *CurFunctionDef;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000146 FunctionDecl *CurFunctionDeclToDeclareForBlock;
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000147 VarDecl *GlobalVarDecl;
Mike Stump1eb44332009-09-09 15:08:12 +0000148
Steve Naroffb619d952008-12-09 12:56:34 +0000149 bool DisableReplaceStmt;
Mike Stump1eb44332009-09-09 15:08:12 +0000150
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +0000151 static const int OBJC_ABI_VERSION =7 ;
Chris Lattner77cd2a02007-10-11 00:43:27 +0000152 public:
Ted Kremeneke3a61982008-05-31 20:11:04 +0000153 virtual void Initialize(ASTContext &context);
154
Chris Lattnerf04da132007-10-24 17:06:59 +0000155 // Top Level Driver code.
Chris Lattner682bf922009-03-29 16:50:03 +0000156 virtual void HandleTopLevelDecl(DeclGroupRef D) {
157 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
158 HandleTopLevelSingleDecl(*I);
159 }
160 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000161 void HandleDeclInMainFile(Decl *D);
Eli Friedman66d6f042009-05-18 22:20:00 +0000162 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000163 Diagnostic &D, const LangOptions &LOpts,
164 bool silenceMacroWarn);
Ted Kremeneke452e0f2008-08-08 04:15:52 +0000165
166 ~RewriteObjC() {}
Mike Stump1eb44332009-09-09 15:08:12 +0000167
Chris Lattnerdacbc5d2009-03-28 04:11:33 +0000168 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump1eb44332009-09-09 15:08:12 +0000169
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000170 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000171 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump1eb44332009-09-09 15:08:12 +0000172
Steve Naroff4c3580e2008-12-04 23:50:32 +0000173 if (ReplacingStmt)
174 return; // We can't rewrite the same node twice.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000175
Steve Naroffb619d952008-12-09 12:56:34 +0000176 if (DisableReplaceStmt)
177 return; // Used when rewriting the assignment of a property setter.
178
Steve Naroff4c3580e2008-12-04 23:50:32 +0000179 // If replacement succeeded or warning disabled return with no warning.
Fariborz Jahanian88906cd2010-02-05 16:43:40 +0000180 if (!Rewrite.ReplaceStmt(Old, New)) {
Steve Naroff4c3580e2008-12-04 23:50:32 +0000181 ReplacedNodes[Old] = New;
182 return;
183 }
184 if (SilenceRewriteMacroWarning)
185 return;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000186 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
187 << Old->getSourceRange();
Chris Lattnerdcbc5b02008-01-31 19:37:57 +0000188 }
Steve Naroffb619d952008-12-09 12:56:34 +0000189
190 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
191 // Measaure the old text.
192 int Size = Rewrite.getRangeSize(SrcRange);
193 if (Size == -1) {
194 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
195 << Old->getSourceRange();
196 return;
197 }
198 // Get the new text.
199 std::string SStr;
200 llvm::raw_string_ostream S(SStr);
Chris Lattnere4f21422009-06-30 01:26:17 +0000201 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroffb619d952008-12-09 12:56:34 +0000202 const std::string &Str = S.str();
203
204 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000205 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroffb619d952008-12-09 12:56:34 +0000206 ReplacedNodes[Old] = New;
207 return;
208 }
209 if (SilenceRewriteMacroWarning)
210 return;
211 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
212 << Old->getSourceRange();
213 }
214
Steve Naroffba92b2e2008-03-27 22:29:16 +0000215 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
216 bool InsertAfter = true) {
Chris Lattneraadaf782008-01-31 19:51:04 +0000217 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000218 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
219 InsertAfter) ||
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000220 SilenceRewriteMacroWarning)
221 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000222
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000223 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
224 }
Mike Stump1eb44332009-09-09 15:08:12 +0000225
Chris Lattneraadaf782008-01-31 19:51:04 +0000226 void RemoveText(SourceLocation Loc, unsigned StrLen) {
227 // If removal succeeded or warning disabled return with no warning.
228 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
229 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000230
Chris Lattneraadaf782008-01-31 19:51:04 +0000231 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
232 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000233
Chris Lattneraadaf782008-01-31 19:51:04 +0000234 void ReplaceText(SourceLocation Start, unsigned OrigLength,
235 const char *NewStr, unsigned NewLength) {
236 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbard7407dc2009-08-19 19:10:30 +0000237 if (!Rewrite.ReplaceText(Start, OrigLength,
238 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattneraadaf782008-01-31 19:51:04 +0000239 SilenceRewriteMacroWarning)
240 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000241
Chris Lattneraadaf782008-01-31 19:51:04 +0000242 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
243 }
Mike Stump1eb44332009-09-09 15:08:12 +0000244
Chris Lattnerf04da132007-10-24 17:06:59 +0000245 // Syntactic Rewriting.
Steve Naroffab972d32007-11-04 22:37:50 +0000246 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000247 void RewriteInclude();
Chris Lattnerf04da132007-10-24 17:06:59 +0000248 void RewriteTabs();
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000249 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffa0876e82008-12-02 17:36:43 +0000250 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
251 ObjCImplementationDecl *IMD,
252 ObjCCategoryImplDecl *CID);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000253 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor4afa39d2009-01-20 01:17:11 +0000254 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000255 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +0000256 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
257 ValueDecl *VD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000258 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
259 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
260 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
261 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000262 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff09b266e2007-10-30 23:14:51 +0000263 void RewriteFunctionDecl(FunctionDecl *FD);
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000264 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000265 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff4f95b752008-07-29 18:15:38 +0000266 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroffd5255f52007-11-01 13:24:47 +0000267 bool needToScanForQualifiers(QualType T);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000268 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +0000269 QualType getSuperStructType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000270 QualType getConstantStringStructType();
Steve Naroffbaf58c32008-05-31 14:15:04 +0000271 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump1eb44332009-09-09 15:08:12 +0000272
Chris Lattnerf04da132007-10-24 17:06:59 +0000273 // Expression Rewriting.
Steve Narofff3473a72007-11-09 15:20:18 +0000274 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroffc77a6362008-12-04 16:24:46 +0000275 void CollectPropertySetters(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000276
Steve Naroff8599e7a2008-12-08 16:43:47 +0000277 Stmt *CurrentBody;
278 ParentMap *PropParentMap; // created lazily.
Mike Stump1eb44332009-09-09 15:08:12 +0000279
Chris Lattnere64b7772007-10-24 16:57:36 +0000280 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +0000281 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart,
282 bool &replaced);
283 Stmt *RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced);
Steve Naroffc77a6362008-12-04 16:24:46 +0000284 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump1eb44332009-09-09 15:08:12 +0000285 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroffb619d952008-12-09 12:56:34 +0000286 SourceRange SrcRange);
Steve Naroffb42f8412007-11-05 14:50:49 +0000287 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattnere64b7772007-10-24 16:57:36 +0000288 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffbeaf2992007-11-03 11:27:19 +0000289 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +0000290 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffb85e77a2009-12-05 21:43:12 +0000291 void WarnAboutReturnGotoStmts(Stmt *S);
292 void HasReturnStmts(Stmt *S, bool &hasReturns);
293 void RewriteTryReturnStmts(Stmt *S);
294 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000295 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +0000296 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000297 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
298 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
299 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattner338d1e22008-01-31 05:10:40 +0000300 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
301 SourceLocation OrigEnd);
Mike Stump1eb44332009-09-09 15:08:12 +0000302 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff934f2762007-10-24 22:48:43 +0000303 Expr **args, unsigned nargs);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000304 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +0000305 Stmt *RewriteBreakStmt(BreakStmt *S);
306 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +0000307 void SynthCountByEnumWithState(std::string &buf);
Mike Stump1eb44332009-09-09 15:08:12 +0000308
Steve Naroff09b266e2007-10-30 23:14:51 +0000309 void SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +0000310 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000311 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +0000312 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +0000313 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +0000314 void SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +0000315 void SynthGetMetaClassFunctionDecl();
Fariborz Jahaniana70711b2007-12-04 21:47:40 +0000316 void SynthSelGetUidFunctionDecl();
Steve Naroffc0a123c2008-03-11 17:37:02 +0000317 void SynthSuperContructorFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000318
Chris Lattnerf04da132007-10-24 17:06:59 +0000319 // Metadata emission.
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000320 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000321 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000322
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000323 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +0000324 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000325
Douglas Gregor653f1b12009-04-23 01:02:12 +0000326 template<typename MethodIterator>
327 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
328 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +0000329 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +0000330 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +0000331 const char *ClassName,
332 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000333
Steve Naroff621edce2009-04-29 16:37:50 +0000334 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
335 const char *prefix,
336 const char *ClassName,
337 std::string &Result);
338 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump1eb44332009-09-09 15:08:12 +0000339 const char *prefix,
Steve Naroff621edce2009-04-29 16:37:50 +0000340 const char *ClassName,
341 std::string &Result);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000342 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000343 std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000344 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
345 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +0000346 std::string &Result);
Steve Narofface66252008-11-13 20:07:04 +0000347 void RewriteImplementations();
348 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump1eb44332009-09-09 15:08:12 +0000349
Steve Naroff54055232008-10-27 17:20:55 +0000350 // Block rewriting.
Mike Stump1eb44332009-09-09 15:08:12 +0000351 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff54055232008-10-27 17:20:55 +0000352 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump1eb44332009-09-09 15:08:12 +0000353
Steve Naroff54055232008-10-27 17:20:55 +0000354 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
355 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump1eb44332009-09-09 15:08:12 +0000356
357 // Block specific rewrite rules.
Steve Naroff54055232008-10-27 17:20:55 +0000358 void RewriteBlockCall(CallExpr *Exp);
359 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000360 void RewriteByRefVar(VarDecl *VD);
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +0000361 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +0000362 Stmt *RewriteBlockDeclRefExpr(Expr *VD);
Steve Naroff54055232008-10-27 17:20:55 +0000363 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump1eb44332009-09-09 15:08:12 +0000364
365 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000366 const char *funcName, std::string Tag);
Mike Stump1eb44332009-09-09 15:08:12 +0000367 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff54055232008-10-27 17:20:55 +0000368 const char *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,
373 int i, const char *funcName,
374 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,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000377 const char *FunName);
Steve Naroff3d7e7862009-12-05 15:55:59 +0000378 void RewriteRecordBody(RecordDecl *RD);
Mike Stump1eb44332009-09-09 15:08:12 +0000379
Steve Naroff54055232008-10-27 17:20:55 +0000380 void CollectBlockDeclRefInfo(BlockExpr *Exp);
381 void GetBlockCallExprs(Stmt *S);
382 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump1eb44332009-09-09 15:08:12 +0000383
Steve Naroff54055232008-10-27 17:20:55 +0000384 // We avoid calling Type::isBlockPointerType(), since it operates on the
385 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000386 bool isTopLevelBlockPointerType(QualType T) {
387 return isa<BlockPointerType>(T);
388 }
Mike Stump1eb44332009-09-09 15:08:12 +0000389
Steve Naroff54055232008-10-27 17:20:55 +0000390 // FIXME: This predicate seems like it would be useful to add to ASTContext.
391 bool isObjCType(QualType T) {
392 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
393 return false;
Mike Stump1eb44332009-09-09 15:08:12 +0000394
Steve Naroff54055232008-10-27 17:20:55 +0000395 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump1eb44332009-09-09 15:08:12 +0000396
Steve Naroff54055232008-10-27 17:20:55 +0000397 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
398 OCT == Context->getCanonicalType(Context->getObjCClassType()))
399 return true;
Mike Stump1eb44332009-09-09 15:08:12 +0000400
Ted Kremenek6217b802009-07-29 21:53:49 +0000401 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump1eb44332009-09-09 15:08:12 +0000402 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Naroffd1b3c2d2009-06-17 22:40:22 +0000403 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff54055232008-10-27 17:20:55 +0000404 return true;
405 }
406 return false;
407 }
408 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek8189cde2009-02-07 01:47:29 +0000409 void GetExtentOfArgList(const char *Name, const char *&LParen,
410 const char *&RParen);
Steve Naroffb2f9e512008-11-03 23:29:32 +0000411 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump1eb44332009-09-09 15:08:12 +0000412
Steve Narofffa15fd92008-10-28 20:29:00 +0000413 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroff8e2f57a2008-10-29 18:15:37 +0000414 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump1eb44332009-09-09 15:08:12 +0000415
Steve Naroff621edce2009-04-29 16:37:50 +0000416 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump1eb44332009-09-09 15:08:12 +0000417 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroff621edce2009-04-29 16:37:50 +0000418 if (From[i] == '"')
419 To += "\\\"";
420 else
421 To += From[i];
422 }
423 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000424 };
John McCall9d125032010-01-15 18:39:57 +0000425
426 // Helper function: create a CStyleCastExpr with trivial type source info.
427 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
428 CastExpr::CastKind Kind, Expr *E) {
429 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
430 return new (Ctx) CStyleCastExpr(Ty, Kind, E, TInfo,
431 SourceLocation(), SourceLocation());
432 }
Chris Lattner77cd2a02007-10-11 00:43:27 +0000433}
434
Mike Stump1eb44332009-09-09 15:08:12 +0000435void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
436 NamedDecl *D) {
Douglas Gregor72564e72009-02-26 23:50:07 +0000437 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump1eb44332009-09-09 15:08:12 +0000438 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +0000439 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +0000440 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff54055232008-10-27 17:20:55 +0000441 // All the args are checked/rewritten. Don't call twice!
442 RewriteBlockPointerDecl(D);
443 break;
444 }
445 }
446}
447
448void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenek6217b802009-07-29 21:53:49 +0000449 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +0000450 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregor72564e72009-02-26 23:50:07 +0000451 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff54055232008-10-27 17:20:55 +0000452}
453
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000454static bool IsHeaderFile(const std::string &Filename) {
455 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump1eb44332009-09-09 15:08:12 +0000456
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000457 if (DotPos == std::string::npos) {
458 // no file extension
Mike Stump1eb44332009-09-09 15:08:12 +0000459 return false;
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000460 }
Mike Stump1eb44332009-09-09 15:08:12 +0000461
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000462 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
463 // C header: .h
464 // C++ header: .hh or .H;
465 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump1eb44332009-09-09 15:08:12 +0000466}
Fariborz Jahanianb4b2f0c2008-01-18 01:15:54 +0000467
Eli Friedman66d6f042009-05-18 22:20:00 +0000468RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000469 Diagnostic &D, const LangOptions &LOpts,
470 bool silenceMacroWarn)
471 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
472 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Naroffa7b402d2008-03-28 22:26:09 +0000473 IsHeader = IsHeaderFile(inFile);
Mike Stump1eb44332009-09-09 15:08:12 +0000474 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Naroffa7b402d2008-03-28 22:26:09 +0000475 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump1eb44332009-09-09 15:08:12 +0000476 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek8189cde2009-02-07 01:47:29 +0000477 "rewriter doesn't support user-specified control flow semantics "
478 "for @try/@finally (code may not execute properly)");
Steve Naroffa7b402d2008-03-28 22:26:09 +0000479}
480
Eli Friedmanbce831b2009-05-18 22:29:17 +0000481ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
482 llvm::raw_ostream* OS,
Mike Stump1eb44332009-09-09 15:08:12 +0000483 Diagnostic &Diags,
Eli Friedmanc6d656e2009-05-18 22:39:16 +0000484 const LangOptions &LOpts,
485 bool SilenceRewriteMacroWarning) {
486 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere365c502007-11-30 22:25:36 +0000487}
Chris Lattner77cd2a02007-10-11 00:43:27 +0000488
Steve Naroffb29b4272008-04-14 22:03:09 +0000489void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000490 Context = &context;
491 SM = &Context->getSourceManager();
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +0000492 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000493 MsgSendFunctionDecl = 0;
494 MsgSendSuperFunctionDecl = 0;
495 MsgSendStretFunctionDecl = 0;
496 MsgSendSuperStretFunctionDecl = 0;
497 MsgSendFpretFunctionDecl = 0;
498 GetClassFunctionDecl = 0;
499 GetMetaClassFunctionDecl = 0;
500 SelGetUidFunctionDecl = 0;
501 CFStringFunctionDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000502 ConstantStringClassReference = 0;
503 NSStringRecord = 0;
Steve Naroff54055232008-10-27 17:20:55 +0000504 CurMethodDef = 0;
505 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +0000506 CurFunctionDeclToDeclareForBlock = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000507 GlobalVarDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000508 SuperStructDecl = 0;
Steve Naroff621edce2009-04-29 16:37:50 +0000509 ProtocolTypeDecl = 0;
Steve Naroff9630ec52008-03-27 22:59:54 +0000510 ConstantStringDecl = 0;
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000511 BcLabelCount = 0;
Steve Naroffc0a123c2008-03-11 17:37:02 +0000512 SuperContructorFunctionDecl = 0;
Steve Naroffd82a9ab2008-03-15 00:55:56 +0000513 NumObjCStringLiterals = 0;
Steve Naroff68272b82008-12-08 20:01:41 +0000514 PropParentMap = 0;
515 CurrentBody = 0;
Steve Naroffb619d952008-12-09 12:56:34 +0000516 DisableReplaceStmt = false;
Fariborz Jahanianf292fcf2010-01-07 22:51:18 +0000517 objc_impl_method = false;
Mike Stump1eb44332009-09-09 15:08:12 +0000518
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000519 // Get the ID and start/end of the main file.
520 MainFileID = SM->getMainFileID();
521 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
522 MainFileStart = MainBuf->getBufferStart();
523 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000524
Chris Lattner2c78b872009-04-14 23:22:57 +0000525 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump1eb44332009-09-09 15:08:12 +0000526
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000527 // declaring objc_selector outside the parameter list removes a silly
528 // scope related warning...
Steve Naroffba92b2e2008-03-27 22:29:16 +0000529 if (IsHeader)
Steve Naroff62c26322009-02-03 20:39:18 +0000530 Preamble = "#pragma once\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000531 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff46a98a72008-12-23 20:11:22 +0000532 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000533 Preamble += "struct objc_object *superClass; ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000534 if (LangOpts.Microsoft) {
535 // Add a constructor for creating temporary objects.
Ted Kremenek8189cde2009-02-07 01:47:29 +0000536 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
537 ": ";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000538 Preamble += "object(o), superClass(s) {} ";
Steve Naroffc0a123c2008-03-11 17:37:02 +0000539 }
Steve Naroffba92b2e2008-03-27 22:29:16 +0000540 Preamble += "};\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000541 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
542 Preamble += "typedef struct objc_object Protocol;\n";
543 Preamble += "#define _REWRITER_typedef_Protocol\n";
544 Preamble += "#endif\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000545 if (LangOpts.Microsoft) {
546 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
547 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
548 } else
549 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
550 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000551 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000552 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000553 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000554 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000555 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000556 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000557 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000558 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000559 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000560 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000561 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000562 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000563 Preamble += "(const char *);\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000564 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
565 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
566 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
567 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
568 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroff580ca782008-05-09 21:17:56 +0000569 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff59f05a42008-07-16 18:58:11 +0000570 // @synchronized hooks.
Steve Naroff4ebd7162008-12-08 17:30:33 +0000571 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
572 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
573 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000574 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
575 Preamble += "struct __objcFastEnumerationState {\n\t";
576 Preamble += "unsigned long state;\n\t";
Steve Naroffb10f2732008-04-04 22:58:22 +0000577 Preamble += "void **itemsPtr;\n\t";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000578 Preamble += "unsigned long *mutationsPtr;\n\t";
579 Preamble += "unsigned long extra[5];\n};\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000580 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000581 Preamble += "#define __FASTENUMERATIONSTATE\n";
582 Preamble += "#endif\n";
583 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
584 Preamble += "struct __NSConstantStringImpl {\n";
585 Preamble += " int *isa;\n";
586 Preamble += " int flags;\n";
587 Preamble += " char *str;\n";
588 Preamble += " long length;\n";
589 Preamble += "};\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000590 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
591 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
592 Preamble += "#else\n";
Steve Naroff4ebd7162008-12-08 17:30:33 +0000593 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroff88bee742008-08-05 20:04:48 +0000594 Preamble += "#endif\n";
Steve Naroffba92b2e2008-03-27 22:29:16 +0000595 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
596 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000597 // Blocks preamble.
598 Preamble += "#ifndef BLOCK_IMPL\n";
599 Preamble += "#define BLOCK_IMPL\n";
600 Preamble += "struct __block_impl {\n";
601 Preamble += " void *isa;\n";
602 Preamble += " int Flags;\n";
Steve Naroff01aec112009-12-06 21:14:13 +0000603 Preamble += " int Reserved;\n";
Steve Naroff54055232008-10-27 17:20:55 +0000604 Preamble += " void *FuncPtr;\n";
605 Preamble += "};\n";
Steve Naroff5bc60d02008-12-16 15:50:30 +0000606 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroffc9c1e9c2009-12-06 01:52:22 +0000607 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000608 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
609 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
610 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
611 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
612 Preamble += "#else\n";
Steve Naroffcd826372010-01-05 18:09:31 +0000613 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
614 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
Steve Naroffa851e602009-12-06 01:33:56 +0000615 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
616 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
617 Preamble += "#endif\n";
Steve Naroff54055232008-10-27 17:20:55 +0000618 Preamble += "#endif\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000619 if (LangOpts.Microsoft) {
Steve Naroff4ebd7162008-12-08 17:30:33 +0000620 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
621 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000622 Preamble += "#define __attribute__(X)\n";
Fariborz Jahanian34204192010-01-15 22:29:39 +0000623 Preamble += "#define __weak\n";
Steve Naroffa48396e2008-10-27 18:50:14 +0000624 }
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000625 else {
Fariborz Jahanian52b08f22009-12-23 02:07:37 +0000626 Preamble += "#define __block\n";
Fariborz Jahanian2086d542010-01-05 19:21:35 +0000627 Preamble += "#define __weak\n";
628 }
Chris Lattner9e13c2e2008-01-31 19:38:44 +0000629}
630
631
Chris Lattnerf04da132007-10-24 17:06:59 +0000632//===----------------------------------------------------------------------===//
633// Top Level Driver Code
634//===----------------------------------------------------------------------===//
635
Chris Lattner682bf922009-03-29 16:50:03 +0000636void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000637 // Two cases: either the decl could be in the main file, or it could be in a
638 // #included file. If the former, rewrite it now. If the later, check to see
639 // if we rewrote the #include/#import.
640 SourceLocation Loc = D->getLocation();
Chris Lattnerf7cf85b2009-01-16 07:36:28 +0000641 Loc = SM->getInstantiationLoc(Loc);
Mike Stump1eb44332009-09-09 15:08:12 +0000642
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000643 // If this is for a builtin, ignore it.
644 if (Loc.isInvalid()) return;
645
Steve Naroffebf2b562007-10-23 23:50:29 +0000646 // Look for built-in declarations that we need to refer during the rewrite.
647 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff09b266e2007-10-30 23:14:51 +0000648 RewriteFunctionDecl(FD);
Steve Naroff248a7532008-04-15 22:42:06 +0000649 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000650 // declared in <Foundation/NSString.h>
Chris Lattner8ec03f52008-11-24 03:54:41 +0000651 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffbeaf2992007-11-03 11:27:19 +0000652 ConstantStringClassReference = FVD;
653 return;
654 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000655 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroffbef11852007-10-26 20:53:56 +0000656 RewriteInterfaceDecl(MD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000657 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff423cb562007-10-30 13:30:57 +0000658 RewriteCategoryDecl(CD);
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000659 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Naroff752d6ef2007-10-30 16:42:30 +0000660 RewriteProtocolDecl(PD);
Mike Stump1eb44332009-09-09 15:08:12 +0000661 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000662 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000663 RewriteForwardProtocolDecl(FP);
Douglas Gregord0434102009-01-09 00:49:46 +0000664 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
665 // Recurse into linkage specifications
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000666 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
667 DIEnd = LSD->decls_end();
Douglas Gregord0434102009-01-09 00:49:46 +0000668 DI != DIEnd; ++DI)
Chris Lattner682bf922009-03-29 16:50:03 +0000669 HandleTopLevelSingleDecl(*DI);
Steve Naroffebf2b562007-10-23 23:50:29 +0000670 }
Chris Lattnerf04da132007-10-24 17:06:59 +0000671 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekcf7e9582008-04-14 21:24:13 +0000672 if (SM->isFromMainFile(Loc))
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000673 return HandleDeclInMainFile(D);
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000674}
675
Chris Lattnerf04da132007-10-24 17:06:59 +0000676//===----------------------------------------------------------------------===//
677// Syntactic (non-AST) Rewriting Code
678//===----------------------------------------------------------------------===//
679
Steve Naroffb29b4272008-04-14 22:03:09 +0000680void RewriteObjC::RewriteInclude() {
Chris Lattner2b2453a2009-01-17 06:22:33 +0000681 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000682 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
683 const char *MainBufStart = MainBuf.first;
684 const char *MainBufEnd = MainBuf.second;
685 size_t ImportLen = strlen("import");
686 size_t IncludeLen = strlen("include");
Mike Stump1eb44332009-09-09 15:08:12 +0000687
Fariborz Jahanianaf57b462008-01-19 01:03:17 +0000688 // Loop over the whole file, looking for includes.
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000689 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
690 if (*BufPtr == '#') {
691 if (++BufPtr == MainBufEnd)
692 return;
693 while (*BufPtr == ' ' || *BufPtr == '\t')
694 if (++BufPtr == MainBufEnd)
695 return;
696 if (!strncmp(BufPtr, "import", ImportLen)) {
697 // replace import with include
Mike Stump1eb44332009-09-09 15:08:12 +0000698 SourceLocation ImportLoc =
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000699 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattneraadaf782008-01-31 19:51:04 +0000700 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian452b8992008-01-19 00:30:35 +0000701 BufPtr += ImportLen;
702 }
703 }
704 }
Chris Lattner2c64b7b2007-10-16 21:07:07 +0000705}
706
Steve Naroffb29b4272008-04-14 22:03:09 +0000707void RewriteObjC::RewriteTabs() {
Chris Lattnerf04da132007-10-24 17:06:59 +0000708 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
709 const char *MainBufStart = MainBuf.first;
710 const char *MainBufEnd = MainBuf.second;
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Chris Lattnerf04da132007-10-24 17:06:59 +0000712 // Loop over the whole file, looking for tabs.
713 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
714 if (*BufPtr != '\t')
715 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000716
Chris Lattnerf04da132007-10-24 17:06:59 +0000717 // Okay, we found a tab. This tab will turn into at least one character,
718 // but it depends on which 'virtual column' it is in. Compute that now.
719 unsigned VCol = 0;
720 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
721 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
722 ++VCol;
Mike Stump1eb44332009-09-09 15:08:12 +0000723
Chris Lattnerf04da132007-10-24 17:06:59 +0000724 // Okay, now that we know the virtual column, we know how many spaces to
725 // insert. We assume 8-character tab-stops.
726 unsigned Spaces = 8-(VCol & 7);
Mike Stump1eb44332009-09-09 15:08:12 +0000727
Chris Lattnerf04da132007-10-24 17:06:59 +0000728 // Get the location of the tab.
Chris Lattner2b2453a2009-01-17 06:22:33 +0000729 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
730 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump1eb44332009-09-09 15:08:12 +0000731
Chris Lattnerf04da132007-10-24 17:06:59 +0000732 // Rewrite the single tab character into a sequence of spaces.
Chris Lattneraadaf782008-01-31 19:51:04 +0000733 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattnerf04da132007-10-24 17:06:59 +0000734 }
Chris Lattner8a12c272007-10-11 18:38:32 +0000735}
736
Steve Naroffeb0646c2008-12-02 15:48:25 +0000737static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
738 ObjCIvarDecl *OID) {
739 std::string S;
740 S = "((struct ";
741 S += ClassDecl->getIdentifier()->getName();
742 S += "_IMPL *)self)->";
Daniel Dunbar5ffe14c2009-10-18 20:26:27 +0000743 S += OID->getName();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000744 return S;
745}
746
Steve Naroffa0876e82008-12-02 17:36:43 +0000747void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
748 ObjCImplementationDecl *IMD,
749 ObjCCategoryImplDecl *CID) {
Steve Naroffd40910b2008-12-01 20:33:01 +0000750 SourceLocation startLoc = PID->getLocStart();
751 InsertText(startLoc, "// ", 3);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000752 const char *startBuf = SM->getCharacterData(startLoc);
753 assert((*startBuf == '@') && "bogus @synthesize location");
754 const char *semiBuf = strchr(startBuf, ';');
755 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek8189cde2009-02-07 01:47:29 +0000756 SourceLocation onePastSemiLoc =
757 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000758
759 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
760 return; // FIXME: is this correct?
Mike Stump1eb44332009-09-09 15:08:12 +0000761
Steve Naroffeb0646c2008-12-02 15:48:25 +0000762 // Generate the 'getter' function.
Steve Naroffeb0646c2008-12-02 15:48:25 +0000763 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000764 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroffeb0646c2008-12-02 15:48:25 +0000765 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump1eb44332009-09-09 15:08:12 +0000766
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000767 if (!OID)
768 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000769
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000770 std::string Getr;
771 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
772 Getr += "{ ";
773 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000774 // FIXME: deal with code generation implications for various property
775 // attributes (copy, retain, nonatomic).
Steve Naroff3539cdb2008-12-02 17:54:50 +0000776 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000777 Getr += "return " + getIvarAccessString(ClassDecl, OID);
778 Getr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000779 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroffeb0646c2008-12-02 15:48:25 +0000780 if (PD->isReadOnly())
781 return;
Mike Stump1eb44332009-09-09 15:08:12 +0000782
Steve Naroffeb0646c2008-12-02 15:48:25 +0000783 // Generate the 'setter' function.
784 std::string Setr;
785 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroffeb0646c2008-12-02 15:48:25 +0000786 Setr += "{ ";
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000787 // Synthesize an explicit cast to initialize the ivar.
Mike Stump1eb44332009-09-09 15:08:12 +0000788 // FIXME: deal with code generation implications for various property
789 // attributes (copy, retain, nonatomic).
Steve Naroff15f081d2008-12-03 00:56:33 +0000790 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000791 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Narofff4312dc2008-12-11 19:29:16 +0000792 Setr += PD->getNameAsCString();
Steve Naroffdd2fdf12008-12-02 16:05:55 +0000793 Setr += "; }";
Steve Naroffeb0646c2008-12-02 15:48:25 +0000794 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffd40910b2008-12-01 20:33:01 +0000795}
Chris Lattner8a12c272007-10-11 18:38:32 +0000796
Steve Naroffb29b4272008-04-14 22:03:09 +0000797void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattnerf04da132007-10-24 17:06:59 +0000798 // Get the start location and compute the semi location.
799 SourceLocation startLoc = ClassDecl->getLocation();
800 const char *startBuf = SM->getCharacterData(startLoc);
801 const char *semiPtr = strchr(startBuf, ';');
Mike Stump1eb44332009-09-09 15:08:12 +0000802
Chris Lattnerf04da132007-10-24 17:06:59 +0000803 // Translate to typedef's that forward reference structs with the same name
804 // as the class. As a convenience, we include the original declaration
805 // as a comment.
806 std::string typedefString;
Fariborz Jahanian91fbd122010-01-11 22:48:40 +0000807 typedefString += "// @class ";
808 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
809 I != E; ++I) {
810 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
811 typedefString += ForwardDecl->getNameAsString();
812 if (I+1 != E)
813 typedefString += ", ";
814 else
815 typedefString += ";\n";
816 }
817
Chris Lattner67956052009-02-20 18:04:31 +0000818 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
819 I != E; ++I) {
Ted Kremenek321c22f2009-11-18 00:28:11 +0000820 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff32174822007-11-09 12:50:28 +0000821 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000822 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000823 typedefString += "\n";
824 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000825 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000826 typedefString += "\n";
Steve Naroff352336b2007-11-05 14:36:37 +0000827 typedefString += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000828 typedefString += ForwardDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +0000829 typedefString += ";\n#endif\n";
Steve Naroff934f2762007-10-24 22:48:43 +0000830 }
Mike Stump1eb44332009-09-09 15:08:12 +0000831
Steve Naroff934f2762007-10-24 22:48:43 +0000832 // Replace the @class with typedefs corresponding to the classes.
Mike Stump1eb44332009-09-09 15:08:12 +0000833 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattneraadaf782008-01-31 19:51:04 +0000834 typedefString.c_str(), typedefString.size());
Chris Lattnerf04da132007-10-24 17:06:59 +0000835}
836
Steve Naroffb29b4272008-04-14 22:03:09 +0000837void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000838 // When method is a synthesized one, such as a getter/setter there is
839 // nothing to rewrite.
840 if (Method->isSynthesized())
841 return;
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000842 SourceLocation LocStart = Method->getLocStart();
843 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +0000844
Chris Lattner30fc9332009-02-04 01:06:56 +0000845 if (SM->getInstantiationLineNumber(LocEnd) >
846 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroff94ac21e2008-10-21 13:37:27 +0000847 InsertText(LocStart, "#if 0\n", 6);
848 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000849 } else {
Chris Lattnerf3dd57e2008-01-31 19:42:41 +0000850 InsertText(LocStart, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000851 }
852}
853
Mike Stump1eb44332009-09-09 15:08:12 +0000854void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Fariborz Jahaniand0502402010-01-21 17:36:00 +0000855 SourceLocation Loc = prop->getAtLoc();
Mike Stump1eb44332009-09-09 15:08:12 +0000856
Steve Naroff6327e0d2009-01-11 01:06:09 +0000857 ReplaceText(Loc, 0, "// ", 3);
Steve Naroff6327e0d2009-01-11 01:06:09 +0000858 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahanian957cf652007-11-07 00:09:37 +0000859}
860
Steve Naroffb29b4272008-04-14 22:03:09 +0000861void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff423cb562007-10-30 13:30:57 +0000862 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000863
Steve Naroff423cb562007-10-30 13:30:57 +0000864 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000865 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000866
867 for (ObjCCategoryDecl::instmeth_iterator
868 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000869 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000870 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +0000871 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000872 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000873 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000874 RewriteMethodDeclaration(*I);
875
Steve Naroff423cb562007-10-30 13:30:57 +0000876 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000877 ReplaceText(CatDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroff423cb562007-10-30 13:30:57 +0000878}
879
Steve Naroffb29b4272008-04-14 22:03:09 +0000880void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000881 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump1eb44332009-09-09 15:08:12 +0000882
Steve Naroff752d6ef2007-10-30 16:42:30 +0000883 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +0000884
Steve Naroff752d6ef2007-10-30 16:42:30 +0000885 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000886 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +0000887
888 for (ObjCProtocolDecl::instmeth_iterator
889 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000890 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000891 RewriteMethodDeclaration(*I);
Douglas Gregor6ab35242009-04-09 21:40:53 +0000892 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +0000893 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +0000894 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +0000895 RewriteMethodDeclaration(*I);
896
Steve Naroff752d6ef2007-10-30 16:42:30 +0000897 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +0000898 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Chris Lattneraadaf782008-01-31 19:51:04 +0000899 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroff8cc764c2007-11-14 15:03:57 +0000900
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000901 // Must comment out @optional/@required
902 const char *startBuf = SM->getCharacterData(LocStart);
903 const char *endBuf = SM->getCharacterData(LocEnd);
904 for (const char *p = startBuf; p < endBuf; p++) {
905 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
906 std::string CommentedOptional = "/* @optional */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000907 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000908 ReplaceText(OptionalLoc, strlen("@optional"),
909 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000910
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000911 }
912 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
913 std::string CommentedRequired = "/* @required */";
Steve Naroff8cc764c2007-11-14 15:03:57 +0000914 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattneraadaf782008-01-31 19:51:04 +0000915 ReplaceText(OptionalLoc, strlen("@required"),
916 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000917
Fariborz Jahanianb82b3ea2007-11-14 01:37:46 +0000918 }
919 }
Steve Naroff752d6ef2007-10-30 16:42:30 +0000920}
921
Steve Naroffb29b4272008-04-14 22:03:09 +0000922void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000923 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffb7fa9922007-11-14 03:37:28 +0000924 if (LocStart.isInvalid())
925 assert(false && "Invalid SourceLocation");
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000926 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattneraadaf782008-01-31 19:51:04 +0000927 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahaniand175ddf2007-11-14 00:42:16 +0000928}
929
Mike Stump1eb44332009-09-09 15:08:12 +0000930void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000931 std::string &ResultStr) {
Steve Naroffced80a82008-10-30 12:09:33 +0000932 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroff76e429d2008-07-16 14:40:40 +0000933 const FunctionType *FPRetType = 0;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000934 ResultStr += "\nstatic ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000935 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000936 ResultStr += "id";
Steve Narofff4312dc2008-12-11 19:29:16 +0000937 else if (OMD->getResultType()->isFunctionPointerType() ||
938 OMD->getResultType()->isBlockPointerType()) {
Steve Naroff76e429d2008-07-16 14:40:40 +0000939 // needs special handling, since pointer-to-functions have special
940 // syntax (where a decaration models use).
941 QualType retType = OMD->getResultType();
Steve Narofff4312dc2008-12-11 19:29:16 +0000942 QualType PointeeTy;
Ted Kremenek6217b802009-07-29 21:53:49 +0000943 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000944 PointeeTy = PT->getPointeeType();
Ted Kremenek6217b802009-07-29 21:53:49 +0000945 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Narofff4312dc2008-12-11 19:29:16 +0000946 PointeeTy = BPT->getPointeeType();
John McCall183700f2009-09-21 23:43:11 +0000947 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Narofff4312dc2008-12-11 19:29:16 +0000948 ResultStr += FPRetType->getResultType().getAsString();
949 ResultStr += "(*";
Steve Naroff76e429d2008-07-16 14:40:40 +0000950 }
951 } else
Fariborz Jahanianc5692492007-12-17 21:03:50 +0000952 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +0000953 ResultStr += " ";
Mike Stump1eb44332009-09-09 15:08:12 +0000954
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000955 // Unique method name
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000956 std::string NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000957
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000958 if (OMD->isInstanceMethod())
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000959 NameStr += "_I_";
960 else
961 NameStr += "_C_";
Mike Stump1eb44332009-09-09 15:08:12 +0000962
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000963 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000964 NameStr += "_";
Mike Stump1eb44332009-09-09 15:08:12 +0000965
966 if (ObjCCategoryImplDecl *CID =
Steve Naroff3e0a5402009-01-08 19:41:02 +0000967 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000968 NameStr += CID->getNameAsString();
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000969 NameStr += "_";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000970 }
Mike Stump1eb44332009-09-09 15:08:12 +0000971 // Append selector names, replacing ':' with '_'
Chris Lattner077bf5e2008-11-24 03:33:13 +0000972 {
973 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000974 int len = selString.size();
975 for (int i = 0; i < len; i++)
976 if (selString[i] == ':')
977 selString[i] = '_';
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000978 NameStr += selString;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000979 }
Fariborz Jahanianb7908b52007-11-13 21:02:00 +0000980 // Remember this name for metadata emission
981 MethodInternalNames[OMD] = NameStr;
982 ResultStr += NameStr;
Mike Stump1eb44332009-09-09 15:08:12 +0000983
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000984 // Rewrite arguments
985 ResultStr += "(";
Mike Stump1eb44332009-09-09 15:08:12 +0000986
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000987 // invisible arguments
Douglas Gregorf8d49f62009-01-09 17:18:27 +0000988 if (OMD->isInstanceMethod()) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +0000989 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000990 selfTy = Context->getPointerType(selfTy);
Steve Naroff05b8c782008-03-12 00:25:36 +0000991 if (!LangOpts.Microsoft) {
992 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
993 ResultStr += "struct ";
994 }
995 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerd9d22dd2008-11-24 05:29:24 +0000996 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +0000997 ResultStr += " *";
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +0000998 }
999 else
Steve Naroff621edce2009-04-29 16:37:50 +00001000 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00001001
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001002 ResultStr += " self, ";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001003 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001004 ResultStr += " _cmd";
Mike Stump1eb44332009-09-09 15:08:12 +00001005
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001006 // Method arguments.
Chris Lattner89951a82009-02-20 18:43:26 +00001007 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1008 E = OMD->param_end(); PI != E; ++PI) {
1009 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001010 ResultStr += ", ";
Steve Naroff543409e2008-04-18 21:13:19 +00001011 if (PDecl->getType()->isObjCQualifiedIdType()) {
1012 ResultStr += "id ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001013 ResultStr += PDecl->getNameAsString();
Steve Naroff543409e2008-04-18 21:13:19 +00001014 } else {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001015 std::string Name = PDecl->getNameAsString();
Steve Naroff01f2ffa2008-12-11 21:05:33 +00001016 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001017 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenek6217b802009-07-29 21:53:49 +00001018 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001019 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
1020 Context->PrintingPolicy);
Steve Naroffc8ad87b2008-10-30 14:45:29 +00001021 } else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00001022 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroff543409e2008-04-18 21:13:19 +00001023 ResultStr += Name;
1024 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001025 }
Fariborz Jahanian7c39ff72008-01-21 20:14:23 +00001026 if (OMD->isVariadic())
1027 ResultStr += ", ...";
Fariborz Jahanian531a1ea2008-01-10 01:39:52 +00001028 ResultStr += ") ";
Mike Stump1eb44332009-09-09 15:08:12 +00001029
Steve Naroff76e429d2008-07-16 14:40:40 +00001030 if (FPRetType) {
1031 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump1eb44332009-09-09 15:08:12 +00001032
Steve Naroff76e429d2008-07-16 14:40:40 +00001033 // Now, emit the argument types (if any).
Douglas Gregor72564e72009-02-26 23:50:07 +00001034 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroff76e429d2008-07-16 14:40:40 +00001035 ResultStr += "(";
1036 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1037 if (i) ResultStr += ", ";
1038 std::string ParamStr = FT->getArgType(i).getAsString();
1039 ResultStr += ParamStr;
1040 }
1041 if (FT->isVariadic()) {
1042 if (FT->getNumArgs()) ResultStr += ", ";
1043 ResultStr += "...";
1044 }
1045 ResultStr += ")";
1046 } else {
1047 ResultStr += "()";
1048 }
1049 }
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001050}
Douglas Gregor4afa39d2009-01-20 01:17:11 +00001051void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001052 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1053 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump1eb44332009-09-09 15:08:12 +00001054
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001055 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001056 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001057 else
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001058 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump1eb44332009-09-09 15:08:12 +00001059
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001060 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001061 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1062 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001063 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001064 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001065 ObjCMethodDecl *OMD = *I;
1066 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001067 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001068 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redld3a413d2009-04-26 20:35:05 +00001069
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001070 const char *startBuf = SM->getCharacterData(LocStart);
1071 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001072 ReplaceText(LocStart, endBuf-startBuf,
1073 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001074 }
Mike Stump1eb44332009-09-09 15:08:12 +00001075
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001076 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001077 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1078 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001079 I != E; ++I) {
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001080 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001081 ObjCMethodDecl *OMD = *I;
1082 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001083 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00001084 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump1eb44332009-09-09 15:08:12 +00001085
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001086 const char *startBuf = SM->getCharacterData(LocStart);
1087 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattneraadaf782008-01-31 19:51:04 +00001088 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump1eb44332009-09-09 15:08:12 +00001089 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001090 }
Steve Naroffd40910b2008-12-01 20:33:01 +00001091 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001092 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump1eb44332009-09-09 15:08:12 +00001093 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00001094 I != E; ++I) {
Steve Naroffa0876e82008-12-02 17:36:43 +00001095 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffd40910b2008-12-01 20:33:01 +00001096 }
1097
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001098 if (IMD)
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001099 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00001100 else
Mike Stump1eb44332009-09-09 15:08:12 +00001101 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian48a0b6a2007-11-13 18:44:14 +00001102}
1103
Steve Naroffb29b4272008-04-14 22:03:09 +00001104void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Narofff908a872007-10-30 02:23:23 +00001105 std::string ResultStr;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001106 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001107 // we haven't seen a forward decl - generate a typedef.
Steve Naroff5086a8d2007-11-14 23:02:56 +00001108 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001109 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001110 ResultStr += "\n";
1111 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001112 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001113 ResultStr += "\n";
Steve Naroff61ed9ca2008-03-10 23:16:54 +00001114 ResultStr += "typedef struct objc_object ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001115 ResultStr += ClassDecl->getNameAsString();
Steve Naroff32174822007-11-09 12:50:28 +00001116 ResultStr += ";\n#endif\n";
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001117 // Mark this typedef as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001118 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff6c6a2db2007-11-01 03:35:41 +00001119 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001120 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump1eb44332009-09-09 15:08:12 +00001121
1122 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001123 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff6327e0d2009-01-11 01:06:09 +00001124 RewriteProperty(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001125 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00001126 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001127 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001128 RewriteMethodDeclaration(*I);
Mike Stump1eb44332009-09-09 15:08:12 +00001129 for (ObjCInterfaceDecl::classmeth_iterator
1130 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregor6ab35242009-04-09 21:40:53 +00001131 I != E; ++I)
Steve Naroff58dbdeb2007-12-14 23:37:57 +00001132 RewriteMethodDeclaration(*I);
1133
Steve Naroff2feac5e2007-10-30 03:43:13 +00001134 // Lastly, comment out the @end.
Ted Kremenek782f2f52010-01-07 01:20:12 +00001135 ReplaceText(ClassDecl->getAtEndRange().getBegin(), 0, "// ", 3);
Steve Naroffbef11852007-10-26 20:53:56 +00001136}
1137
Steve Naroffb619d952008-12-09 12:56:34 +00001138Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1139 SourceRange SrcRange) {
Steve Naroffc77a6362008-12-04 16:24:46 +00001140 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1141 // This allows us to reuse all the fun and games in SynthMessageExpr().
1142 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1143 ObjCMessageExpr *MsgExpr;
1144 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1145 llvm::SmallVector<Expr *, 1> ExprVec;
1146 ExprVec.push_back(newStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001147
Steve Naroff8599e7a2008-12-08 16:43:47 +00001148 Stmt *Receiver = PropRefExpr->getBase();
1149 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1150 if (PRE && PropGetters[PRE]) {
1151 // This allows us to handle chain/nested property getters.
1152 Receiver = PropGetters[PRE];
1153 }
Mike Stump1eb44332009-09-09 15:08:12 +00001154 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1155 PDecl->getSetterName(), PDecl->getType(),
1156 PDecl->getSetterMethodDecl(),
1157 SourceLocation(), SourceLocation(),
Steve Naroffc77a6362008-12-04 16:24:46 +00001158 &ExprVec[0], 1);
1159 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump1eb44332009-09-09 15:08:12 +00001160
Steve Naroffc77a6362008-12-04 16:24:46 +00001161 // Now do the actual rewrite.
Steve Naroffb619d952008-12-09 12:56:34 +00001162 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffe58ee0c2008-12-10 14:53:27 +00001163 //delete BinOp;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001164 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1165 // to things that stay around.
1166 Context->Deallocate(MsgExpr);
Steve Naroffc77a6362008-12-04 16:24:46 +00001167 return ReplacingStmt;
Steve Naroff15f081d2008-12-03 00:56:33 +00001168}
1169
Steve Naroffc77a6362008-12-04 16:24:46 +00001170Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Naroff15f081d2008-12-03 00:56:33 +00001171 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1172 // This allows us to reuse all the fun and games in SynthMessageExpr().
1173 ObjCMessageExpr *MsgExpr;
1174 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump1eb44332009-09-09 15:08:12 +00001175
Steve Naroff8599e7a2008-12-08 16:43:47 +00001176 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Steve Naroff8599e7a2008-12-08 16:43:47 +00001178 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1179 if (PRE && PropGetters[PRE]) {
1180 // This allows us to handle chain/nested property getters.
1181 Receiver = PropGetters[PRE];
1182 }
Mike Stump1eb44332009-09-09 15:08:12 +00001183 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1184 PDecl->getGetterName(), PDecl->getType(),
1185 PDecl->getGetterMethodDecl(),
1186 SourceLocation(), SourceLocation(),
Steve Naroff15f081d2008-12-03 00:56:33 +00001187 0, 0);
1188
Steve Naroff4c3580e2008-12-04 23:50:32 +00001189 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001190
1191 if (!PropParentMap)
1192 PropParentMap = new ParentMap(CurrentBody);
1193
1194 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1195 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1196 // We stash away the ReplacingStmt since actually doing the
1197 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1198 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek8189cde2009-02-07 01:47:29 +00001199 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1200 // to things that stay around.
1201 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001202 return PropRefExpr; // return the original...
1203 } else {
1204 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00001205 // delete PropRefExpr; elsewhere...
Ted Kremenek8189cde2009-02-07 01:47:29 +00001206 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1207 // to things that stay around.
1208 Context->Deallocate(MsgExpr);
Steve Naroff8599e7a2008-12-08 16:43:47 +00001209 return ReplacingStmt;
1210 }
Steve Naroff15f081d2008-12-03 00:56:33 +00001211}
1212
Mike Stump1eb44332009-09-09 15:08:12 +00001213Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001214 SourceLocation OrigStart,
1215 bool &replaced) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001216 ObjCIvarDecl *D = IV->getDecl();
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001217 const Expr *BaseExpr = IV->getBase();
Steve Naroff54055232008-10-27 17:20:55 +00001218 if (CurMethodDef) {
Fariborz Jahanian8f095432010-01-26 18:28:51 +00001219 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001220 ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian84ed6002010-01-07 18:18:32 +00001221 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanianffbdead2010-01-26 20:37:44 +00001222 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
Steve Narofff0757612008-05-08 17:52:16 +00001223 // lookup which class implements the instance variable.
1224 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001225 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001226 clsDeclared);
Steve Narofff0757612008-05-08 17:52:16 +00001227 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001228
Steve Narofff0757612008-05-08 17:52:16 +00001229 // Synthesize an explicit cast to gain access to the ivar.
1230 std::string RecName = clsDeclared->getIdentifier()->getName();
1231 RecName += "_IMPL";
1232 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001233 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001234 SourceLocation(), II);
Steve Narofff0757612008-05-08 17:52:16 +00001235 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1236 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001237 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1238 CastExpr::CK_Unknown,
1239 IV->getBase());
Steve Narofff0757612008-05-08 17:52:16 +00001240 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001241 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1242 IV->getBase()->getLocEnd(),
1243 castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001244 replaced = true;
Mike Stump1eb44332009-09-09 15:08:12 +00001245 if (IV->isFreeIvar() &&
Steve Naroff54055232008-10-27 17:20:55 +00001246 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00001247 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1248 IV->getLocation(),
1249 D->getType());
Steve Naroff4c3580e2008-12-04 23:50:32 +00001250 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Narofff0757612008-05-08 17:52:16 +00001251 return ME;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001252 }
Fariborz Jahanian7e20ffe2010-01-28 01:41:20 +00001253 // Get the new text
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001254 // Cannot delete IV->getBase(), since PE points to it.
1255 // Replace the old base with the cast. This is important when doing
1256 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001257 IV->setBase(PE);
Chris Lattner3b2c58c2008-05-23 20:40:52 +00001258 return IV;
Steve Naroffc2a689b2007-11-15 11:33:00 +00001259 }
Steve Naroff84472a82008-04-18 21:55:08 +00001260 } else { // we are outside a method.
Steve Naroff9f525972008-05-06 23:20:07 +00001261 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump1eb44332009-09-09 15:08:12 +00001262
Steve Naroff9f525972008-05-06 23:20:07 +00001263 // Explicit ivar refs need to have a cast inserted.
1264 // FIXME: consider sharing some of this code with the code above.
Fariborz Jahanian26337b22010-01-12 17:31:23 +00001265 if (BaseExpr->getType()->isObjCObjectPointerType()) {
Fariborz Jahanianc374cd92010-01-11 17:50:35 +00001266 ObjCInterfaceType *iFaceDecl =
1267 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Steve Naroff9f525972008-05-06 23:20:07 +00001268 // lookup which class implements the instance variable.
1269 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00001270 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregor6ab35242009-04-09 21:40:53 +00001271 clsDeclared);
Steve Naroff9f525972008-05-06 23:20:07 +00001272 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Steve Naroff9f525972008-05-06 23:20:07 +00001274 // Synthesize an explicit cast to gain access to the ivar.
1275 std::string RecName = clsDeclared->getIdentifier()->getName();
1276 RecName += "_IMPL";
1277 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00001278 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenekdf042e62008-09-05 01:34:33 +00001279 SourceLocation(), II);
Steve Naroff9f525972008-05-06 23:20:07 +00001280 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1281 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
John McCall9d125032010-01-15 18:39:57 +00001282 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, castT,
1283 CastExpr::CK_Unknown,
1284 IV->getBase());
Steve Naroff9f525972008-05-06 23:20:07 +00001285 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001286 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner8d366162008-05-28 16:38:23 +00001287 IV->getBase()->getLocEnd(), castExpr);
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001288 replaced = true;
Steve Naroff9f525972008-05-06 23:20:07 +00001289 // Cannot delete IV->getBase(), since PE points to it.
1290 // Replace the old base with the cast. This is important when doing
1291 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump1eb44332009-09-09 15:08:12 +00001292 IV->setBase(PE);
Steve Naroff9f525972008-05-06 23:20:07 +00001293 return IV;
1294 }
Steve Naroffc2a689b2007-11-15 11:33:00 +00001295 }
Steve Naroff84472a82008-04-18 21:55:08 +00001296 return IV;
Steve Naroff7e3411b2007-11-15 02:58:25 +00001297}
1298
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001299Stmt *RewriteObjC::RewriteObjCNestedIvarRefExpr(Stmt *S, bool &replaced) {
1300 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1301 CI != E; ++CI) {
1302 if (*CI) {
1303 Stmt *newStmt = RewriteObjCNestedIvarRefExpr(*CI, replaced);
1304 if (newStmt)
1305 *CI = newStmt;
1306 }
1307 }
1308 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
1309 SourceRange OrigStmtRange = S->getSourceRange();
1310 Stmt *newStmt = RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin(),
1311 replaced);
1312 return newStmt;
Fariborz Jahanian376338a2010-02-05 17:48:10 +00001313 }
1314 if (ObjCMessageExpr *MsgRefExpr = dyn_cast<ObjCMessageExpr>(S)) {
1315 Stmt *newStmt = SynthMessageExpr(MsgRefExpr);
1316 return newStmt;
1317 }
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00001318 return S;
1319}
1320
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001321/// SynthCountByEnumWithState - To print:
1322/// ((unsigned int (*)
1323/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001324/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001325/// sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001326/// "countByEnumeratingWithState:objects:count:"),
1327/// &enumState,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001328/// (id *)items, (unsigned int)16)
1329///
Steve Naroffb29b4272008-04-14 22:03:09 +00001330void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001331 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1332 "id *, unsigned int))(void *)objc_msgSend)";
1333 buf += "\n\t\t";
1334 buf += "((id)l_collection,\n\t\t";
1335 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1336 buf += "\n\t\t";
1337 buf += "&enumState, "
1338 "(id *)items, (unsigned int)16)";
1339}
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001340
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001341/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1342/// statement to exit to its outer synthesized loop.
1343///
Steve Naroffb29b4272008-04-14 22:03:09 +00001344Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001345 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1346 return S;
1347 // replace break with goto __break_label
1348 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001349
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001350 SourceLocation startLoc = S->getLocStart();
1351 buf = "goto __break_label_";
1352 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001353 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001354
1355 return 0;
1356}
1357
1358/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1359/// statement to continue with its inner synthesized loop.
1360///
Steve Naroffb29b4272008-04-14 22:03:09 +00001361Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001362 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1363 return S;
1364 // replace continue with goto __continue_label
1365 std::string buf;
Mike Stump1eb44332009-09-09 15:08:12 +00001366
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001367 SourceLocation startLoc = S->getLocStart();
1368 buf = "goto __continue_label_";
1369 buf += utostr(ObjCBcLabelNo.back());
Chris Lattneraadaf782008-01-31 19:51:04 +00001370 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001371
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001372 return 0;
1373}
1374
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001375/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001376/// It rewrites:
1377/// for ( type elem in collection) { stmts; }
Mike Stump1eb44332009-09-09 15:08:12 +00001378
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001379/// Into:
1380/// {
Mike Stump1eb44332009-09-09 15:08:12 +00001381/// type elem;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001382/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001383/// id items[16];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001384/// id l_collection = (id)collection;
Mike Stump1eb44332009-09-09 15:08:12 +00001385/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001386/// objects:items count:16];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001387/// if (limit) {
1388/// unsigned long startMutations = *enumState.mutationsPtr;
1389/// do {
1390/// unsigned long counter = 0;
1391/// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001392/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001393/// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001394/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001395/// stmts;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001396/// __continue_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001397/// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001398/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001399/// objects:items count:16]);
1400/// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001401/// __break_label: ;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001402/// }
1403/// else
1404/// elem = nil;
1405/// }
1406///
Steve Naroffb29b4272008-04-14 22:03:09 +00001407Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattner338d1e22008-01-31 05:10:40 +00001408 SourceLocation OrigEnd) {
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001409 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001410 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001411 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump1eb44332009-09-09 15:08:12 +00001412 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001413 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump1eb44332009-09-09 15:08:12 +00001414
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001415 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001416 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001417 const char *elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001418 std::string elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001419 std::string buf;
1420 buf = "\n{\n\t";
1421 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1422 // type elem;
Chris Lattner7e24e822009-03-28 06:33:19 +00001423 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek1ed8e2a2008-10-06 22:16:13 +00001424 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001425 if (ElementType->isObjCQualifiedIdType() ||
1426 ElementType->isObjCQualifiedInterfaceType())
1427 // Simply use 'id' for all qualified types.
1428 elementTypeAsString = "id";
1429 else
1430 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001431 buf += elementTypeAsString;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001432 buf += " ";
Chris Lattner8ec03f52008-11-24 03:54:41 +00001433 elementName = D->getNameAsCString();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001434 buf += elementName;
1435 buf += ";\n\t";
1436 }
Chris Lattner06767512008-04-08 05:52:18 +00001437 else {
1438 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner8ec03f52008-11-24 03:54:41 +00001439 elementName = DR->getDecl()->getNameAsCString();
Steve Naroffe89b8e72009-12-04 21:18:19 +00001440 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1441 if (VD->getType()->isObjCQualifiedIdType() ||
1442 VD->getType()->isObjCQualifiedInterfaceType())
1443 // Simply use 'id' for all qualified types.
1444 elementTypeAsString = "id";
1445 else
1446 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001447 }
Mike Stump1eb44332009-09-09 15:08:12 +00001448
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001449 // struct __objcFastEnumerationState enumState = { 0 };
1450 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1451 // id items[16];
1452 buf += "id items[16];\n\t";
1453 // id l_collection = (id)
1454 buf += "id l_collection = (id)";
Fariborz Jahanian75712282008-01-10 00:24:29 +00001455 // Find start location of 'collection' the hard way!
1456 const char *startCollectionBuf = startBuf;
1457 startCollectionBuf += 3; // skip 'for'
1458 startCollectionBuf = strchr(startCollectionBuf, '(');
1459 startCollectionBuf++; // skip '('
1460 // find 'in' and skip it.
1461 while (*startCollectionBuf != ' ' ||
1462 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1463 (*(startCollectionBuf+3) != ' ' &&
1464 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1465 startCollectionBuf++;
1466 startCollectionBuf += 3;
Mike Stump1eb44332009-09-09 15:08:12 +00001467
1468 // Replace: "for (type element in" with string constructed thus far.
Chris Lattneraadaf782008-01-31 19:51:04 +00001469 ReplaceText(startLoc, startCollectionBuf - startBuf,
1470 buf.c_str(), buf.size());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001471 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian75712282008-01-10 00:24:29 +00001472 SourceLocation rightParenLoc = S->getRParenLoc();
1473 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1474 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001475 buf = ";\n\t";
Mike Stump1eb44332009-09-09 15:08:12 +00001476
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001477 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1478 // objects:items count:16];
1479 // which is synthesized into:
Mike Stump1eb44332009-09-09 15:08:12 +00001480 // unsigned int limit =
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001481 // ((unsigned int (*)
1482 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump1eb44332009-09-09 15:08:12 +00001483 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001484 // sel_registerName(
Mike Stump1eb44332009-09-09 15:08:12 +00001485 // "countByEnumeratingWithState:objects:count:"),
1486 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001487 // (id *)items, (unsigned int)16);
1488 buf += "unsigned long limit =\n\t\t";
1489 SynthCountByEnumWithState(buf);
1490 buf += ";\n\t";
1491 /// if (limit) {
1492 /// unsigned long startMutations = *enumState.mutationsPtr;
1493 /// do {
1494 /// unsigned long counter = 0;
1495 /// do {
Mike Stump1eb44332009-09-09 15:08:12 +00001496 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001497 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001498 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001499 buf += "if (limit) {\n\t";
1500 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1501 buf += "do {\n\t\t";
1502 buf += "unsigned long counter = 0;\n\t\t";
1503 buf += "do {\n\t\t\t";
1504 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1505 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1506 buf += elementName;
Fariborz Jahanian88f50f32008-01-09 18:15:42 +00001507 buf += " = (";
1508 buf += elementTypeAsString;
1509 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001510 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattneraadaf782008-01-31 19:51:04 +00001511 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001512
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001513 /// __continue_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001514 /// } while (counter < limit);
Mike Stump1eb44332009-09-09 15:08:12 +00001515 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001516 /// objects:items count:16]);
1517 /// elem = nil;
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001518 /// __break_label: ;
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001519 /// }
1520 /// else
1521 /// elem = nil;
1522 /// }
Mike Stump1eb44332009-09-09 15:08:12 +00001523 ///
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001524 buf = ";\n\t";
1525 buf += "__continue_label_";
1526 buf += utostr(ObjCBcLabelNo.back());
1527 buf += ": ;";
1528 buf += "\n\t\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001529 buf += "} while (counter < limit);\n\t";
1530 buf += "} while (limit = ";
1531 SynthCountByEnumWithState(buf);
1532 buf += ");\n\t";
1533 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001534 buf += " = ((";
1535 buf += elementTypeAsString;
1536 buf += ")0);\n\t";
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001537 buf += "__break_label_";
1538 buf += utostr(ObjCBcLabelNo.back());
1539 buf += ": ;\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001540 buf += "}\n\t";
1541 buf += "else\n\t\t";
1542 buf += elementName;
Fariborz Jahanian65b0aa52010-01-08 01:29:44 +00001543 buf += " = ((";
1544 buf += elementTypeAsString;
1545 buf += ")0);\n\t";
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001546 buf += "}\n";
Mike Stump1eb44332009-09-09 15:08:12 +00001547
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001548 // Insert all these *after* the statement body.
Sebastian Redld3a413d2009-04-26 20:35:05 +00001549 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Naroff600e4e82008-07-21 18:26:02 +00001550 if (isa<CompoundStmt>(S->getBody())) {
1551 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1552 InsertText(endBodyLoc, buf.c_str(), buf.size());
1553 } else {
1554 /* Need to treat single statements specially. For example:
1555 *
1556 * for (A *a in b) if (stuff()) break;
1557 * for (A *a in b) xxxyy;
1558 *
1559 * The following code simply scans ahead to the semi to find the actual end.
1560 */
1561 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1562 const char *semiBuf = strchr(stmtBuf, ';');
1563 assert(semiBuf && "Can't find ';'");
1564 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1565 InsertText(endBodyLoc, buf.c_str(), buf.size());
1566 }
Fariborz Jahaniane8d1c052008-01-15 23:58:23 +00001567 Stmts.pop_back();
1568 ObjCBcLabelNo.pop_back();
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00001569 return 0;
Fariborz Jahanian10d24f02008-01-07 21:40:22 +00001570}
1571
Mike Stump1eb44332009-09-09 15:08:12 +00001572/// RewriteObjCSynchronizedStmt -
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001573/// This routine rewrites @synchronized(expr) stmt;
1574/// into:
1575/// objc_sync_enter(expr);
1576/// @try stmt @finally { objc_sync_exit(expr); }
1577///
Steve Naroffb29b4272008-04-14 22:03:09 +00001578Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001579 // Get the start location and compute the semi location.
1580 SourceLocation startLoc = S->getLocStart();
1581 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001582
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001583 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump1eb44332009-09-09 15:08:12 +00001584
1585 std::string buf;
Steve Naroff3498cc92008-08-21 13:03:03 +00001586 buf = "objc_sync_enter((id)";
1587 const char *lparenBuf = startBuf;
1588 while (*lparenBuf != '(') lparenBuf++;
1589 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001590 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1591 // the sync expression is typically a message expression that's already
Steve Naroffc7089f12008-08-19 13:04:19 +00001592 // been rewritten! (which implies the SourceLocation's are invalid).
1593 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001594 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffc7089f12008-08-19 13:04:19 +00001595 while (*endBuf != ')') endBuf--;
1596 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001597 buf = ");\n";
1598 // declare a new scope with two variables, _stack and _rethrow.
1599 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1600 buf += "int buf[18/*32-bit i386*/];\n";
1601 buf += "char *pointers[4];} _stack;\n";
1602 buf += "id volatile _rethrow = 0;\n";
1603 buf += "objc_exception_try_enter(&_stack);\n";
1604 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00001605 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001606 startLoc = S->getSynchBody()->getLocEnd();
1607 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001608
Steve Naroffc7089f12008-08-19 13:04:19 +00001609 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001610 SourceLocation lastCurlyLoc = startLoc;
1611 buf = "}\nelse {\n";
1612 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroff621edce2009-04-29 16:37:50 +00001613 buf += "}\n";
1614 buf += "{ /* implicit finally clause */\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001615 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffb85e77a2009-12-05 21:43:12 +00001616
1617 std::string syncBuf;
1618 syncBuf += " objc_sync_exit(";
John McCall9d125032010-01-15 18:39:57 +00001619 Expr *syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1620 CastExpr::CK_Unknown,
1621 S->getSynchExpr());
Ted Kremeneka95d3752008-09-13 05:16:45 +00001622 std::string syncExprBufS;
1623 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00001624 syncExpr->printPretty(syncExprBuf, *Context, 0,
1625 PrintingPolicy(LangOpts));
Steve Naroffb85e77a2009-12-05 21:43:12 +00001626 syncBuf += syncExprBuf.str();
1627 syncBuf += ");";
1628
1629 buf += syncBuf;
1630 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001631 buf += "}\n";
1632 buf += "}";
Mike Stump1eb44332009-09-09 15:08:12 +00001633
Chris Lattneraadaf782008-01-31 19:51:04 +00001634 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001635
1636 bool hasReturns = false;
1637 HasReturnStmts(S->getSynchBody(), hasReturns);
1638 if (hasReturns)
1639 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1640
Fariborz Jahaniana0f55792008-01-29 22:59:37 +00001641 return 0;
1642}
1643
Steve Naroffb85e77a2009-12-05 21:43:12 +00001644void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1645{
Steve Naroff8c565152008-12-05 17:03:39 +00001646 // Perform a bottom up traversal of all children.
1647 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1648 CI != E; ++CI)
1649 if (*CI)
Steve Naroffb85e77a2009-12-05 21:43:12 +00001650 WarnAboutReturnGotoStmts(*CI);
Steve Naroff8c565152008-12-05 17:03:39 +00001651
Steve Naroffb85e77a2009-12-05 21:43:12 +00001652 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump1eb44332009-09-09 15:08:12 +00001653 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff8c565152008-12-05 17:03:39 +00001654 TryFinallyContainsReturnDiag);
1655 }
1656 return;
1657}
1658
Steve Naroffb85e77a2009-12-05 21:43:12 +00001659void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1660{
1661 // Perform a bottom up traversal of all children.
1662 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1663 CI != E; ++CI)
1664 if (*CI)
1665 HasReturnStmts(*CI, hasReturns);
1666
1667 if (isa<ReturnStmt>(S))
1668 hasReturns = true;
1669 return;
1670}
1671
1672void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1673 // Perform a bottom up traversal of all children.
1674 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1675 CI != E; ++CI)
1676 if (*CI) {
1677 RewriteTryReturnStmts(*CI);
1678 }
1679 if (isa<ReturnStmt>(S)) {
1680 SourceLocation startLoc = S->getLocStart();
1681 const char *startBuf = SM->getCharacterData(startLoc);
1682
1683 const char *semiBuf = strchr(startBuf, ';');
1684 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1685 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1686
1687 std::string buf;
1688 buf = "{ objc_exception_try_exit(&_stack); return";
1689
1690 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1691 InsertText(onePastSemiLoc, "}", 1);
1692 }
1693 return;
1694}
1695
1696void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1697 // Perform a bottom up traversal of all children.
1698 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1699 CI != E; ++CI)
1700 if (*CI) {
1701 RewriteSyncReturnStmts(*CI, syncExitBuf);
1702 }
1703 if (isa<ReturnStmt>(S)) {
1704 SourceLocation startLoc = S->getLocStart();
1705 const char *startBuf = SM->getCharacterData(startLoc);
1706
1707 const char *semiBuf = strchr(startBuf, ';');
1708 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1709 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1710
1711 std::string buf;
1712 buf = "{ objc_exception_try_exit(&_stack);";
1713 buf += syncExitBuf;
1714 buf += " return";
1715
1716 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1717 InsertText(onePastSemiLoc, "}", 1);
1718 }
1719 return;
1720}
1721
Steve Naroffb29b4272008-04-14 22:03:09 +00001722Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroff75730982007-11-07 04:08:17 +00001723 // Get the start location and compute the semi location.
1724 SourceLocation startLoc = S->getLocStart();
1725 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001726
Steve Naroff75730982007-11-07 04:08:17 +00001727 assert((*startBuf == '@') && "bogus @try location");
1728
1729 std::string buf;
1730 // declare a new scope with two variables, _stack and _rethrow.
1731 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1732 buf += "int buf[18/*32-bit i386*/];\n";
1733 buf += "char *pointers[4];} _stack;\n";
1734 buf += "id volatile _rethrow = 0;\n";
1735 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff21867b12007-11-07 18:43:40 +00001736 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroff75730982007-11-07 04:08:17 +00001737
Chris Lattneraadaf782008-01-31 19:51:04 +00001738 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001739
Steve Naroff75730982007-11-07 04:08:17 +00001740 startLoc = S->getTryBody()->getLocEnd();
1741 startBuf = SM->getCharacterData(startLoc);
1742
1743 assert((*startBuf == '}') && "bogus @try block");
Mike Stump1eb44332009-09-09 15:08:12 +00001744
Steve Naroff75730982007-11-07 04:08:17 +00001745 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffc9ba1722008-07-16 15:31:30 +00001746 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1747 if (catchList) {
1748 startLoc = startLoc.getFileLocWithOffset(1);
1749 buf = " /* @catch begin */ else {\n";
1750 buf += " id _caught = objc_exception_extract(&_stack);\n";
1751 buf += " objc_exception_try_enter (&_stack);\n";
1752 buf += " if (_setjmp(_stack.buf))\n";
1753 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1754 buf += " else { /* @catch continue */";
Mike Stump1eb44332009-09-09 15:08:12 +00001755
Steve Naroffc9ba1722008-07-16 15:31:30 +00001756 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff8bd3dc62008-09-09 19:59:12 +00001757 } else { /* no catch list */
1758 buf = "}\nelse {\n";
1759 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1760 buf += "}";
1761 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffc9ba1722008-07-16 15:31:30 +00001762 }
Steve Naroff75730982007-11-07 04:08:17 +00001763 bool sawIdTypedCatch = false;
1764 Stmt *lastCatchBody = 0;
Steve Naroff75730982007-11-07 04:08:17 +00001765 while (catchList) {
Steve Naroff7ba138a2009-03-03 19:52:17 +00001766 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroff75730982007-11-07 04:08:17 +00001767
Mike Stump1eb44332009-09-09 15:08:12 +00001768 if (catchList == S->getCatchStmts())
Steve Naroff75730982007-11-07 04:08:17 +00001769 buf = "if ("; // we are generating code for the first catch clause
1770 else
1771 buf = "else if (";
1772 startLoc = catchList->getLocStart();
1773 startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001774
Steve Naroff75730982007-11-07 04:08:17 +00001775 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump1eb44332009-09-09 15:08:12 +00001776
Steve Naroff75730982007-11-07 04:08:17 +00001777 const char *lParenLoc = strchr(startBuf, '(');
1778
Steve Naroffbe4b3332008-02-01 22:08:12 +00001779 if (catchList->hasEllipsis()) {
Steve Naroffe12e6922008-02-01 20:02:07 +00001780 // Now rewrite the body...
1781 lastCatchBody = catchList->getCatchBody();
Steve Naroffe12e6922008-02-01 20:02:07 +00001782 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1783 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner06767512008-04-08 05:52:18 +00001784 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1785 "bogus @catch paren location");
Steve Naroffe12e6922008-02-01 20:02:07 +00001786 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001787
Steve Naroffe12e6922008-02-01 20:02:07 +00001788 buf += "1) { id _tmp = _caught;";
Daniel Dunbard7407dc2009-08-19 19:10:30 +00001789 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff7ba138a2009-03-03 19:52:17 +00001790 } else if (catchDecl) {
1791 QualType t = catchDecl->getType();
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001792 if (t == Context->getObjCIdType()) {
Steve Naroff75730982007-11-07 04:08:17 +00001793 buf += "1) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001794 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001795 sawIdTypedCatch = true;
Fariborz Jahanian66867c52010-01-12 01:22:23 +00001796 } else if (t->isObjCObjectPointerType()) {
1797 QualType InterfaceTy = t->getPointeeType();
1798 const ObjCInterfaceType *cls = // Should be a pointer to a class.
1799 InterfaceTy->getAs<ObjCInterfaceType>();
Steve Naroff75730982007-11-07 04:08:17 +00001800 if (cls) {
Steve Naroff21867b12007-11-07 18:43:40 +00001801 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00001802 buf += cls->getDecl()->getNameAsString();
Steve Naroff21867b12007-11-07 18:43:40 +00001803 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattneraadaf782008-01-31 19:51:04 +00001804 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001805 }
1806 }
1807 // Now rewrite the body...
1808 lastCatchBody = catchList->getCatchBody();
1809 SourceLocation rParenLoc = catchList->getRParenLoc();
1810 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1811 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1812 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1813 assert((*rParenBuf == ')') && "bogus @catch paren location");
1814 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001815
Steve Naroff75730982007-11-07 04:08:17 +00001816 buf = " = _caught;";
Mike Stump1eb44332009-09-09 15:08:12 +00001817 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroff75730982007-11-07 04:08:17 +00001818 // declares the @catch parameter).
Chris Lattneraadaf782008-01-31 19:51:04 +00001819 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff7ba138a2009-03-03 19:52:17 +00001820 } else {
Steve Naroff75730982007-11-07 04:08:17 +00001821 assert(false && "@catch rewrite bug");
Steve Naroff2bd03922007-11-07 15:32:26 +00001822 }
Steve Naroffe12e6922008-02-01 20:02:07 +00001823 // make sure all the catch bodies get rewritten!
Steve Naroff75730982007-11-07 04:08:17 +00001824 catchList = catchList->getNextCatchStmt();
1825 }
1826 // Complete the catch list...
1827 if (lastCatchBody) {
1828 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001829 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1830 "bogus @catch body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001831
Steve Naroff378f47a2008-09-11 15:29:03 +00001832 // Insert the last (implicit) else clause *before* the right curly brace.
1833 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1834 buf = "} /* last catch end */\n";
1835 buf += "else {\n";
1836 buf += " _rethrow = _caught;\n";
1837 buf += " objc_exception_try_exit(&_stack);\n";
1838 buf += "} } /* @catch end */\n";
1839 if (!S->getFinallyStmt())
1840 buf += "}\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001841 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001842
Steve Naroff75730982007-11-07 04:08:17 +00001843 // Set lastCurlyLoc
1844 lastCurlyLoc = lastCatchBody->getLocEnd();
1845 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00001846 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroff75730982007-11-07 04:08:17 +00001847 startLoc = finalStmt->getLocStart();
1848 startBuf = SM->getCharacterData(startLoc);
1849 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump1eb44332009-09-09 15:08:12 +00001850
Steve Naroff75730982007-11-07 04:08:17 +00001851 buf = "/* @finally */";
Chris Lattneraadaf782008-01-31 19:51:04 +00001852 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001853
Steve Naroff75730982007-11-07 04:08:17 +00001854 Stmt *body = finalStmt->getFinallyBody();
1855 SourceLocation startLoc = body->getLocStart();
1856 SourceLocation endLoc = body->getLocEnd();
Chris Lattner06767512008-04-08 05:52:18 +00001857 assert(*SM->getCharacterData(startLoc) == '{' &&
1858 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001859 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner06767512008-04-08 05:52:18 +00001860 "bogus @finally body location");
Mike Stump1eb44332009-09-09 15:08:12 +00001861
Steve Naroff75730982007-11-07 04:08:17 +00001862 startLoc = startLoc.getFileLocWithOffset(1);
1863 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001864 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroff75730982007-11-07 04:08:17 +00001865 endLoc = endLoc.getFileLocWithOffset(-1);
1866 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001867 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001868
Steve Naroff75730982007-11-07 04:08:17 +00001869 // Set lastCurlyLoc
1870 lastCurlyLoc = body->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00001871
Steve Naroff8c565152008-12-05 17:03:39 +00001872 // Now check for any return/continue/go statements within the @try.
Steve Naroffb85e77a2009-12-05 21:43:12 +00001873 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff378f47a2008-09-11 15:29:03 +00001874 } else { /* no finally clause - make sure we synthesize an implicit one */
1875 buf = "{ /* implicit finally clause */\n";
1876 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1877 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1878 buf += "}";
1879 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffb85e77a2009-12-05 21:43:12 +00001880
1881 // Now check for any return/continue/go statements within the @try.
1882 // The implicit finally clause won't called if the @try contains any
1883 // jump statements.
1884 bool hasReturns = false;
1885 HasReturnStmts(S->getTryBody(), hasReturns);
1886 if (hasReturns)
1887 RewriteTryReturnStmts(S->getTryBody());
Steve Naroff75730982007-11-07 04:08:17 +00001888 }
1889 // Now emit the final closing curly brace...
1890 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1891 buf = " } /* @try scope end */\n";
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00001892 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001893 return 0;
1894}
1895
Steve Naroffb29b4272008-04-14 22:03:09 +00001896Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001897 return 0;
1898}
1899
Steve Naroffb29b4272008-04-14 22:03:09 +00001900Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001901 return 0;
1902}
1903
Mike Stump1eb44332009-09-09 15:08:12 +00001904// This can't be done with ReplaceStmt(S, ThrowExpr), since
1905// the throw expression is typically a message expression that's already
Steve Naroff2bd03922007-11-07 15:32:26 +00001906// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroffb29b4272008-04-14 22:03:09 +00001907Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroff2bd03922007-11-07 15:32:26 +00001908 // Get the start location and compute the semi location.
1909 SourceLocation startLoc = S->getLocStart();
1910 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00001911
Steve Naroff2bd03922007-11-07 15:32:26 +00001912 assert((*startBuf == '@') && "bogus @throw location");
1913
1914 std::string buf;
1915 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroff20ebf8f2008-01-19 00:42:38 +00001916 if (S->getThrowExpr())
1917 buf = "objc_exception_throw(";
1918 else // add an implicit argument
1919 buf = "objc_exception_throw(_caught";
Mike Stump1eb44332009-09-09 15:08:12 +00001920
Steve Naroff4ba0acb2008-07-25 15:41:30 +00001921 // handle "@ throw" correctly.
1922 const char *wBuf = strchr(startBuf, 'w');
1923 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1924 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump1eb44332009-09-09 15:08:12 +00001925
Steve Naroff2bd03922007-11-07 15:32:26 +00001926 const char *semiBuf = strchr(startBuf, ';');
1927 assert((*semiBuf == ';') && "@throw: can't find ';'");
1928 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1929 buf = ");";
Chris Lattneraadaf782008-01-31 19:51:04 +00001930 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroff2bd03922007-11-07 15:32:26 +00001931 return 0;
1932}
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00001933
Steve Naroffb29b4272008-04-14 22:03:09 +00001934Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattner01c57482007-10-17 22:35:30 +00001935 // Create a new string expression.
1936 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlsson85f9bce2007-10-29 05:01:08 +00001937 std::string StrEncoding;
Daniel Dunbar0d504c12008-10-17 20:21:44 +00001938 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattner2085fd62009-02-18 06:40:38 +00001939 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1940 StrEncoding.length(), false,StrType,
1941 SourceLocation());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001942 ReplaceStmt(Exp, Replacement);
Mike Stump1eb44332009-09-09 15:08:12 +00001943
Chris Lattner07506182007-11-30 22:53:43 +00001944 // Replace this subexpr in the parent.
Steve Naroff4c3580e2008-12-04 23:50:32 +00001945 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattnere64b7772007-10-24 16:57:36 +00001946 return Replacement;
Chris Lattner311ff022007-10-16 22:36:42 +00001947}
1948
Steve Naroffb29b4272008-04-14 22:03:09 +00001949Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff1a937642008-12-22 22:16:07 +00001950 if (!SelGetUidFunctionDecl)
1951 SynthSelGetUidFunctionDecl();
Steve Naroffb42f8412007-11-05 14:50:49 +00001952 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1953 // Create a call to sel_registerName("selName").
1954 llvm::SmallVector<Expr*, 8> SelExprs;
1955 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001956 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00001957 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00001958 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00001959 false, argType, SourceLocation()));
Steve Naroffb42f8412007-11-05 14:50:49 +00001960 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1961 &SelExprs[0], SelExprs.size());
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00001962 ReplaceStmt(Exp, SelExp);
Steve Naroff4c3580e2008-12-04 23:50:32 +00001963 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb42f8412007-11-05 14:50:49 +00001964 return SelExp;
1965}
1966
Steve Naroffb29b4272008-04-14 22:03:09 +00001967CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff934f2762007-10-24 22:48:43 +00001968 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffebf2b562007-10-23 23:50:29 +00001969 // Get the type, we will need to reference it in a couple spots.
Steve Naroff934f2762007-10-24 22:48:43 +00001970 QualType msgSendType = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00001971
Steve Naroffebf2b562007-10-23 23:50:29 +00001972 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek8189cde2009-02-07 01:47:29 +00001973 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00001974
Steve Naroffebf2b562007-10-23 23:50:29 +00001975 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattnerf04da132007-10-24 17:06:59 +00001976 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump1eb44332009-09-09 15:08:12 +00001977 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssoncdef2b72009-07-31 00:48:10 +00001978 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00001979 DRE,
Douglas Gregoreb8f3062008-11-12 17:17:38 +00001980 /*isLvalue=*/false);
Mike Stump1eb44332009-09-09 15:08:12 +00001981
John McCall183700f2009-09-21 23:43:11 +00001982 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump1eb44332009-09-09 15:08:12 +00001983
Ted Kremenek668bf912009-02-09 20:51:47 +00001984 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1985 SourceLocation());
Steve Naroff934f2762007-10-24 22:48:43 +00001986}
1987
Steve Naroffd5255f52007-11-01 13:24:47 +00001988static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1989 const char *&startRef, const char *&endRef) {
1990 while (startBuf < endBuf) {
1991 if (*startBuf == '<')
1992 startRef = startBuf; // mark the start.
1993 if (*startBuf == '>') {
Steve Naroff32174822007-11-09 12:50:28 +00001994 if (startRef && *startRef == '<') {
1995 endRef = startBuf; // mark the end.
1996 return true;
1997 }
1998 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00001999 }
2000 startBuf++;
2001 }
2002 return false;
2003}
2004
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002005static void scanToNextArgument(const char *&argRef) {
2006 int angle = 0;
2007 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2008 if (*argRef == '<')
2009 angle++;
2010 else if (*argRef == '>')
2011 angle--;
2012 argRef++;
2013 }
2014 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2015}
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002016
Steve Naroffb29b4272008-04-14 22:03:09 +00002017bool RewriteObjC::needToScanForQualifiers(QualType T) {
Fariborz Jahanian32132a02010-02-03 21:29:28 +00002018 if (T->isObjCQualifiedIdType())
2019 return true;
Fariborz Jahanian84aa9462010-02-02 18:35:07 +00002020 if (const PointerType *PT = T->getAs<PointerType>()) {
2021 if (PT->getPointeeType()->isObjCQualifiedIdType())
2022 return true;
2023 }
2024 if (T->isObjCObjectPointerType()) {
2025 T = T->getPointeeType();
2026 return T->isObjCQualifiedInterfaceType();
2027 }
2028 return false;
Steve Naroffd5255f52007-11-01 13:24:47 +00002029}
2030
Steve Naroff4f95b752008-07-29 18:15:38 +00002031void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2032 QualType Type = E->getType();
2033 if (needToScanForQualifiers(Type)) {
Steve Naroffcda658e2008-11-19 21:15:47 +00002034 SourceLocation Loc, EndLoc;
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Steve Naroffcda658e2008-11-19 21:15:47 +00002036 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2037 Loc = ECE->getLParenLoc();
2038 EndLoc = ECE->getRParenLoc();
2039 } else {
2040 Loc = E->getLocStart();
2041 EndLoc = E->getLocEnd();
2042 }
2043 // This will defend against trying to rewrite synthesized expressions.
2044 if (Loc.isInvalid() || EndLoc.isInvalid())
2045 return;
2046
Steve Naroff4f95b752008-07-29 18:15:38 +00002047 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffcda658e2008-11-19 21:15:47 +00002048 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff4f95b752008-07-29 18:15:38 +00002049 const char *startRef = 0, *endRef = 0;
2050 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2051 // Get the locations of the startRef, endRef.
2052 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
2053 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
2054 // Comment out the protocol references.
2055 InsertText(LessLoc, "/*", 2);
2056 InsertText(GreaterLoc, "*/", 2);
2057 }
2058 }
2059}
2060
Steve Naroffb29b4272008-04-14 22:03:09 +00002061void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002062 SourceLocation Loc;
2063 QualType Type;
Douglas Gregor72564e72009-02-26 23:50:07 +00002064 const FunctionProtoType *proto = 0;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002065 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2066 Loc = VD->getLocation();
2067 Type = VD->getType();
2068 }
2069 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2070 Loc = FD->getLocation();
2071 // Check for ObjC 'id' and class types that have been adorned with protocol
2072 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall183700f2009-09-21 23:43:11 +00002073 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002074 assert(funcType && "missing function type");
Douglas Gregor72564e72009-02-26 23:50:07 +00002075 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002076 if (!proto)
2077 return;
2078 Type = proto->getResultType();
2079 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00002080 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2081 Loc = FD->getLocation();
2082 Type = FD->getType();
2083 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002084 else
2085 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002086
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002087 if (needToScanForQualifiers(Type)) {
Steve Naroffd5255f52007-11-01 13:24:47 +00002088 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002089
Steve Naroffd5255f52007-11-01 13:24:47 +00002090 const char *endBuf = SM->getCharacterData(Loc);
2091 const char *startBuf = endBuf;
Steve Naroff6cafbf22008-05-31 05:02:17 +00002092 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroffd5255f52007-11-01 13:24:47 +00002093 startBuf--; // scan backward (from the decl location) for return type.
2094 const char *startRef = 0, *endRef = 0;
2095 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2096 // Get the locations of the startRef, endRef.
2097 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2098 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2099 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002100 InsertText(LessLoc, "/*", 2);
2101 InsertText(GreaterLoc, "*/", 2);
Steve Naroff9165ad32007-10-31 04:38:33 +00002102 }
2103 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002104 if (!proto)
2105 return; // most likely, was a variable
Steve Naroffd5255f52007-11-01 13:24:47 +00002106 // Now check arguments.
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002107 const char *startBuf = SM->getCharacterData(Loc);
2108 const char *startFuncBuf = startBuf;
Steve Naroffd5255f52007-11-01 13:24:47 +00002109 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2110 if (needToScanForQualifiers(proto->getArgType(i))) {
2111 // Since types are unique, we need to scan the buffer.
Mike Stump1eb44332009-09-09 15:08:12 +00002112
Steve Naroffd5255f52007-11-01 13:24:47 +00002113 const char *endBuf = startBuf;
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002114 // scan forward (from the decl location) for argument types.
2115 scanToNextArgument(endBuf);
Steve Naroffd5255f52007-11-01 13:24:47 +00002116 const char *startRef = 0, *endRef = 0;
2117 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2118 // Get the locations of the startRef, endRef.
Mike Stump1eb44332009-09-09 15:08:12 +00002119 SourceLocation LessLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002120 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump1eb44332009-09-09 15:08:12 +00002121 SourceLocation GreaterLoc =
Fariborz Jahanian291e04b2007-12-11 23:04:08 +00002122 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroffd5255f52007-11-01 13:24:47 +00002123 // Comment out the protocol references.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002124 InsertText(LessLoc, "/*", 2);
2125 InsertText(GreaterLoc, "*/", 2);
Steve Naroffd5255f52007-11-01 13:24:47 +00002126 }
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002127 startBuf = ++endBuf;
2128 }
2129 else {
Steve Naroffaba49d12008-08-06 15:58:23 +00002130 // If the function name is derived from a macro expansion, then the
2131 // argument buffer will not follow the name. Need to speak with Chris.
2132 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian61477f72007-12-11 22:50:14 +00002133 startBuf++; // scan forward (from the decl location) for argument types.
2134 startBuf++;
2135 }
Steve Naroffd5255f52007-11-01 13:24:47 +00002136 }
Steve Naroff9165ad32007-10-31 04:38:33 +00002137}
2138
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002139// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroffb29b4272008-04-14 22:03:09 +00002140void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002141 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2142 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002143 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002144 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002145 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002146 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002147 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002148 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002149 SelGetUidIdent, getFuncType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002150 FunctionDecl::Extern, false);
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002151}
2152
Steve Naroffb29b4272008-04-14 22:03:09 +00002153void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002154 // declared in <objc/objc.h>
Douglas Gregor51efe562009-01-09 01:47:02 +00002155 if (FD->getIdentifier() &&
2156 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff09b266e2007-10-30 23:14:51 +00002157 SelGetUidFunctionDecl = FD;
Steve Naroff9165ad32007-10-31 04:38:33 +00002158 return;
2159 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002160 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff09b266e2007-10-30 23:14:51 +00002161}
2162
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00002163void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2164 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2165 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2166 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2167 if (!proto)
2168 return;
2169 QualType Type = proto->getResultType();
2170 std::string FdStr = Type.getAsString();
2171 FdStr += " ";
2172 FdStr += FD->getNameAsCString();
2173 FdStr += "(";
2174 unsigned numArgs = proto->getNumArgs();
2175 for (unsigned i = 0; i < numArgs; i++) {
2176 QualType ArgType = proto->getArgType(i);
2177 FdStr += ArgType.getAsString();
2178
2179 if (i+1 < numArgs)
2180 FdStr += ", ";
2181 }
2182 FdStr += ");\n";
2183 InsertText(FunLocStart, FdStr.c_str(), FdStr.size());
2184 CurFunctionDeclToDeclareForBlock = 0;
2185}
2186
Steve Naroffc0a123c2008-03-11 17:37:02 +00002187// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroffb29b4272008-04-14 22:03:09 +00002188void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroffc0a123c2008-03-11 17:37:02 +00002189 if (SuperContructorFunctionDecl)
2190 return;
Steve Naroff46a98a72008-12-23 20:11:22 +00002191 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroffc0a123c2008-03-11 17:37:02 +00002192 llvm::SmallVector<QualType, 16> ArgTys;
2193 QualType argT = Context->getObjCIdType();
2194 assert(!argT.isNull() && "Can't find 'id' type");
2195 ArgTys.push_back(argT);
2196 ArgTys.push_back(argT);
2197 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2198 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002199 false, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002200 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002201 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002202 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002203 FunctionDecl::Extern, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002204}
2205
Steve Naroff09b266e2007-10-30 23:14:51 +00002206// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002207void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002208 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2209 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002210 QualType argT = Context->getObjCIdType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002211 assert(!argT.isNull() && "Can't find 'id' type");
2212 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002213 argT = Context->getObjCSelType();
Steve Naroff09b266e2007-10-30 23:14:51 +00002214 assert(!argT.isNull() && "Can't find 'SEL' type");
2215 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002216 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002217 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002218 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002219 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002220 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002221 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002222 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002223}
2224
Steve Naroff874e2322007-11-15 10:28:18 +00002225// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002226void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff874e2322007-11-15 10:28:18 +00002227 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2228 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002229 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002230 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002231 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002232 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2233 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2234 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002235 argT = Context->getObjCSelType();
Steve Naroff874e2322007-11-15 10:28:18 +00002236 assert(!argT.isNull() && "Can't find 'SEL' type");
2237 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002238 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff874e2322007-11-15 10:28:18 +00002239 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002240 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002241 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002242 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002243 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002244 FunctionDecl::Extern, false);
Steve Naroff874e2322007-11-15 10:28:18 +00002245}
2246
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002247// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002248void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002249 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2250 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002251 QualType argT = Context->getObjCIdType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002252 assert(!argT.isNull() && "Can't find 'id' type");
2253 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002254 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002255 assert(!argT.isNull() && "Can't find 'SEL' type");
2256 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002257 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002258 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002259 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002260 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002261 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002262 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002263 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002264}
2265
Mike Stump1eb44332009-09-09 15:08:12 +00002266// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002267// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002268void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump1eb44332009-09-09 15:08:12 +00002269 IdentifierInfo *msgSendIdent =
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002270 &Context->Idents.get("objc_msgSendSuper_stret");
2271 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002272 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattner0ed844b2008-04-04 06:12:32 +00002273 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002274 &Context->Idents.get("objc_super"));
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002275 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2276 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2277 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002278 argT = Context->getObjCSelType();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002279 assert(!argT.isNull() && "Can't find 'SEL' type");
2280 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002281 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002282 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002283 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002284 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002285 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002286 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002287 FunctionDecl::Extern, false);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002288}
2289
Steve Naroff1284db82008-05-08 22:02:18 +00002290// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroffb29b4272008-04-14 22:03:09 +00002291void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002292 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2293 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002294 QualType argT = Context->getObjCIdType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002295 assert(!argT.isNull() && "Can't find 'id' type");
2296 ArgTys.push_back(argT);
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002297 argT = Context->getObjCSelType();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002298 assert(!argT.isNull() && "Can't find 'SEL' type");
2299 ArgTys.push_back(argT);
Steve Naroff1284db82008-05-08 22:02:18 +00002300 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002301 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002302 true /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002303 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002304 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002305 msgSendIdent, msgSendType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002306 FunctionDecl::Extern, false);
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002307}
2308
Steve Naroff09b266e2007-10-30 23:14:51 +00002309// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002310void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff09b266e2007-10-30 23:14:51 +00002311 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2312 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002313 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002314 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff09b266e2007-10-30 23:14:51 +00002315 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002316 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002317 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002318 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002319 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002320 FunctionDecl::Extern, false);
Steve Naroff09b266e2007-10-30 23:14:51 +00002321}
2322
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002323// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroffb29b4272008-04-14 22:03:09 +00002324void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002325 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2326 llvm::SmallVector<QualType, 16> ArgTys;
John McCall0953e762009-09-24 19:53:00 +00002327 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002328 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002329 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002330 false /*isVariadic*/, 0);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00002331 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002332 SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002333 getClassIdent, getClassType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002334 FunctionDecl::Extern, false);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002335}
2336
Steve Naroffb29b4272008-04-14 22:03:09 +00002337Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002338 QualType strType = getConstantStringStructType();
2339
2340 std::string S = "__NSConstantStringImpl_";
Steve Naroff7691d9b2008-05-31 03:35:42 +00002341
2342 std::string tmpName = InFileName;
2343 unsigned i;
2344 for (i=0; i < tmpName.length(); i++) {
2345 char c = tmpName.at(i);
2346 // replace any non alphanumeric characters with '_'.
2347 if (!isalpha(c) && (c < '0' || c > '9'))
2348 tmpName[i] = '_';
2349 }
2350 S += tmpName;
2351 S += "_";
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002352 S += utostr(NumObjCStringLiterals++);
2353
Steve Naroffba92b2e2008-03-27 22:29:16 +00002354 Preamble += "static __NSConstantStringImpl " + S;
2355 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2356 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002357 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremeneka95d3752008-09-13 05:16:45 +00002358 std::string prettyBufS;
2359 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnere4f21422009-06-30 01:26:17 +00002360 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2361 PrintingPolicy(LangOpts));
Steve Naroffba92b2e2008-03-27 22:29:16 +00002362 Preamble += prettyBuf.str();
2363 Preamble += ",";
Steve Narofffd5b76f2009-12-06 01:48:44 +00002364 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002365
2366 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2367 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002368 VarDecl::Static);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002369 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2370 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002371 Context->getPointerType(DRE->getType()),
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002372 SourceLocation());
Steve Naroff96984642007-11-08 14:30:50 +00002373 // cast to NSConstantString *
John McCall9d125032010-01-15 18:39:57 +00002374 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2375 CastExpr::CK_Unknown, Unop);
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002376 ReplaceStmt(Exp, cast);
Steve Naroff4c3580e2008-12-04 23:50:32 +00002377 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff96984642007-11-08 14:30:50 +00002378 return cast;
Steve Naroffbeaf2992007-11-03 11:27:19 +00002379}
2380
Steve Naroffb29b4272008-04-14 22:03:09 +00002381ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002382 // check if we are sending a message to 'super'
Douglas Gregorf8d49f62009-01-09 17:18:27 +00002383 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump1eb44332009-09-09 15:08:12 +00002384
Douglas Gregorcd9b46e2008-11-04 14:56:14 +00002385 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002386 const ObjCObjectPointerType *OPT =
John McCall183700f2009-09-21 23:43:11 +00002387 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff14108da2009-07-10 23:34:53 +00002388 assert(OPT);
2389 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattner0d17f6f2008-06-21 18:04:54 +00002390 return IT->getDecl();
2391 }
2392 return 0;
Steve Naroff874e2322007-11-15 10:28:18 +00002393}
2394
2395// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroffb29b4272008-04-14 22:03:09 +00002396QualType RewriteObjC::getSuperStructType() {
Steve Naroff874e2322007-11-15 10:28:18 +00002397 if (!SuperStructDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002398 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002399 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002400 &Context->Idents.get("objc_super"));
Steve Naroff874e2322007-11-15 10:28:18 +00002401 QualType FieldTypes[2];
Mike Stump1eb44332009-09-09 15:08:12 +00002402
Steve Naroff874e2322007-11-15 10:28:18 +00002403 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002404 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff874e2322007-11-15 10:28:18 +00002405 // struct objc_class *super;
Mike Stump1eb44332009-09-09 15:08:12 +00002406 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor44b43212008-12-11 16:49:14 +00002407
Steve Naroff874e2322007-11-15 10:28:18 +00002408 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002409 for (unsigned i = 0; i < 2; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002410 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2411 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002412 FieldTypes[i], 0,
2413 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002414 /*Mutable=*/false));
Douglas Gregor44b43212008-12-11 16:49:14 +00002415 }
Mike Stump1eb44332009-09-09 15:08:12 +00002416
Douglas Gregor44b43212008-12-11 16:49:14 +00002417 SuperStructDecl->completeDefinition(*Context);
Steve Naroff874e2322007-11-15 10:28:18 +00002418 }
2419 return Context->getTagDeclType(SuperStructDecl);
2420}
2421
Steve Naroffb29b4272008-04-14 22:03:09 +00002422QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002423 if (!ConstantStringDecl) {
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00002424 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002425 SourceLocation(),
Ted Kremenekdf042e62008-09-05 01:34:33 +00002426 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002427 QualType FieldTypes[4];
Mike Stump1eb44332009-09-09 15:08:12 +00002428
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002429 // struct objc_object *receiver;
Mike Stump1eb44332009-09-09 15:08:12 +00002430 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002431 // int flags;
Mike Stump1eb44332009-09-09 15:08:12 +00002432 FieldTypes[1] = Context->IntTy;
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002433 // char *str;
Mike Stump1eb44332009-09-09 15:08:12 +00002434 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002435 // long length;
Mike Stump1eb44332009-09-09 15:08:12 +00002436 FieldTypes[3] = Context->LongTy;
Douglas Gregor44b43212008-12-11 16:49:14 +00002437
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002438 // Create fields
Douglas Gregor44b43212008-12-11 16:49:14 +00002439 for (unsigned i = 0; i < 4; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +00002440 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2441 ConstantStringDecl,
Douglas Gregor44b43212008-12-11 16:49:14 +00002442 SourceLocation(), 0,
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00002443 FieldTypes[i], 0,
Douglas Gregor44b43212008-12-11 16:49:14 +00002444 /*BitWidth=*/0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00002445 /*Mutable=*/true));
Douglas Gregor44b43212008-12-11 16:49:14 +00002446 }
2447
2448 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffd82a9ab2008-03-15 00:55:56 +00002449 }
2450 return Context->getTagDeclType(ConstantStringDecl);
2451}
2452
Steve Naroffb29b4272008-04-14 22:03:09 +00002453Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahaniana70711b2007-12-04 21:47:40 +00002454 if (!SelGetUidFunctionDecl)
2455 SynthSelGetUidFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002456 if (!MsgSendFunctionDecl)
2457 SynthMsgSendFunctionDecl();
Steve Naroff874e2322007-11-15 10:28:18 +00002458 if (!MsgSendSuperFunctionDecl)
2459 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002460 if (!MsgSendStretFunctionDecl)
2461 SynthMsgSendStretFunctionDecl();
2462 if (!MsgSendSuperStretFunctionDecl)
2463 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002464 if (!MsgSendFpretFunctionDecl)
2465 SynthMsgSendFpretFunctionDecl();
Steve Naroff09b266e2007-10-30 23:14:51 +00002466 if (!GetClassFunctionDecl)
2467 SynthGetClassFunctionDecl();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002468 if (!GetMetaClassFunctionDecl)
2469 SynthGetMetaClassFunctionDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00002470
Steve Naroff874e2322007-11-15 10:28:18 +00002471 // default to objc_msgSend().
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002472 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2473 // May need to use objc_msgSend_stret() as well.
2474 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroff621edce2009-04-29 16:37:50 +00002475 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2476 QualType resultType = mDecl->getResultType();
Chris Lattner8b51fd72008-07-26 22:36:27 +00002477 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002478 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner8b51fd72008-07-26 22:36:27 +00002479 else if (resultType->isRealFloatingType())
Fariborz Jahanianacb49772007-12-03 21:26:48 +00002480 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002481 }
Mike Stump1eb44332009-09-09 15:08:12 +00002482
Steve Naroff934f2762007-10-24 22:48:43 +00002483 // Synthesize a call to objc_msgSend().
2484 llvm::SmallVector<Expr*, 8> MsgExprs;
2485 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump1eb44332009-09-09 15:08:12 +00002486
Steve Naroff934f2762007-10-24 22:48:43 +00002487 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2488 if (clsName) { // class message.
Steve Narofffc93d522008-07-24 19:44:33 +00002489 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2490 // the 'super' idiom within a class method.
Daniel Dunbar01eb9b92009-10-18 21:17:35 +00002491 if (clsName->getName() == "super") {
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002492 MsgSendFlavor = MsgSendSuperFunctionDecl;
2493 if (MsgSendStretFlavor)
2494 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2495 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002496
2497 ObjCInterfaceDecl *SuperDecl =
Steve Naroff54055232008-10-27 17:20:55 +00002498 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002499
2500 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002501
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002502 // set the receiver to self, the first argument to all methods.
Steve Naroff621edce2009-04-29 16:37:50 +00002503 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002504 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2505 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002506 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff621edce2009-04-29 16:37:50 +00002507 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002508 SourceLocation()))
2509 ); // set the 'receiver'.
Steve Naroff621edce2009-04-29 16:37:50 +00002510
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002511 llvm::SmallVector<Expr*, 8> ClsExprs;
2512 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002513 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002514 SuperDecl->getIdentifier()->getNameStart(),
2515 SuperDecl->getIdentifier()->getLength(),
2516 false, argType, SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002517 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002518 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002519 ClsExprs.size());
2520 // To turn off a warning, type-cast to 'id'
Douglas Gregor49badde2008-10-27 19:41:14 +00002521 InitExprs.push_back( // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002522 NoTypeInfoCStyleCastExpr(Context,
2523 Context->getObjCIdType(),
2524 CastExpr::CK_Unknown, Cls));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002525 // struct objc_super
2526 QualType superType = getSuperStructType();
Steve Naroff23f41272008-03-11 18:14:26 +00002527 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002528
Steve Naroff23f41272008-03-11 18:14:26 +00002529 if (LangOpts.Microsoft) {
2530 SynthSuperContructorFunctionDecl();
2531 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002532 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff23f41272008-03-11 18:14:26 +00002533 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002534 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002535 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002536 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002537 // The code for super is a little tricky to prevent collision with
2538 // the structure definition in the header. The rewriter has it's own
2539 // internal definition (__rw_objc_super) that is uses. This is why
2540 // we need the cast below. For example:
2541 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2542 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002543 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002544 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002545 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002546 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2547 Context->getPointerType(superType),
2548 CastExpr::CK_Unknown, SuperRep);
Mike Stump1eb44332009-09-09 15:08:12 +00002549 } else {
Steve Naroff23f41272008-03-11 18:14:26 +00002550 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002551 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2552 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002553 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002554 TypeSourceInfo *superTInfo
2555 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002556 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2557 superType, ILE, false);
Steve Naroff46a98a72008-12-23 20:11:22 +00002558 // struct objc_super *
Ted Kremenek8189cde2009-02-07 01:47:29 +00002559 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002560 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002561 SourceLocation());
Steve Naroff23f41272008-03-11 18:14:26 +00002562 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002563 MsgExprs.push_back(SuperRep);
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002564 } else {
2565 llvm::SmallVector<Expr*, 8> ClsExprs;
2566 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattner2085fd62009-02-18 06:40:38 +00002567 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002568 clsName->getNameStart(),
Chris Lattner2085fd62009-02-18 06:40:38 +00002569 clsName->getLength(),
2570 false, argType,
2571 SourceLocation()));
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002572 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002573 &ClsExprs[0],
Steve Naroff9bcb5fc2007-12-07 03:50:46 +00002574 ClsExprs.size());
2575 MsgExprs.push_back(Cls);
2576 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002577 } else { // instance message.
2578 Expr *recExpr = Exp->getReceiver();
Steve Naroff874e2322007-11-15 10:28:18 +00002579
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002580 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff874e2322007-11-15 10:28:18 +00002581 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002582 if (MsgSendStretFlavor)
2583 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff874e2322007-11-15 10:28:18 +00002584 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump1eb44332009-09-09 15:08:12 +00002585
Steve Naroff874e2322007-11-15 10:28:18 +00002586 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00002587
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002588 InitExprs.push_back(
John McCall9d125032010-01-15 18:39:57 +00002589 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2590 CastExpr::CK_Unknown,
Mike Stump1eb44332009-09-09 15:08:12 +00002591 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Narofff616ebb2008-07-16 22:35:27 +00002592 Context->getObjCIdType(),
John McCall9d125032010-01-15 18:39:57 +00002593 SourceLocation()))
2594 ); // set the 'receiver'.
Mike Stump1eb44332009-09-09 15:08:12 +00002595
Steve Naroff874e2322007-11-15 10:28:18 +00002596 llvm::SmallVector<Expr*, 8> ClsExprs;
2597 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002598 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbare013d682009-10-18 20:26:12 +00002599 SuperDecl->getIdentifier()->getNameStart(),
2600 SuperDecl->getIdentifier()->getLength(),
2601 false, argType, SourceLocation()));
Steve Naroff874e2322007-11-15 10:28:18 +00002602 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002603 &ClsExprs[0],
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002604 ClsExprs.size());
Fariborz Jahanian71274312007-12-05 17:29:46 +00002605 // To turn off a warning, type-cast to 'id'
Fariborz Jahanianceee3e82007-12-04 22:32:58 +00002606 InitExprs.push_back(
Douglas Gregor49badde2008-10-27 19:41:14 +00002607 // set 'super class', using objc_getClass().
John McCall9d125032010-01-15 18:39:57 +00002608 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2609 CastExpr::CK_Unknown, Cls));
Steve Naroff874e2322007-11-15 10:28:18 +00002610 // struct objc_super
2611 QualType superType = getSuperStructType();
Steve Naroffc0a123c2008-03-11 17:37:02 +00002612 Expr *SuperRep;
Mike Stump1eb44332009-09-09 15:08:12 +00002613
Steve Naroffc0a123c2008-03-11 17:37:02 +00002614 if (LangOpts.Microsoft) {
2615 SynthSuperContructorFunctionDecl();
2616 // Simulate a contructor call...
Mike Stump1eb44332009-09-09 15:08:12 +00002617 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroffc0a123c2008-03-11 17:37:02 +00002618 superType, SourceLocation());
Ted Kremenek668bf912009-02-09 20:51:47 +00002619 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002620 InitExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002621 superType, SourceLocation());
Steve Naroff46a98a72008-12-23 20:11:22 +00002622 // The code for super is a little tricky to prevent collision with
2623 // the structure definition in the header. The rewriter has it's own
2624 // internal definition (__rw_objc_super) that is uses. This is why
2625 // we need the cast below. For example:
2626 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2627 //
Ted Kremenek8189cde2009-02-07 01:47:29 +00002628 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00002629 Context->getPointerType(SuperRep->getType()),
Steve Naroff46a98a72008-12-23 20:11:22 +00002630 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002631 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2632 Context->getPointerType(superType),
2633 CastExpr::CK_Unknown, SuperRep);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002634 } else {
2635 // (struct objc_super) { <exprs from above> }
Mike Stump1eb44332009-09-09 15:08:12 +00002636 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2637 &InitExprs[0], InitExprs.size(),
Douglas Gregor4c678342009-01-28 21:54:33 +00002638 SourceLocation());
John McCall42f56b52010-01-18 19:35:47 +00002639 TypeSourceInfo *superTInfo
2640 = Context->getTrivialTypeSourceInfo(superType);
John McCall1d7d8d62010-01-19 22:33:45 +00002641 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2642 superType, ILE, false);
Steve Naroffc0a123c2008-03-11 17:37:02 +00002643 }
Steve Naroff46a98a72008-12-23 20:11:22 +00002644 MsgExprs.push_back(SuperRep);
Steve Naroff874e2322007-11-15 10:28:18 +00002645 } else {
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002646 // Remove all type-casts because it may contain objc-style types; e.g.
2647 // Foo<Proto> *.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002648 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanian7dd82832007-12-07 21:21:21 +00002649 recExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002650 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2651 CastExpr::CK_Unknown, recExpr);
Steve Naroff874e2322007-11-15 10:28:18 +00002652 MsgExprs.push_back(recExpr);
2653 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002654 }
Steve Naroffbeaf2992007-11-03 11:27:19 +00002655 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff934f2762007-10-24 22:48:43 +00002656 llvm::SmallVector<Expr*, 8> SelExprs;
2657 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002658 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6e94ef52009-02-06 19:55:15 +00002659 Exp->getSelector().getAsString().c_str(),
Chris Lattner077bf5e2008-11-24 03:33:13 +00002660 Exp->getSelector().getAsString().size(),
Chris Lattner726e1682009-02-18 05:49:11 +00002661 false, argType, SourceLocation()));
Steve Naroff934f2762007-10-24 22:48:43 +00002662 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2663 &SelExprs[0], SelExprs.size());
2664 MsgExprs.push_back(SelExp);
Mike Stump1eb44332009-09-09 15:08:12 +00002665
Steve Naroff934f2762007-10-24 22:48:43 +00002666 // Now push any user supplied arguments.
2667 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroff6568d4d2007-11-14 23:54:14 +00002668 Expr *userExpr = Exp->getArg(i);
Steve Naroff7e3411b2007-11-15 02:58:25 +00002669 // Make all implicit casts explicit...ICE comes in handy:-)
2670 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2671 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregor49badde2008-10-27 19:41:14 +00002672 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002673 ? Context->getObjCIdType()
Douglas Gregor49badde2008-10-27 19:41:14 +00002674 : ICE->getType();
John McCall9d125032010-01-15 18:39:57 +00002675 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CastExpr::CK_Unknown,
2676 userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002677 }
2678 // Make id<P...> cast into an 'id' cast.
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002679 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002680 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregor6eec8e82008-10-28 15:36:24 +00002681 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002682 userExpr = CE->getSubExpr();
John McCall9d125032010-01-15 18:39:57 +00002683 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2684 CastExpr::CK_Unknown, userExpr);
Fariborz Jahaniand58fabf2007-12-18 21:33:44 +00002685 }
Mike Stump1eb44332009-09-09 15:08:12 +00002686 }
Steve Naroff6568d4d2007-11-14 23:54:14 +00002687 MsgExprs.push_back(userExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002688 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2689 // out the argument in the original expression (since we aren't deleting
2690 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2691 //Exp->setArg(i, 0);
Steve Naroff934f2762007-10-24 22:48:43 +00002692 }
Steve Naroffab972d32007-11-04 22:37:50 +00002693 // Generate the funky cast.
2694 CastExpr *cast;
2695 llvm::SmallVector<QualType, 8> ArgTypes;
2696 QualType returnType;
Mike Stump1eb44332009-09-09 15:08:12 +00002697
Steve Naroffab972d32007-11-04 22:37:50 +00002698 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroffc3a438c2007-11-15 10:43:57 +00002699 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2700 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2701 else
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002702 ArgTypes.push_back(Context->getObjCIdType());
2703 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattner89951a82009-02-20 18:43:26 +00002704 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Naroffab972d32007-11-04 22:37:50 +00002705 // Push any user argument types.
Chris Lattner89951a82009-02-20 18:43:26 +00002706 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2707 E = OMD->param_end(); PI != E; ++PI) {
2708 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump1eb44332009-09-09 15:08:12 +00002709 ? Context->getObjCIdType()
Chris Lattner89951a82009-02-20 18:43:26 +00002710 : (*PI)->getType();
Steve Naroffa206b062008-10-29 14:49:46 +00002711 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00002712 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00002713 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffa206b062008-10-29 14:49:46 +00002714 t = Context->getPointerType(BPT->getPointeeType());
2715 }
Steve Naroff352336b2007-11-05 14:36:37 +00002716 ArgTypes.push_back(t);
2717 }
Chris Lattner89951a82009-02-20 18:43:26 +00002718 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2719 ? Context->getObjCIdType() : OMD->getResultType();
Steve Naroffab972d32007-11-04 22:37:50 +00002720 } else {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002721 returnType = Context->getObjCIdType();
Steve Naroffab972d32007-11-04 22:37:50 +00002722 }
2723 // Get the type, we will need to reference it in a couple spots.
Steve Naroff874e2322007-11-15 10:28:18 +00002724 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00002725
Steve Naroffab972d32007-11-04 22:37:50 +00002726 // Create a reference to the objc_msgSend() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002727 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002728 SourceLocation());
Steve Naroffab972d32007-11-04 22:37:50 +00002729
Mike Stump1eb44332009-09-09 15:08:12 +00002730 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Naroffab972d32007-11-04 22:37:50 +00002731 // If we don't do this cast, we get the following bizarre warning/note:
2732 // xx.m:13: warning: function called through a non-compatible type
2733 // xx.m:13: note: if this code is reached, the program will abort
John McCall9d125032010-01-15 18:39:57 +00002734 cast = NoTypeInfoCStyleCastExpr(Context,
2735 Context->getPointerType(Context->VoidTy),
2736 CastExpr::CK_Unknown, DRE);
Mike Stump1eb44332009-09-09 15:08:12 +00002737
Steve Naroffab972d32007-11-04 22:37:50 +00002738 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002739 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002740 &ArgTypes[0], ArgTypes.size(),
Steve Naroff2679e482008-03-18 02:02:04 +00002741 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002742 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Naroffab972d32007-11-04 22:37:50 +00002743 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002744 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2745 cast);
Steve Naroffab972d32007-11-04 22:37:50 +00002746
2747 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002748 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002749
John McCall183700f2009-09-21 23:43:11 +00002750 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002751 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002752 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002753 FT->getResultType(), SourceLocation());
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002754 Stmt *ReplacingStmt = CE;
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002755 if (MsgSendStretFlavor) {
2756 // We have the method which returns a struct/union. Must also generate
2757 // call to objc_msgSend_stret and hang both varieties on a conditional
2758 // expression which dictate which one to envoke depending on size of
2759 // method's return type.
Mike Stump1eb44332009-09-09 15:08:12 +00002760
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002761 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump1eb44332009-09-09 15:08:12 +00002762 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002763 SourceLocation());
2764 // Need to cast objc_msgSend_stret to "void *" (see above comment).
John McCall9d125032010-01-15 18:39:57 +00002765 cast = NoTypeInfoCStyleCastExpr(Context,
2766 Context->getPointerType(Context->VoidTy),
2767 CastExpr::CK_Unknown, STDRE);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002768 // Now do the "normal" pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00002769 castType = Context->getFunctionType(returnType,
Fariborz Jahaniand0ee6f92007-12-06 19:49:56 +00002770 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis7fb5e482008-10-26 16:43:14 +00002771 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002772 castType = Context->getPointerType(castType);
John McCall9d125032010-01-15 18:39:57 +00002773 cast = NoTypeInfoCStyleCastExpr(Context, castType, CastExpr::CK_Unknown,
2774 cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002775
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002776 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00002777 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump1eb44332009-09-09 15:08:12 +00002778
John McCall183700f2009-09-21 23:43:11 +00002779 FT = msgSendType->getAs<FunctionType>();
Ted Kremenek668bf912009-02-09 20:51:47 +00002780 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump1eb44332009-09-09 15:08:12 +00002781 MsgExprs.size(),
Ted Kremenek668bf912009-02-09 20:51:47 +00002782 FT->getResultType(), SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002783
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002784 // Build sizeof(returnType)
Mike Stump1eb44332009-09-09 15:08:12 +00002785 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCalla93c9342009-12-07 02:54:59 +00002786 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl05189992008-11-11 17:56:53 +00002787 Context->getSizeType(),
2788 SourceLocation(), SourceLocation());
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002789 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2790 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2791 // For X86 it is more complicated and some kind of target specific routine
2792 // is needed to decide what to do.
Mike Stump1eb44332009-09-09 15:08:12 +00002793 unsigned IntSize =
Chris Lattner98be4942008-03-05 18:54:05 +00002794 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump1eb44332009-09-09 15:08:12 +00002795 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002796 Context->IntTy,
2797 SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00002798 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2799 BinaryOperator::LE,
2800 Context->IntTy,
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002801 SourceLocation());
2802 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump1eb44332009-09-09 15:08:12 +00002803 ConditionalOperator *CondExpr =
Douglas Gregor47e1f7c2009-08-26 14:37:04 +00002804 new (Context) ConditionalOperator(lessThanExpr,
2805 SourceLocation(), CE,
2806 SourceLocation(), STCE, returnType);
Ted Kremenek8189cde2009-02-07 01:47:29 +00002807 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian80a6a5a2007-12-03 19:17:29 +00002808 }
Mike Stump1eb44332009-09-09 15:08:12 +00002809 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002810 return ReplacingStmt;
2811}
2812
Steve Naroffb29b4272008-04-14 22:03:09 +00002813Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002814 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Steve Naroff934f2762007-10-24 22:48:43 +00002816 // Now do the actual rewrite.
Chris Lattnerdcbc5b02008-01-31 19:37:57 +00002817 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00002818
2819 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian33b9c4e2008-01-08 22:06:28 +00002820 return ReplacingStmt;
Steve Naroffebf2b562007-10-23 23:50:29 +00002821}
2822
Steve Naroff621edce2009-04-29 16:37:50 +00002823// typedef struct objc_object Protocol;
2824QualType RewriteObjC::getProtocolType() {
2825 if (!ProtocolTypeDecl) {
John McCalla93c9342009-12-07 02:54:59 +00002826 TypeSourceInfo *TInfo
2827 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroff621edce2009-04-29 16:37:50 +00002828 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump1eb44332009-09-09 15:08:12 +00002829 SourceLocation(),
Steve Naroff621edce2009-04-29 16:37:50 +00002830 &Context->Idents.get("Protocol"),
John McCalla93c9342009-12-07 02:54:59 +00002831 TInfo);
Steve Naroff621edce2009-04-29 16:37:50 +00002832 }
2833 return Context->getTypeDeclType(ProtocolTypeDecl);
2834}
2835
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002836/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroff621edce2009-04-29 16:37:50 +00002837/// a synthesized/forward data reference (to the protocol's metadata).
2838/// The forward references (and metadata) are generated in
2839/// RewriteObjC::HandleTranslationUnit().
Steve Naroffb29b4272008-04-14 22:03:09 +00002840Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroff621edce2009-04-29 16:37:50 +00002841 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2842 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump1eb44332009-09-09 15:08:12 +00002843 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregor0da76df2009-11-23 11:41:28 +00002844 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroff621edce2009-04-29 16:37:50 +00002845 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2846 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2847 Context->getPointerType(DRE->getType()),
2848 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00002849 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2850 CastExpr::CK_Unknown,
2851 DerefExpr);
Steve Naroff621edce2009-04-29 16:37:50 +00002852 ReplaceStmt(Exp, castExpr);
2853 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump1eb44332009-09-09 15:08:12 +00002854 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff621edce2009-04-29 16:37:50 +00002855 return castExpr;
Mike Stump1eb44332009-09-09 15:08:12 +00002856
Fariborz Jahanian36ee2cb2007-12-07 18:47:10 +00002857}
2858
Mike Stump1eb44332009-09-09 15:08:12 +00002859bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffbaf58c32008-05-31 14:15:04 +00002860 const char *endBuf) {
2861 while (startBuf < endBuf) {
2862 if (*startBuf == '#') {
2863 // Skip whitespace.
2864 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2865 ;
2866 if (!strncmp(startBuf, "if", strlen("if")) ||
2867 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2868 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2869 !strncmp(startBuf, "define", strlen("define")) ||
2870 !strncmp(startBuf, "undef", strlen("undef")) ||
2871 !strncmp(startBuf, "else", strlen("else")) ||
2872 !strncmp(startBuf, "elif", strlen("elif")) ||
2873 !strncmp(startBuf, "endif", strlen("endif")) ||
2874 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2875 !strncmp(startBuf, "include", strlen("include")) ||
2876 !strncmp(startBuf, "import", strlen("import")) ||
2877 !strncmp(startBuf, "include_next", strlen("include_next")))
2878 return true;
2879 }
2880 startBuf++;
2881 }
2882 return false;
2883}
2884
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002885/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002886/// an objective-c class with ivars.
Steve Naroffb29b4272008-04-14 22:03:09 +00002887void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00002888 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002889 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump1eb44332009-09-09 15:08:12 +00002890 assert(CDecl->getNameAsCString() &&
Douglas Gregor2e1cd422008-11-17 14:58:09 +00002891 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002892 // Do not synthesize more than once.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002893 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian212b7682007-10-31 23:08:24 +00002894 return;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002895 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002896 int NumIvars = CDecl->ivar_size();
Steve Narofffea763e82007-11-14 19:25:57 +00002897 SourceLocation LocStart = CDecl->getLocStart();
2898 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00002899
Steve Narofffea763e82007-11-14 19:25:57 +00002900 const char *startBuf = SM->getCharacterData(LocStart);
2901 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump1eb44332009-09-09 15:08:12 +00002902
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002903 // If no ivars and no root or if its root, directly or indirectly,
2904 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattnerf3a7af92008-03-16 21:08:55 +00002905 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2906 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner2c78b872009-04-14 23:22:57 +00002907 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattneraadaf782008-01-31 19:51:04 +00002908 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002909 return;
2910 }
Mike Stump1eb44332009-09-09 15:08:12 +00002911
2912 // FIXME: This has potential of causing problem. If
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002913 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahanian2c7038b2007-11-26 19:52:57 +00002914 Result += "\nstruct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002915 Result += CDecl->getNameAsString();
Steve Naroff61ed9ca2008-03-10 23:16:54 +00002916 if (LangOpts.Microsoft)
2917 Result += "_IMPL";
Steve Naroff05b8c782008-03-12 00:25:36 +00002918
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002919 if (NumIvars > 0) {
Steve Narofffea763e82007-11-14 19:25:57 +00002920 const char *cursor = strchr(startBuf, '{');
Mike Stump1eb44332009-09-09 15:08:12 +00002921 assert((cursor && endBuf)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002922 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffbaf58c32008-05-31 14:15:04 +00002923 // If the buffer contains preprocessor directives, we do more fine-grained
2924 // rewrites. This is intended to fix code that looks like (which occurs in
2925 // NSURL.h, for example):
2926 //
2927 // #ifdef XYZ
2928 // @interface Foo : NSObject
2929 // #else
2930 // @interface FooBar : NSObject
2931 // #endif
2932 // {
2933 // int i;
2934 // }
2935 // @end
2936 //
2937 // This clause is segregated to avoid breaking the common case.
2938 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump1eb44332009-09-09 15:08:12 +00002939 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffbaf58c32008-05-31 14:15:04 +00002940 CDecl->getClassLoc();
2941 const char *endHeader = SM->getCharacterData(L);
Chris Lattner2c78b872009-04-14 23:22:57 +00002942 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffbaf58c32008-05-31 14:15:04 +00002943
Chris Lattnercafeb352009-02-20 18:18:36 +00002944 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffbaf58c32008-05-31 14:15:04 +00002945 // advance to the end of the referenced protocols.
2946 while (endHeader < cursor && *endHeader != '>') endHeader++;
2947 endHeader++;
2948 }
2949 // rewrite the original header
2950 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2951 } else {
2952 // rewrite the original header *without* disturbing the '{'
Steve Naroff17c87782009-12-04 21:36:32 +00002953 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffbaf58c32008-05-31 14:15:04 +00002954 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00002955 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Narofffea763e82007-11-14 19:25:57 +00002956 Result = "\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002957 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00002958 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00002959 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00002960 Result += "_IVARS;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00002961
Steve Narofffea763e82007-11-14 19:25:57 +00002962 // insert the super class structure definition.
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002963 SourceLocation OnePastCurly =
2964 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2965 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Narofffea763e82007-11-14 19:25:57 +00002966 }
2967 cursor++; // past '{'
Mike Stump1eb44332009-09-09 15:08:12 +00002968
Steve Narofffea763e82007-11-14 19:25:57 +00002969 // Now comment out any visibility specifiers.
2970 while (cursor < endBuf) {
2971 if (*cursor == '@') {
2972 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerdf6a51b2007-11-14 22:57:51 +00002973 // Skip whitespace.
2974 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2975 /*scan*/;
2976
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002977 // FIXME: presence of @public, etc. inside comment results in
2978 // this transformation as well, which is still correct c-code.
Steve Narofffea763e82007-11-14 19:25:57 +00002979 if (!strncmp(cursor, "public", strlen("public")) ||
2980 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffc5e32772008-04-04 22:34:24 +00002981 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanian95673922007-11-14 22:26:25 +00002982 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002983 InsertText(atLoc, "// ", 3);
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00002984 }
Fariborz Jahanian95673922007-11-14 22:26:25 +00002985 // FIXME: If there are cases where '<' is used in ivar declaration part
2986 // of user code, then scan the ivar list and use needToScanForQualifiers
2987 // for type checking.
2988 else if (*cursor == '<') {
2989 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002990 InsertText(atLoc, "/* ", 3);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002991 cursor = strchr(cursor, '>');
2992 cursor++;
2993 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00002994 InsertText(atLoc, " */", 3);
Steve Naroffced80a82008-10-30 12:09:33 +00002995 } else if (*cursor == '^') { // rewrite block specifier.
2996 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2997 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanian95673922007-11-14 22:26:25 +00002998 }
Steve Narofffea763e82007-11-14 19:25:57 +00002999 cursor++;
Fariborz Jahanianfdc08a02007-10-31 17:29:28 +00003000 }
Steve Narofffea763e82007-11-14 19:25:57 +00003001 // Don't forget to add a ';'!!
Chris Lattnerf3dd57e2008-01-31 19:42:41 +00003002 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Narofffea763e82007-11-14 19:25:57 +00003003 } else { // we don't have any instance variables - insert super struct.
Chris Lattner2c78b872009-04-14 23:22:57 +00003004 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Narofffea763e82007-11-14 19:25:57 +00003005 Result += " {\n struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003006 Result += RCDecl->getNameAsString();
Steve Naroff39bbd9f2008-03-12 21:09:20 +00003007 Result += "_IMPL ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003008 Result += RCDecl->getNameAsString();
Steve Naroff819173c2008-03-12 21:22:52 +00003009 Result += "_IVARS;\n};\n";
Chris Lattneraadaf782008-01-31 19:51:04 +00003010 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003011 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003012 // Mark this struct as having been generated.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003013 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Narofffbfe8252008-05-06 18:26:51 +00003014 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003015}
3016
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003017// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003018/// class methods.
Douglas Gregor653f1b12009-04-23 01:02:12 +00003019template<typename MethodIterator>
3020void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
3021 MethodIterator MethodEnd,
Fariborz Jahanian8e991ba2007-10-25 00:14:44 +00003022 bool IsInstanceMethod,
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003023 const char *prefix,
Chris Lattner158ecb92007-10-25 17:07:24 +00003024 const char *ClassName,
3025 std::string &Result) {
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003026 if (MethodBegin == MethodEnd) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003027
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003028 if (!objc_impl_method) {
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003029 /* struct _objc_method {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003030 SEL _cmd;
3031 char *method_types;
3032 void *_imp;
3033 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003034 */
Chris Lattner158ecb92007-10-25 17:07:24 +00003035 Result += "\nstruct _objc_method {\n";
3036 Result += "\tSEL _cmd;\n";
3037 Result += "\tchar *method_types;\n";
3038 Result += "\tvoid *_imp;\n";
3039 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003040
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003041 objc_impl_method = true;
Fariborz Jahanian776d6ff2007-10-19 00:36:46 +00003042 }
Mike Stump1eb44332009-09-09 15:08:12 +00003043
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003044 // Build _objc_method_list for class's methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003045
Steve Naroff946a6932008-03-11 00:12:29 +00003046 /* struct {
3047 struct _objc_method_list *next_method;
3048 int method_count;
3049 struct _objc_method method_list[];
3050 }
3051 */
Douglas Gregor653f1b12009-04-23 01:02:12 +00003052 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroff946a6932008-03-11 00:12:29 +00003053 Result += "\nstatic struct {\n";
3054 Result += "\tstruct _objc_method_list *next_method;\n";
3055 Result += "\tint method_count;\n";
3056 Result += "\tstruct _objc_method method_list[";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003057 Result += utostr(NumMethods);
Steve Naroff946a6932008-03-11 00:12:29 +00003058 Result += "];\n} _OBJC_";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003059 Result += prefix;
3060 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
3061 Result += "_METHODS_";
3062 Result += ClassName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003063 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003064 Result += IsInstanceMethod ? "inst" : "cls";
3065 Result += "_meth\")))= ";
Douglas Gregor653f1b12009-04-23 01:02:12 +00003066 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003067
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003068 Result += "\t,{{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003069 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003070 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003071 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003072 Result += "\", \"";
3073 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003074 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003075 Result += MethodInternalNames[*MethodBegin];
3076 Result += "}\n";
3077 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
3078 Result += "\t ,{(SEL)\"";
Chris Lattner077bf5e2008-11-24 03:33:13 +00003079 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003080 std::string MethodTypeString;
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003081 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian33e1d642007-10-29 22:57:28 +00003082 Result += "\", \"";
3083 Result += MethodTypeString;
Steve Naroff946a6932008-03-11 00:12:29 +00003084 Result += "\", (void *)";
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003085 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanianb7908b52007-11-13 21:02:00 +00003086 Result += "}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003087 }
Chris Lattnerab4c4d52007-12-12 07:46:12 +00003088 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003089}
3090
Steve Naroff621edce2009-04-29 16:37:50 +00003091/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner780f3292008-07-21 21:32:27 +00003092void RewriteObjC::
Steve Naroff621edce2009-04-29 16:37:50 +00003093RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
3094 const char *ClassName, std::string &Result) {
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003095 static bool objc_protocol_methods = false;
Steve Naroff621edce2009-04-29 16:37:50 +00003096
3097 // Output struct protocol_methods holder of method selector and type.
3098 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
3099 /* struct protocol_methods {
3100 SEL _cmd;
3101 char *method_types;
3102 }
3103 */
3104 Result += "\nstruct _protocol_methods {\n";
3105 Result += "\tstruct objc_selector *_cmd;\n";
3106 Result += "\tchar *method_types;\n";
3107 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003108
Steve Naroff621edce2009-04-29 16:37:50 +00003109 objc_protocol_methods = true;
3110 }
3111 // Do not synthesize the protocol more than once.
3112 if (ObjCSynthesizedProtocols.count(PDecl))
3113 return;
Mike Stump1eb44332009-09-09 15:08:12 +00003114
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003115 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3116 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3117 PDecl->instmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003118 /* struct _objc_protocol_method_list {
3119 int protocol_method_count;
3120 struct protocol_methods protocols[];
3121 }
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003122 */
Steve Naroff621edce2009-04-29 16:37:50 +00003123 Result += "\nstatic struct {\n";
3124 Result += "\tint protocol_method_count;\n";
3125 Result += "\tstruct _protocol_methods protocol_methods[";
3126 Result += utostr(NumMethods);
3127 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3128 Result += PDecl->getNameAsString();
3129 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3130 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003131
Steve Naroff621edce2009-04-29 16:37:50 +00003132 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003133 for (ObjCProtocolDecl::instmeth_iterator
3134 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003135 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003136 if (I == PDecl->instmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003137 Result += "\t ,{{(struct objc_selector *)\"";
3138 else
3139 Result += "\t ,{(struct objc_selector *)\"";
3140 Result += (*I)->getSelector().getAsString().c_str();
3141 std::string MethodTypeString;
3142 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3143 Result += "\", \"";
3144 Result += MethodTypeString;
3145 Result += "\"}\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003146 }
Steve Naroff621edce2009-04-29 16:37:50 +00003147 Result += "\t }\n};\n";
3148 }
Mike Stump1eb44332009-09-09 15:08:12 +00003149
Steve Naroff621edce2009-04-29 16:37:50 +00003150 // Output class methods declared in this protocol.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003151 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3152 PDecl->classmeth_end());
Steve Naroff621edce2009-04-29 16:37:50 +00003153 if (NumMethods > 0) {
3154 /* struct _objc_protocol_method_list {
3155 int protocol_method_count;
3156 struct protocol_methods protocols[];
3157 }
3158 */
3159 Result += "\nstatic struct {\n";
3160 Result += "\tint protocol_method_count;\n";
3161 Result += "\tstruct _protocol_methods protocol_methods[";
3162 Result += utostr(NumMethods);
3163 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3164 Result += PDecl->getNameAsString();
3165 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3166 "{\n\t";
3167 Result += utostr(NumMethods);
3168 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003169
Steve Naroff621edce2009-04-29 16:37:50 +00003170 // Output instance methods declared in this protocol.
Mike Stump1eb44332009-09-09 15:08:12 +00003171 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003172 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroff621edce2009-04-29 16:37:50 +00003173 I != E; ++I) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003174 if (I == PDecl->classmeth_begin())
Steve Naroff621edce2009-04-29 16:37:50 +00003175 Result += "\t ,{{(struct objc_selector *)\"";
3176 else
3177 Result += "\t ,{(struct objc_selector *)\"";
3178 Result += (*I)->getSelector().getAsString().c_str();
3179 std::string MethodTypeString;
3180 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3181 Result += "\", \"";
3182 Result += MethodTypeString;
3183 Result += "\"}\n";
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003184 }
Steve Naroff621edce2009-04-29 16:37:50 +00003185 Result += "\t }\n};\n";
3186 }
3187
3188 // Output:
3189 /* struct _objc_protocol {
3190 // Objective-C 1.0 extensions
3191 struct _objc_protocol_extension *isa;
3192 char *protocol_name;
3193 struct _objc_protocol **protocol_list;
3194 struct _objc_protocol_method_list *instance_methods;
3195 struct _objc_protocol_method_list *class_methods;
Mike Stump1eb44332009-09-09 15:08:12 +00003196 };
Steve Naroff621edce2009-04-29 16:37:50 +00003197 */
3198 static bool objc_protocol = false;
3199 if (!objc_protocol) {
3200 Result += "\nstruct _objc_protocol {\n";
3201 Result += "\tstruct _objc_protocol_extension *isa;\n";
3202 Result += "\tchar *protocol_name;\n";
3203 Result += "\tstruct _objc_protocol **protocol_list;\n";
3204 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3205 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003206 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003207
Steve Naroff621edce2009-04-29 16:37:50 +00003208 objc_protocol = true;
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003209 }
Mike Stump1eb44332009-09-09 15:08:12 +00003210
Steve Naroff621edce2009-04-29 16:37:50 +00003211 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3212 Result += PDecl->getNameAsString();
3213 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3214 "{\n\t0, \"";
3215 Result += PDecl->getNameAsString();
3216 Result += "\", 0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003217 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003218 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3219 Result += PDecl->getNameAsString();
3220 Result += ", ";
3221 }
3222 else
3223 Result += "0, ";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003224 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroff621edce2009-04-29 16:37:50 +00003225 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3226 Result += PDecl->getNameAsString();
3227 Result += "\n";
3228 }
3229 else
3230 Result += "0\n";
3231 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003232
Steve Naroff621edce2009-04-29 16:37:50 +00003233 // Mark this protocol as having been generated.
3234 if (!ObjCSynthesizedProtocols.insert(PDecl))
3235 assert(false && "protocol already synthesized");
3236
3237}
3238
3239void RewriteObjC::
3240RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3241 const char *prefix, const char *ClassName,
3242 std::string &Result) {
3243 if (Protocols.empty()) return;
Mike Stump1eb44332009-09-09 15:08:12 +00003244
Steve Naroff621edce2009-04-29 16:37:50 +00003245 for (unsigned i = 0; i != Protocols.size(); i++)
3246 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3247
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003248 // Output the top lovel protocol meta-data for the class.
3249 /* struct _objc_protocol_list {
3250 struct _objc_protocol_list *next;
3251 int protocol_count;
3252 struct _objc_protocol *class_protocols[];
3253 }
3254 */
3255 Result += "\nstatic struct {\n";
3256 Result += "\tstruct _objc_protocol_list *next;\n";
3257 Result += "\tint protocol_count;\n";
3258 Result += "\tstruct _objc_protocol *class_protocols[";
3259 Result += utostr(Protocols.size());
3260 Result += "];\n} _OBJC_";
3261 Result += prefix;
3262 Result += "_PROTOCOLS_";
3263 Result += ClassName;
3264 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3265 "{\n\t0, ";
3266 Result += utostr(Protocols.size());
3267 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003268
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003269 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003270 Result += Protocols[0]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003271 Result += " \n";
Mike Stump1eb44332009-09-09 15:08:12 +00003272
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003273 for (unsigned i = 1; i != Protocols.size(); i++) {
3274 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003275 Result += Protocols[i]->getNameAsString();
Chris Lattner9d0aaa12008-07-21 21:33:21 +00003276 Result += "\n";
3277 }
3278 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003279}
3280
Steve Naroff621edce2009-04-29 16:37:50 +00003281
Mike Stump1eb44332009-09-09 15:08:12 +00003282/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003283/// implementation.
Steve Naroffb29b4272008-04-14 22:03:09 +00003284void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003285 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003286 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003287 // Find category declaration for this implementation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003288 ObjCCategoryDecl *CDecl;
Mike Stump1eb44332009-09-09 15:08:12 +00003289 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003290 CDecl = CDecl->getNextClassCategory())
3291 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3292 break;
Mike Stump1eb44332009-09-09 15:08:12 +00003293
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003294 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnereb44eee2007-12-23 01:40:15 +00003295 FullCategoryName += '_';
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003296 FullCategoryName += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003297
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003298 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003299 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003300 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003301
3302 // If any of our property implementations have associated getters or
3303 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003304 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3305 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003306 Prop != PropEnd; ++Prop) {
3307 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3308 continue;
3309 if (!(*Prop)->getPropertyIvarDecl())
3310 continue;
3311 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3312 if (!PD)
3313 continue;
3314 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3315 InstanceMethods.push_back(Getter);
3316 if (PD->isReadOnly())
3317 continue;
3318 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3319 InstanceMethods.push_back(Setter);
3320 }
3321 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003322 true, "CATEGORY_", FullCategoryName.c_str(),
3323 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003324
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003325 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003326 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnereb44eee2007-12-23 01:40:15 +00003327 false, "CATEGORY_", FullCategoryName.c_str(),
3328 Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003329
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003330 // Protocols referenced in class declaration?
Fariborz Jahanianbac97d42007-11-13 22:09:49 +00003331 // Null CDecl is case of a category implementation with no category interface
3332 if (CDecl)
Steve Naroff621edce2009-04-29 16:37:50 +00003333 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3334 FullCategoryName.c_str(), Result);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003335 /* struct _objc_category {
3336 char *category_name;
3337 char *class_name;
3338 struct _objc_method_list *instance_methods;
3339 struct _objc_method_list *class_methods;
3340 struct _objc_protocol_list *protocols;
3341 // Objective-C 1.0 extensions
3342 uint32_t size; // sizeof (struct _objc_category)
Mike Stump1eb44332009-09-09 15:08:12 +00003343 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003344 // @property decl.
Mike Stump1eb44332009-09-09 15:08:12 +00003345 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003346 */
Mike Stump1eb44332009-09-09 15:08:12 +00003347
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003348 static bool objc_category = false;
3349 if (!objc_category) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003350 Result += "\nstruct _objc_category {\n";
3351 Result += "\tchar *category_name;\n";
3352 Result += "\tchar *class_name;\n";
3353 Result += "\tstruct _objc_method_list *instance_methods;\n";
3354 Result += "\tstruct _objc_method_list *class_methods;\n";
3355 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003356 Result += "\tunsigned int size;\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003357 Result += "\tstruct _objc_property_list *instance_properties;\n";
3358 Result += "};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003359 objc_category = true;
Fariborz Jahaniane887c092007-10-22 21:41:37 +00003360 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003361 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3362 Result += FullCategoryName;
Steve Naroffdbb65432008-03-12 17:18:30 +00003363 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003364 Result += IDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003365 Result += "\"\n\t, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003366 Result += ClassDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003367 Result += "\"\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003368
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003369 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003370 Result += "\t, (struct _objc_method_list *)"
3371 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3372 Result += FullCategoryName;
3373 Result += "\n";
3374 }
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003375 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003376 Result += "\t, 0\n";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003377 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003378 Result += "\t, (struct _objc_method_list *)"
3379 "&_OBJC_CATEGORY_CLASS_METHODS_";
3380 Result += FullCategoryName;
3381 Result += "\n";
3382 }
3383 else
3384 Result += "\t, 0\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003385
Chris Lattnercafeb352009-02-20 18:18:36 +00003386 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003387 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003388 Result += FullCategoryName;
3389 Result += "\n";
3390 }
3391 else
3392 Result += "\t, 0\n";
3393 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003394}
3395
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003396/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3397/// ivar offset.
Mike Stump1eb44332009-09-09 15:08:12 +00003398void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3399 ObjCIvarDecl *ivar,
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003400 std::string &Result) {
Steve Naroff8f3b2652008-07-16 18:22:22 +00003401 if (ivar->isBitField()) {
3402 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3403 // place all bitfields at offset 0.
3404 Result += "0";
3405 } else {
3406 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003407 Result += IDecl->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003408 if (LangOpts.Microsoft)
3409 Result += "_IMPL";
3410 Result += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003411 Result += ivar->getNameAsString();
Steve Naroff8f3b2652008-07-16 18:22:22 +00003412 Result += ")";
3413 }
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003414}
3415
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003416//===----------------------------------------------------------------------===//
3417// Meta Data Emission
3418//===----------------------------------------------------------------------===//
3419
Steve Naroffb29b4272008-04-14 22:03:09 +00003420void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003421 std::string &Result) {
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003422 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump1eb44332009-09-09 15:08:12 +00003423
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003424 // Explictly declared @interface's are already synthesized.
Steve Naroff33feeb02009-04-20 20:09:33 +00003425 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003426 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003427 // produce correct synthesis as yet.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003428 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanianebe668f2007-11-26 20:59:57 +00003429 }
Mike Stump1eb44332009-09-09 15:08:12 +00003430
Chris Lattnerbe6df082007-12-12 07:56:42 +00003431 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003432 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump1eb44332009-09-09 15:08:12 +00003433 ? IDecl->ivar_size()
Chris Lattnerf3a7af92008-03-16 21:08:55 +00003434 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003435 if (NumIvars > 0) {
3436 static bool objc_ivar = false;
3437 if (!objc_ivar) {
3438 /* struct _objc_ivar {
3439 char *ivar_name;
3440 char *ivar_type;
3441 int ivar_offset;
Mike Stump1eb44332009-09-09 15:08:12 +00003442 };
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003443 */
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003444 Result += "\nstruct _objc_ivar {\n";
3445 Result += "\tchar *ivar_name;\n";
3446 Result += "\tchar *ivar_type;\n";
3447 Result += "\tint ivar_offset;\n";
3448 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003449
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003450 objc_ivar = true;
3451 }
3452
Steve Naroff946a6932008-03-11 00:12:29 +00003453 /* struct {
3454 int ivar_count;
3455 struct _objc_ivar ivar_list[nIvars];
Mike Stump1eb44332009-09-09 15:08:12 +00003456 };
Steve Naroff946a6932008-03-11 00:12:29 +00003457 */
Mike Stump1eb44332009-09-09 15:08:12 +00003458 Result += "\nstatic struct {\n";
Steve Naroff946a6932008-03-11 00:12:29 +00003459 Result += "\tint ivar_count;\n";
3460 Result += "\tstruct _objc_ivar ivar_list[";
3461 Result += utostr(NumIvars);
3462 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003463 Result += IDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003464 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003465 "{\n\t";
3466 Result += utostr(NumIvars);
3467 Result += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003468
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003469 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003470 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003471 if (!IDecl->ivar_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00003472 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003473 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor8f36aba2009-04-23 03:23:08 +00003474 IV != IVEnd; ++IV)
3475 IVars.push_back(*IV);
3476 IVI = IVars.begin();
3477 IVE = IVars.end();
Chris Lattnerbe6df082007-12-12 07:56:42 +00003478 } else {
3479 IVI = CDecl->ivar_begin();
3480 IVE = CDecl->ivar_end();
3481 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003482 Result += "\t,{{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003483 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003484 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003485 std::string TmpString, StrEncoding;
3486 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3487 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003488 Result += StrEncoding;
3489 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003490 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003491 Result += "}\n";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003492 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003493 Result += "\t ,{\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003494 Result += (*IVI)->getNameAsString();
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003495 Result += "\", \"";
Steve Naroff621edce2009-04-29 16:37:50 +00003496 std::string TmpString, StrEncoding;
3497 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3498 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanian160eb652007-10-29 17:16:25 +00003499 Result += StrEncoding;
3500 Result += "\", ";
Chris Lattnerbe6df082007-12-12 07:56:42 +00003501 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003502 Result += "}\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003503 }
Mike Stump1eb44332009-09-09 15:08:12 +00003504
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003505 Result += "\t }\n};\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003506 }
Mike Stump1eb44332009-09-09 15:08:12 +00003507
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003508 // Build _objc_method_list for class's instance methods if needed
Mike Stump1eb44332009-09-09 15:08:12 +00003509 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003510 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor653f1b12009-04-23 01:02:12 +00003511
3512 // If any of our property implementations have associated getters or
3513 // setters, produce metadata for them as well.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003514 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3515 PropEnd = IDecl->propimpl_end();
Douglas Gregor653f1b12009-04-23 01:02:12 +00003516 Prop != PropEnd; ++Prop) {
3517 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3518 continue;
3519 if (!(*Prop)->getPropertyIvarDecl())
3520 continue;
3521 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3522 if (!PD)
3523 continue;
3524 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3525 InstanceMethods.push_back(Getter);
3526 if (PD->isReadOnly())
3527 continue;
3528 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3529 InstanceMethods.push_back(Setter);
3530 }
3531 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003532 true, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003533
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003534 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003535 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00003536 false, "", IDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003537
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003538 // Protocols referenced in class declaration?
Steve Naroff621edce2009-04-29 16:37:50 +00003539 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3540 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003541
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003542 // Declaration of class/meta-class metadata
3543 /* struct _objc_class {
3544 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003545 const char *super_class_name;
3546 char *name;
3547 long version;
3548 long info;
3549 long instance_size;
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003550 struct _objc_ivar_list *ivars;
3551 struct _objc_method_list *methods;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003552 struct objc_cache *cache;
3553 struct objc_protocol_list *protocols;
3554 const char *ivar_layout;
3555 struct _objc_class_ext *ext;
Mike Stump1eb44332009-09-09 15:08:12 +00003556 };
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003557 */
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003558 static bool objc_class = false;
3559 if (!objc_class) {
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003560 Result += "\nstruct _objc_class {\n";
3561 Result += "\tstruct _objc_class *isa;\n";
3562 Result += "\tconst char *super_class_name;\n";
3563 Result += "\tchar *name;\n";
3564 Result += "\tlong version;\n";
3565 Result += "\tlong info;\n";
3566 Result += "\tlong instance_size;\n";
3567 Result += "\tstruct _objc_ivar_list *ivars;\n";
3568 Result += "\tstruct _objc_method_list *methods;\n";
3569 Result += "\tstruct objc_cache *cache;\n";
3570 Result += "\tstruct _objc_protocol_list *protocols;\n";
3571 Result += "\tconst char *ivar_layout;\n";
3572 Result += "\tstruct _objc_class_ext *ext;\n";
3573 Result += "};\n";
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003574 objc_class = true;
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003575 }
Mike Stump1eb44332009-09-09 15:08:12 +00003576
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003577 // Meta-class metadata generation.
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003578 ObjCInterfaceDecl *RootClass = 0;
3579 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003580 while (SuperClass) {
3581 RootClass = SuperClass;
3582 SuperClass = SuperClass->getSuperClass();
3583 }
3584 SuperClass = CDecl->getSuperClass();
Mike Stump1eb44332009-09-09 15:08:12 +00003585
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003586 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003587 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003588 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003589 "{\n\t(struct _objc_class *)\"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003590 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003591 Result += "\"";
3592
3593 if (SuperClass) {
3594 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003595 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003596 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003597 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003598 Result += "\"";
3599 }
3600 else {
3601 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003602 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003603 Result += "\"";
3604 }
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003605 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003606 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003607 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003608 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff23f41272008-03-11 18:14:26 +00003609 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003610 Result += IDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003611 Result += "\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003612 }
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003613 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003614 Result += ", 0\n";
Chris Lattnercafeb352009-02-20 18:18:36 +00003615 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003616 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003617 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003618 Result += ",0,0\n";
3619 }
Fariborz Jahanian454cb012007-10-24 20:54:23 +00003620 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003621 Result += "\t,0,0,0,0\n";
3622 Result += "};\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003623
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003624 // class metadata generation.
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003625 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003626 Result += CDecl->getNameAsString();
Steve Naroffdbb65432008-03-12 17:18:30 +00003627 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003628 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003629 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003630 if (SuperClass) {
3631 Result += ", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003632 Result += SuperClass->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003633 Result += "\", \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003634 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003635 Result += "\"";
3636 }
3637 else {
3638 Result += ", 0, \"";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003639 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003640 Result += "\"";
3641 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003642 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003643 Result += ", 0,1";
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003644 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003645 Result += ",0";
3646 else {
3647 // class has size. Must synthesize its size.
Fariborz Jahanian909f02a2007-11-05 17:47:33 +00003648 Result += ",sizeof(struct ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003649 Result += CDecl->getNameAsString();
Steve Naroffba9ac4e2008-03-10 23:33:22 +00003650 if (LangOpts.Microsoft)
3651 Result += "_IMPL";
Fariborz Jahanian4d733d32007-10-26 23:09:28 +00003652 Result += ")";
3653 }
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003654 if (NumIvars > 0) {
Steve Naroffc0a123c2008-03-11 17:37:02 +00003655 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003656 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003657 Result += "\n\t";
3658 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003659 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003660 Result += ",0";
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00003661 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroff946a6932008-03-11 00:12:29 +00003662 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003663 Result += CDecl->getNameAsString();
Mike Stump1eb44332009-09-09 15:08:12 +00003664 Result += ", 0\n\t";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003665 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003666 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003667 Result += ",0,0";
Chris Lattnercafeb352009-02-20 18:18:36 +00003668 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff8eb4a5e2008-03-12 01:06:30 +00003669 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003670 Result += CDecl->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003671 Result += ", 0,0\n";
3672 }
Fariborz Jahaniandeef5182007-10-23 18:53:48 +00003673 else
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003674 Result += ",0,0,0\n";
3675 Result += "};\n";
Fariborz Jahanian9f0a1cb2007-10-23 00:02:02 +00003676}
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003677
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003678/// RewriteImplementations - This routine rewrites all method implementations
3679/// and emits meta-data.
3680
Steve Narofface66252008-11-13 20:07:04 +00003681void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003682 int ClsDefCount = ClassImplementation.size();
3683 int CatDefCount = CategoryImplementation.size();
Mike Stump1eb44332009-09-09 15:08:12 +00003684
Fariborz Jahanian7a3279d2007-11-13 19:21:13 +00003685 // Rewrite implemented methods
3686 for (int i = 0; i < ClsDefCount; i++)
3687 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump1eb44332009-09-09 15:08:12 +00003688
Fariborz Jahanian66d6b292007-11-13 20:04:28 +00003689 for (int i = 0; i < CatDefCount; i++)
3690 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofface66252008-11-13 20:07:04 +00003691}
Mike Stump1eb44332009-09-09 15:08:12 +00003692
Steve Narofface66252008-11-13 20:07:04 +00003693void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3694 int ClsDefCount = ClassImplementation.size();
3695 int CatDefCount = CategoryImplementation.size();
3696
Steve Naroff5df5b762008-05-07 21:23:49 +00003697 // This is needed for determining instance variable offsets.
Fariborz Jahanianc98cbb42010-01-07 18:31:42 +00003698 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003699 // For each implemented class, write out all its meta data.
Fariborz Jahanianf4d331d2007-10-18 22:09:03 +00003700 for (int i = 0; i < ClsDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003701 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump1eb44332009-09-09 15:08:12 +00003702
Fariborz Jahanian2e6d9352007-10-24 19:23:36 +00003703 // For each implemented category, write out all its meta data.
3704 for (int i = 0; i < CatDefCount; i++)
Ted Kremeneka526c5c2008-01-07 19:49:32 +00003705 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroff621edce2009-04-29 16:37:50 +00003706
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003707 // Write objc_symtab metadata
3708 /*
3709 struct _objc_symtab
3710 {
3711 long sel_ref_cnt;
3712 SEL *refs;
3713 short cls_def_cnt;
3714 short cat_def_cnt;
3715 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump1eb44332009-09-09 15:08:12 +00003716 };
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003717 */
Mike Stump1eb44332009-09-09 15:08:12 +00003718
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003719 Result += "\nstruct _objc_symtab {\n";
3720 Result += "\tlong sel_ref_cnt;\n";
3721 Result += "\tSEL *refs;\n";
3722 Result += "\tshort cls_def_cnt;\n";
3723 Result += "\tshort cat_def_cnt;\n";
3724 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3725 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003726
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003727 Result += "static struct _objc_symtab "
Steve Naroffdbb65432008-03-12 17:18:30 +00003728 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003729 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003730 + ", " + utostr(CatDefCount) + "\n";
3731 for (int i = 0; i < ClsDefCount; i++) {
3732 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003733 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003734 Result += "\n";
3735 }
Mike Stump1eb44332009-09-09 15:08:12 +00003736
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003737 for (int i = 0; i < CatDefCount; i++) {
3738 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003739 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003740 Result += "_";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003741 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003742 Result += "\n";
3743 }
Mike Stump1eb44332009-09-09 15:08:12 +00003744
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003745 Result += "};\n\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003746
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003747 // Write objc_module metadata
Mike Stump1eb44332009-09-09 15:08:12 +00003748
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003749 /*
3750 struct _objc_module {
3751 long version;
3752 long size;
3753 const char *name;
3754 struct _objc_symtab *symtab;
3755 }
3756 */
Mike Stump1eb44332009-09-09 15:08:12 +00003757
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003758 Result += "\nstruct _objc_module {\n";
3759 Result += "\tlong version;\n";
3760 Result += "\tlong size;\n";
3761 Result += "\tconst char *name;\n";
3762 Result += "\tstruct _objc_symtab *symtab;\n";
3763 Result += "};\n\n";
3764 Result += "static struct _objc_module "
Steve Naroffdbb65432008-03-12 17:18:30 +00003765 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003766 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian26e4cd32007-10-26 19:46:17 +00003767 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanianccd87b02007-10-25 20:55:25 +00003768 Result += "};\n\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003769
3770 if (LangOpts.Microsoft) {
Steve Naroff621edce2009-04-29 16:37:50 +00003771 if (ProtocolExprDecls.size()) {
3772 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3773 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003774 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00003775 E = ProtocolExprDecls.end(); I != E; ++I) {
3776 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3777 Result += (*I)->getNameAsString();
3778 Result += " = &_OBJC_PROTOCOL_";
3779 Result += (*I)->getNameAsString();
3780 Result += ";\n";
3781 }
3782 Result += "#pragma data_seg(pop)\n\n";
3783 }
Steve Naroff4f943c22008-03-10 20:43:59 +00003784 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroff19190322008-05-07 00:06:16 +00003785 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff4f943c22008-03-10 20:43:59 +00003786 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3787 Result += "&_OBJC_MODULES;\n";
3788 Result += "#pragma data_seg(pop)\n\n";
3789 }
Fariborz Jahanian545b9ae2007-10-18 19:23:00 +00003790}
Chris Lattner311ff022007-10-16 22:36:42 +00003791
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003792void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3793 const std::string &Name,
3794 ValueDecl *VD) {
3795 assert(BlockByRefDeclNo.count(VD) &&
3796 "RewriteByRefString: ByRef decl missing");
3797 ResultStr += "struct __Block_byref_" + Name +
3798 "_" + utostr(BlockByRefDeclNo[VD]) ;
3799}
3800
Steve Naroff54055232008-10-27 17:20:55 +00003801std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3802 const char *funcName,
3803 std::string Tag) {
3804 const FunctionType *AFT = CE->getFunctionType();
3805 QualType RT = AFT->getResultType();
3806 std::string StructRef = "struct " + Tag;
3807 std::string S = "static " + RT.getAsString() + " __" +
3808 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisef177822008-04-17 14:40:12 +00003809
Steve Naroff54055232008-10-27 17:20:55 +00003810 BlockDecl *BD = CE->getBlockDecl();
Mike Stump1eb44332009-09-09 15:08:12 +00003811
Douglas Gregor72564e72009-02-26 23:50:07 +00003812 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump1eb44332009-09-09 15:08:12 +00003813 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Naroffdf8570d2009-02-02 17:19:26 +00003814 // block (to reference imported block decl refs).
3815 S += "(" + StructRef + " *__cself)";
Steve Naroff54055232008-10-27 17:20:55 +00003816 } else if (BD->param_empty()) {
3817 S += "(" + StructRef + " *__cself)";
3818 } else {
Douglas Gregor72564e72009-02-26 23:50:07 +00003819 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff54055232008-10-27 17:20:55 +00003820 assert(FT && "SynthesizeBlockFunc: No function proto");
3821 S += '(';
3822 // first add the implicit argument.
3823 S += StructRef + " *__cself, ";
3824 std::string ParamStr;
3825 for (BlockDecl::param_iterator AI = BD->param_begin(),
3826 E = BD->param_end(); AI != E; ++AI) {
3827 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003828 ParamStr = (*AI)->getNameAsString();
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003829 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003830 S += ParamStr;
3831 }
3832 if (FT->isVariadic()) {
3833 if (!BD->param_empty()) S += ", ";
3834 S += "...";
3835 }
3836 S += ')';
3837 }
3838 S += " {\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003839
Steve Naroff54055232008-10-27 17:20:55 +00003840 // Create local declarations to avoid rewriting all closure decl ref exprs.
3841 // First, emit a declaration for all "by ref" decls.
Mike Stump1eb44332009-09-09 15:08:12 +00003842 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003843 E = BlockByRefDecls.end(); I != E; ++I) {
3844 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003845 std::string Name = (*I)->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003846 std::string TypeString;
3847 RewriteByRefString(TypeString, Name, (*I));
3848 TypeString += " *";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003849 Name = TypeString + Name;
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003850 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003851 }
Steve Naroff54055232008-10-27 17:20:55 +00003852 // Next, emit a declaration for all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003853 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003854 E = BlockByCopyDecls.end(); I != E; ++I) {
3855 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003856 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003857 // Handle nested closure invocation. For example:
3858 //
3859 // void (^myImportedClosure)(void);
3860 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003861 //
Steve Naroff54055232008-10-27 17:20:55 +00003862 // void (^anotherClosure)(void);
3863 // anotherClosure = ^(void) {
3864 // myImportedClosure(); // import and invoke the closure
3865 // };
3866 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003867 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00003868 S += "struct __block_impl *";
3869 else
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003870 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003871 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff54055232008-10-27 17:20:55 +00003872 }
3873 std::string RewrittenStr = RewrittenBlockExprs[CE];
3874 const char *cstr = RewrittenStr.c_str();
3875 while (*cstr++ != '{') ;
3876 S += cstr;
3877 S += "\n";
3878 return S;
3879}
Argyrios Kyrtzidis39ba4ae2008-06-09 23:19:58 +00003880
Steve Naroff54055232008-10-27 17:20:55 +00003881std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3882 const char *funcName,
3883 std::string Tag) {
3884 std::string StructRef = "struct " + Tag;
3885 std::string S = "static void __";
Mike Stump1eb44332009-09-09 15:08:12 +00003886
Steve Naroff54055232008-10-27 17:20:55 +00003887 S += funcName;
3888 S += "_block_copy_" + utostr(i);
3889 S += "(" + StructRef;
3890 S += "*dst, " + StructRef;
3891 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003892 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003893 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003894 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003895 S += (*I)->getNameAsString();
Steve Naroff47a24222008-12-11 20:51:38 +00003896 S += ", (void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003897 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003898 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003899 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003900 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003901 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003902 }
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003903 S += "}\n";
3904
Steve Naroff54055232008-10-27 17:20:55 +00003905 S += "\nstatic void __";
3906 S += funcName;
3907 S += "_block_dispose_" + utostr(i);
3908 S += "(" + StructRef;
3909 S += "*src) {";
Mike Stump1eb44332009-09-09 15:08:12 +00003910 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003911 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff5bc60d02008-12-16 15:50:30 +00003912 S += "_Block_object_dispose((void*)src->";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003913 S += (*I)->getNameAsString();
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003914 if (BlockByRefDecls.count((*I)))
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003915 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
Fariborz Jahaniand25d1b52009-12-23 20:32:38 +00003916 else
Fariborz Jahanian73e437b2009-12-23 21:18:41 +00003917 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff54055232008-10-27 17:20:55 +00003918 }
Mike Stump1eb44332009-09-09 15:08:12 +00003919 S += "}\n";
Steve Naroff54055232008-10-27 17:20:55 +00003920 return S;
3921}
3922
Steve Naroff01aec112009-12-06 21:14:13 +00003923std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3924 std::string Desc) {
Steve Naroffced80a82008-10-30 12:09:33 +00003925 std::string S = "\nstruct " + Tag;
Steve Naroff54055232008-10-27 17:20:55 +00003926 std::string Constructor = " " + Tag;
Mike Stump1eb44332009-09-09 15:08:12 +00003927
Steve Naroff54055232008-10-27 17:20:55 +00003928 S += " {\n struct __block_impl impl;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003929 S += " struct " + Desc;
3930 S += "* Desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003931
Steve Naroff01aec112009-12-06 21:14:13 +00003932 Constructor += "(void *fp, "; // Invoke function pointer.
3933 Constructor += "struct " + Desc; // Descriptor pointer.
3934 Constructor += " *desc";
Mike Stump1eb44332009-09-09 15:08:12 +00003935
Steve Naroff54055232008-10-27 17:20:55 +00003936 if (BlockDeclRefs.size()) {
3937 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003938 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003939 E = BlockByCopyDecls.end(); I != E; ++I) {
3940 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003941 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003942 std::string ArgName = "_" + FieldName;
3943 // Handle nested closure invocation. For example:
3944 //
3945 // void (^myImportedBlock)(void);
3946 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003947 //
Steve Naroff54055232008-10-27 17:20:55 +00003948 // void (^anotherBlock)(void);
3949 // anotherBlock = ^(void) {
3950 // myImportedBlock(); // import and invoke the closure
3951 // };
3952 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003953 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003954 S += "struct __block_impl *";
3955 Constructor += ", void *" + ArgName;
3956 } else {
Douglas Gregord249e1d1f2009-05-29 20:38:28 +00003957 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3958 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff54055232008-10-27 17:20:55 +00003959 Constructor += ", " + ArgName;
3960 }
3961 S += FieldName + ";\n";
3962 }
3963 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00003964 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00003965 E = BlockByRefDecls.end(); I != E; ++I) {
3966 S += " ";
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00003967 std::string FieldName = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00003968 std::string ArgName = "_" + FieldName;
3969 // Handle nested closure invocation. For example:
3970 //
3971 // void (^myImportedBlock)(void);
3972 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump1eb44332009-09-09 15:08:12 +00003973 //
Steve Naroff54055232008-10-27 17:20:55 +00003974 // void (^anotherBlock)(void);
3975 // anotherBlock = ^(void) {
3976 // myImportedBlock(); // import and invoke the closure
3977 // };
3978 //
Steve Naroff01f2ffa2008-12-11 21:05:33 +00003979 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff54055232008-10-27 17:20:55 +00003980 S += "struct __block_impl *";
3981 Constructor += ", void *" + ArgName;
3982 } else {
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00003983 std::string TypeString;
3984 RewriteByRefString(TypeString, FieldName, (*I));
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00003985 TypeString += " *";
3986 FieldName = TypeString + FieldName;
3987 ArgName = TypeString + ArgName;
Steve Naroff54055232008-10-27 17:20:55 +00003988 Constructor += ", " + ArgName;
3989 }
3990 S += FieldName + "; // by ref\n";
3991 }
3992 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00003993 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00003994 if (GlobalVarDecl)
3995 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3996 else
3997 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00003998 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00003999
Steve Naroff01aec112009-12-06 21:14:13 +00004000 Constructor += " Desc = desc;\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004001
Steve Naroff54055232008-10-27 17:20:55 +00004002 // Initialize all "by copy" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004003 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004004 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004005 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004006 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004007 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004008 Constructor += Name + " = (struct __block_impl *)_";
4009 else
4010 Constructor += Name + " = _";
4011 Constructor += Name + ";\n";
4012 }
4013 // Initialize all "by ref" arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004014 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004015 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004016 std::string Name = (*I)->getNameAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004017 Constructor += " ";
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004018 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff54055232008-10-27 17:20:55 +00004019 Constructor += Name + " = (struct __block_impl *)_";
4020 else
4021 Constructor += Name + " = _";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004022 Constructor += Name + "->__forwarding;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004023 }
4024 } else {
4025 // Finish writing the constructor.
Steve Naroff54055232008-10-27 17:20:55 +00004026 Constructor += ", int flags=0) {\n";
Steve Naroff621edce2009-04-29 16:37:50 +00004027 if (GlobalVarDecl)
4028 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4029 else
4030 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004031 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4032 Constructor += " Desc = desc;\n";
Steve Naroff54055232008-10-27 17:20:55 +00004033 }
4034 Constructor += " ";
4035 Constructor += "}\n";
4036 S += Constructor;
4037 S += "};\n";
4038 return S;
4039}
4040
Steve Naroff01aec112009-12-06 21:14:13 +00004041std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
4042 std::string ImplTag, int i,
4043 const char *FunName,
4044 unsigned hasCopy) {
4045 std::string S = "\nstatic struct " + DescTag;
4046
4047 S += " {\n unsigned long reserved;\n";
4048 S += " unsigned long Block_size;\n";
4049 if (hasCopy) {
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004050 S += " void (*copy)(struct ";
4051 S += ImplTag; S += "*, struct ";
4052 S += ImplTag; S += "*);\n";
4053
4054 S += " void (*dispose)(struct ";
4055 S += ImplTag; S += "*);\n";
Steve Naroff01aec112009-12-06 21:14:13 +00004056 }
4057 S += "} ";
4058
4059 S += DescTag + "_DATA = { 0, sizeof(struct ";
4060 S += ImplTag + ")";
4061 if (hasCopy) {
4062 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
4063 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
4064 }
4065 S += "};\n";
4066 return S;
4067}
4068
Steve Naroff54055232008-10-27 17:20:55 +00004069void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004070 const char *FunName) {
4071 // Insert declaration for the function in which block literal is used.
Fariborz Jahanianbf070122010-01-15 18:14:52 +00004072 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004073 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004074 // Insert closures that were part of the function.
4075 for (unsigned i = 0; i < Blocks.size(); i++) {
4076
4077 CollectBlockDeclRefInfo(Blocks[i]);
4078
Steve Naroff01aec112009-12-06 21:14:13 +00004079 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
4080 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump1eb44332009-09-09 15:08:12 +00004081
Steve Naroff01aec112009-12-06 21:14:13 +00004082 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff54055232008-10-27 17:20:55 +00004083
4084 InsertText(FunLocStart, CI.c_str(), CI.size());
4085
Steve Naroff01aec112009-12-06 21:14:13 +00004086 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump1eb44332009-09-09 15:08:12 +00004087
Steve Naroff54055232008-10-27 17:20:55 +00004088 InsertText(FunLocStart, CF.c_str(), CF.size());
4089
4090 if (ImportedBlockDecls.size()) {
Steve Naroff01aec112009-12-06 21:14:13 +00004091 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff54055232008-10-27 17:20:55 +00004092 InsertText(FunLocStart, HF.c_str(), HF.size());
4093 }
Steve Naroff01aec112009-12-06 21:14:13 +00004094 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4095 ImportedBlockDecls.size() > 0);
4096 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump1eb44332009-09-09 15:08:12 +00004097
Steve Naroff54055232008-10-27 17:20:55 +00004098 BlockDeclRefs.clear();
4099 BlockByRefDecls.clear();
4100 BlockByCopyDecls.clear();
4101 BlockCallExprs.clear();
4102 ImportedBlockDecls.clear();
4103 }
4104 Blocks.clear();
4105 RewrittenBlockExprs.clear();
4106}
4107
4108void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4109 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner8ec03f52008-11-24 03:54:41 +00004110 const char *FuncName = FD->getNameAsCString();
Mike Stump1eb44332009-09-09 15:08:12 +00004111
Steve Naroff54055232008-10-27 17:20:55 +00004112 SynthesizeBlockLiterals(FunLocStart, FuncName);
4113}
4114
4115void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroffced80a82008-10-30 12:09:33 +00004116 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4117 //SourceLocation FunLocStart = MD->getLocStart();
Fariborz Jahanian0e1c99a2010-01-29 01:55:49 +00004118 SourceLocation FunLocStart = MD->getLocStart();
Chris Lattner077bf5e2008-11-24 03:33:13 +00004119 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff54055232008-10-27 17:20:55 +00004120 // Convert colons to underscores.
4121 std::string::size_type loc = 0;
4122 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4123 FuncName.replace(loc, 1, "_");
Mike Stump1eb44332009-09-09 15:08:12 +00004124
Steve Naroff54055232008-10-27 17:20:55 +00004125 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4126}
4127
4128void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4129 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4130 CI != E; ++CI)
4131 if (*CI) {
4132 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4133 GetBlockDeclRefExprs(CBE->getBody());
4134 else
4135 GetBlockDeclRefExprs(*CI);
4136 }
4137 // Handle specific things.
4138 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4139 // FIXME: Handle enums.
4140 if (!isa<FunctionDecl>(CDRE->getDecl()))
4141 BlockDeclRefs.push_back(CDRE);
4142 return;
4143}
4144
4145void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4146 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4147 CI != E; ++CI)
4148 if (*CI) {
4149 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4150 GetBlockCallExprs(CBE->getBody());
4151 else
4152 GetBlockCallExprs(*CI);
4153 }
Mike Stump1eb44332009-09-09 15:08:12 +00004154
Steve Naroff54055232008-10-27 17:20:55 +00004155 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4156 if (CE->getCallee()->getType()->isBlockPointerType()) {
4157 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4158 }
4159 }
4160 return;
4161}
4162
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004163Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff54055232008-10-27 17:20:55 +00004164 // Navigate to relevant type information.
Steve Naroff54055232008-10-27 17:20:55 +00004165 const BlockPointerType *CPT = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004166
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004167 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004168 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004169 } else if (const BlockDeclRefExpr *CDRE =
4170 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004171 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004172 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004173 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004174 }
4175 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4176 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4177 }
4178 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4179 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4180 else if (const ConditionalOperator *CEXPR =
4181 dyn_cast<ConditionalOperator>(BlockExp)) {
4182 Expr *LHSExp = CEXPR->getLHS();
4183 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4184 Expr *RHSExp = CEXPR->getRHS();
4185 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4186 Expr *CONDExp = CEXPR->getCond();
4187 ConditionalOperator *CondExpr =
4188 new (Context) ConditionalOperator(CONDExp,
4189 SourceLocation(), cast<Expr>(LHSStmt),
4190 SourceLocation(), cast<Expr>(RHSStmt),
4191 Exp->getType());
4192 return CondExpr;
Fariborz Jahaniane24b22b2009-12-18 01:15:21 +00004193 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4194 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004195 } else {
4196 assert(1 && "RewriteBlockClass: Bad type");
4197 }
4198 assert(CPT && "RewriteBlockClass: Bad type");
John McCall183700f2009-09-21 23:43:11 +00004199 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff54055232008-10-27 17:20:55 +00004200 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregor72564e72009-02-26 23:50:07 +00004201 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff54055232008-10-27 17:20:55 +00004202 // FTP will be null for closures that don't take arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004203
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004204 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4205 SourceLocation(),
4206 &Context->Idents.get("__block_impl"));
4207 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff54055232008-10-27 17:20:55 +00004208
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004209 // Generate a funky cast.
4210 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump1eb44332009-09-09 15:08:12 +00004211
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004212 // Push the block argument type.
4213 ArgTypes.push_back(PtrBlock);
Steve Naroff54055232008-10-27 17:20:55 +00004214 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004215 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004216 E = FTP->arg_type_end(); I && (I != E); ++I) {
4217 QualType t = *I;
4218 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004219 if (isTopLevelBlockPointerType(t)) {
Ted Kremenek6217b802009-07-29 21:53:49 +00004220 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004221 t = Context->getPointerType(BPT->getPointeeType());
4222 }
4223 ArgTypes.push_back(t);
4224 }
Steve Naroff54055232008-10-27 17:20:55 +00004225 }
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004226 // Now do the pointer to function cast.
Mike Stump1eb44332009-09-09 15:08:12 +00004227 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004228 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00004229
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004230 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump1eb44332009-09-09 15:08:12 +00004231
John McCall9d125032010-01-15 18:39:57 +00004232 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4233 CastExpr::CK_Unknown,
4234 const_cast<Expr*>(BlockExp));
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004235 // Don't forget the parens to enforce the proper binding.
Ted Kremenek8189cde2009-02-07 01:47:29 +00004236 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4237 BlkCast);
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004238 //PE->dump();
Mike Stump1eb44332009-09-09 15:08:12 +00004239
Douglas Gregor44b43212008-12-11 16:49:14 +00004240 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump1eb44332009-09-09 15:08:12 +00004241 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor4afa39d2009-01-20 01:17:11 +00004242 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004243 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4244 FD->getType());
Mike Stump1eb44332009-09-09 15:08:12 +00004245
John McCall9d125032010-01-15 18:39:57 +00004246 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4247 CastExpr::CK_Unknown, ME);
Ted Kremenek8189cde2009-02-07 01:47:29 +00004248 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump1eb44332009-09-09 15:08:12 +00004249
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004250 llvm::SmallVector<Expr*, 8> BlkExprs;
4251 // Add the implicit argument.
4252 BlkExprs.push_back(BlkCast);
4253 // Add the user arguments.
Mike Stump1eb44332009-09-09 15:08:12 +00004254 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004255 E = Exp->arg_end(); I != E; ++I) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004256 BlkExprs.push_back(*I);
Steve Naroff54055232008-10-27 17:20:55 +00004257 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004258 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4259 BlkExprs.size(),
Ted Kremenek8189cde2009-02-07 01:47:29 +00004260 Exp->getType(), SourceLocation());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004261 return CE;
Steve Naroff54055232008-10-27 17:20:55 +00004262}
4263
4264void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00004265 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00004266 ReplaceStmt(Exp, BlockCall);
Steve Naroff54055232008-10-27 17:20:55 +00004267}
4268
Steve Naroff621edce2009-04-29 16:37:50 +00004269// We need to return the rewritten expression to handle cases where the
4270// BlockDeclRefExpr is embedded in another expression being rewritten.
4271// For example:
4272//
4273// int main() {
4274// __block Foo *f;
4275// __block int i;
Mike Stump1eb44332009-09-09 15:08:12 +00004276//
Steve Naroff621edce2009-04-29 16:37:50 +00004277// void (^myblock)() = ^() {
4278// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4279// i = 77;
4280// };
4281//}
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004282Stmt *RewriteObjC::RewriteBlockDeclRefExpr(Expr *DeclRefExp) {
Fariborz Jahanianbbf37e22009-12-23 19:26:34 +00004283 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004284 // for each DeclRefExp where BYREFVAR is name of the variable.
4285 ValueDecl *VD;
4286 bool isArrow = true;
4287 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(DeclRefExp))
4288 VD = BDRE->getDecl();
4289 else {
4290 VD = cast<DeclRefExpr>(DeclRefExp)->getDecl();
4291 isArrow = false;
4292 }
4293
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004294 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4295 &Context->Idents.get("__forwarding"),
4296 Context->VoidPtrTy, 0,
4297 /*BitWidth=*/0, /*Mutable=*/true);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004298 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4299 FD, SourceLocation(),
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004300 FD->getType());
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004301
4302 const char *Name = VD->getNameAsCString();
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004303 FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4304 &Context->Idents.get(Name),
4305 Context->VoidPtrTy, 0,
4306 /*BitWidth=*/0, /*Mutable=*/true);
4307 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004308 DeclRefExp->getType());
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004309
4310
4311
Steve Naroffdf8570d2009-02-02 17:19:26 +00004312 // Need parens to enforce precedence.
Fariborz Jahanianec878f22009-12-23 19:22:33 +00004313 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4314 ME);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004315 ReplaceStmt(DeclRefExp, PE);
Steve Naroff621edce2009-04-29 16:37:50 +00004316 return PE;
Steve Naroff54055232008-10-27 17:20:55 +00004317}
4318
Steve Naroffb2f9e512008-11-03 23:29:32 +00004319void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4320 SourceLocation LocStart = CE->getLParenLoc();
4321 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofffa15fd92008-10-28 20:29:00 +00004322
4323 // Need to avoid trying to rewrite synthesized casts.
4324 if (LocStart.isInvalid())
4325 return;
Steve Naroff8f6ce572008-11-03 11:20:24 +00004326 // Need to avoid trying to rewrite casts contained in macros.
4327 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4328 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004329
Steve Naroff54055232008-10-27 17:20:55 +00004330 const char *startBuf = SM->getCharacterData(LocStart);
4331 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahanian1d4fca22010-01-19 21:48:35 +00004332 QualType QT = CE->getType();
4333 const Type* TypePtr = QT->getAs<Type>();
4334 if (isa<TypeOfExprType>(TypePtr)) {
4335 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4336 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4337 std::string TypeAsString = "(";
4338 TypeAsString += QT.getAsString();
4339 TypeAsString += ")";
4340 ReplaceText(LocStart, endBuf-startBuf+1,
4341 TypeAsString.c_str(), TypeAsString.size());
4342 return;
4343 }
Steve Naroff54055232008-10-27 17:20:55 +00004344 // advance the location to startArgList.
4345 const char *argPtr = startBuf;
Mike Stump1eb44332009-09-09 15:08:12 +00004346
Steve Naroff54055232008-10-27 17:20:55 +00004347 while (*argPtr++ && (argPtr < endBuf)) {
4348 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004349 case '^':
4350 // Replace the '^' with '*'.
4351 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4352 ReplaceText(LocStart, 1, "*", 1);
4353 break;
Steve Naroff54055232008-10-27 17:20:55 +00004354 }
4355 }
4356 return;
4357}
4358
4359void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4360 SourceLocation DeclLoc = FD->getLocation();
4361 unsigned parenCount = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00004362
Steve Naroff54055232008-10-27 17:20:55 +00004363 // We have 1 or more arguments that have closure pointers.
4364 const char *startBuf = SM->getCharacterData(DeclLoc);
4365 const char *startArgList = strchr(startBuf, '(');
Mike Stump1eb44332009-09-09 15:08:12 +00004366
Steve Naroff54055232008-10-27 17:20:55 +00004367 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004368
Steve Naroff54055232008-10-27 17:20:55 +00004369 parenCount++;
4370 // advance the location to startArgList.
4371 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4372 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump1eb44332009-09-09 15:08:12 +00004373
Steve Naroff54055232008-10-27 17:20:55 +00004374 const char *argPtr = startArgList;
Mike Stump1eb44332009-09-09 15:08:12 +00004375
Steve Naroff54055232008-10-27 17:20:55 +00004376 while (*argPtr++ && parenCount) {
4377 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004378 case '^':
4379 // Replace the '^' with '*'.
4380 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4381 ReplaceText(DeclLoc, 1, "*", 1);
4382 break;
4383 case '(':
4384 parenCount++;
4385 break;
4386 case ')':
4387 parenCount--;
4388 break;
Steve Naroff54055232008-10-27 17:20:55 +00004389 }
4390 }
4391 return;
4392}
4393
4394bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregor72564e72009-02-26 23:50:07 +00004395 const FunctionProtoType *FTP;
Ted Kremenek6217b802009-07-29 21:53:49 +00004396 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004397 if (PT) {
John McCall183700f2009-09-21 23:43:11 +00004398 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004399 } else {
Ted Kremenek6217b802009-07-29 21:53:49 +00004400 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff54055232008-10-27 17:20:55 +00004401 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall183700f2009-09-21 23:43:11 +00004402 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff54055232008-10-27 17:20:55 +00004403 }
4404 if (FTP) {
Mike Stump1eb44332009-09-09 15:08:12 +00004405 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff54055232008-10-27 17:20:55 +00004406 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004407 if (isTopLevelBlockPointerType(*I))
Steve Naroff54055232008-10-27 17:20:55 +00004408 return true;
4409 }
4410 return false;
4411}
4412
Ted Kremenek8189cde2009-02-07 01:47:29 +00004413void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4414 const char *&RParen) {
Steve Naroff54055232008-10-27 17:20:55 +00004415 const char *argPtr = strchr(Name, '(');
4416 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump1eb44332009-09-09 15:08:12 +00004417
Steve Naroff54055232008-10-27 17:20:55 +00004418 LParen = argPtr; // output the start.
4419 argPtr++; // skip past the left paren.
4420 unsigned parenCount = 1;
Mike Stump1eb44332009-09-09 15:08:12 +00004421
Steve Naroff54055232008-10-27 17:20:55 +00004422 while (*argPtr && parenCount) {
4423 switch (*argPtr) {
Mike Stumpb7166332010-01-20 02:03:14 +00004424 case '(': parenCount++; break;
4425 case ')': parenCount--; break;
4426 default: break;
Steve Naroff54055232008-10-27 17:20:55 +00004427 }
4428 if (parenCount) argPtr++;
4429 }
4430 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4431 RParen = argPtr; // output the end
4432}
4433
4434void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4435 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4436 RewriteBlockPointerFunctionArgs(FD);
4437 return;
Mike Stump1eb44332009-09-09 15:08:12 +00004438 }
Steve Naroff54055232008-10-27 17:20:55 +00004439 // Handle Variables and Typedefs.
4440 SourceLocation DeclLoc = ND->getLocation();
4441 QualType DeclT;
4442 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4443 DeclT = VD->getType();
4444 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4445 DeclT = TDD->getUnderlyingType();
4446 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4447 DeclT = FD->getType();
Mike Stump1eb44332009-09-09 15:08:12 +00004448 else
Steve Naroff54055232008-10-27 17:20:55 +00004449 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump1eb44332009-09-09 15:08:12 +00004450
Steve Naroff54055232008-10-27 17:20:55 +00004451 const char *startBuf = SM->getCharacterData(DeclLoc);
4452 const char *endBuf = startBuf;
4453 // scan backward (from the decl location) for the end of the previous decl.
4454 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4455 startBuf--;
Mike Stump1eb44332009-09-09 15:08:12 +00004456
Steve Naroff54055232008-10-27 17:20:55 +00004457 // *startBuf != '^' if we are dealing with a pointer to function that
4458 // may take block argument types (which will be handled below).
4459 if (*startBuf == '^') {
4460 // Replace the '^' with '*', computing a negative offset.
4461 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4462 ReplaceText(DeclLoc, 1, "*", 1);
4463 }
4464 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4465 // Replace the '^' with '*' for arguments.
4466 DeclLoc = ND->getLocation();
4467 startBuf = SM->getCharacterData(DeclLoc);
4468 const char *argListBegin, *argListEnd;
4469 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4470 while (argListBegin < argListEnd) {
4471 if (*argListBegin == '^') {
4472 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4473 ReplaceText(CaretLoc, 1, "*", 1);
4474 }
4475 argListBegin++;
4476 }
4477 }
4478 return;
4479}
4480
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004481
4482/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4483/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4484/// struct Block_byref_id_object *src) {
4485/// _Block_object_assign (&_dest->object, _src->object,
4486/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4487/// [|BLOCK_FIELD_IS_WEAK]) // object
4488/// _Block_object_assign(&_dest->object, _src->object,
4489/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4490/// [|BLOCK_FIELD_IS_WEAK]) // block
4491/// }
4492/// And:
4493/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4494/// _Block_object_dispose(_src->object,
4495/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4496/// [|BLOCK_FIELD_IS_WEAK]) // object
4497/// _Block_object_dispose(_src->object,
4498/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4499/// [|BLOCK_FIELD_IS_WEAK]) // block
4500/// }
4501
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004502std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4503 int flag) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004504 std::string S;
Benjamin Kramer1211a712010-01-10 19:57:50 +00004505 if (CopyDestroyCache.count(flag))
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004506 return S;
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004507 CopyDestroyCache.insert(flag);
4508 S = "static void __Block_byref_id_object_copy_";
4509 S += utostr(flag);
4510 S += "(void *dst, void *src) {\n";
4511
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004512 // offset into the object pointer is computed as:
4513 // void * + void* + int + int + void* + void *
4514 unsigned IntSize =
4515 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4516 unsigned VoidPtrSize =
4517 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4518
4519 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/8;
4520 S += " _Block_object_assign((char*)dst + ";
4521 S += utostr(offset);
4522 S += ", *(void * *) ((char*)src + ";
4523 S += utostr(offset);
4524 S += "), ";
4525 S += utostr(flag);
4526 S += ");\n}\n";
4527
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004528 S += "static void __Block_byref_id_object_dispose_";
4529 S += utostr(flag);
4530 S += "(void *src) {\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004531 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4532 S += utostr(offset);
4533 S += "), ";
4534 S += utostr(flag);
4535 S += ");\n}\n";
4536 return S;
4537}
4538
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004539/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4540/// the declaration into:
4541/// struct __Block_byref_ND {
4542/// void *__isa; // NULL for everything except __weak pointers
4543/// struct __Block_byref_ND *__forwarding;
4544/// int32_t __flags;
4545/// int32_t __size;
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004546/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4547/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004548/// typex ND;
4549/// };
4550///
4551/// It then replaces declaration of ND variable with:
4552/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4553/// __size=sizeof(struct __Block_byref_ND),
4554/// ND=initializer-if-any};
4555///
4556///
4557void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00004558 // Insert declaration for the function in which block literal is
4559 // used.
4560 if (CurFunctionDeclToDeclareForBlock)
4561 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004562 int flag = 0;
4563 int isa = 0;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004564 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4565 const char *startBuf = SM->getCharacterData(DeclLoc);
Fariborz Jahanian6f0a0a92009-12-30 20:38:08 +00004566 SourceLocation X = ND->getLocEnd();
4567 X = SM->getInstantiationLoc(X);
4568 const char *endBuf = SM->getCharacterData(X);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004569 std::string Name(ND->getNameAsString());
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004570 std::string ByrefType;
4571 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004572 ByrefType += " {\n";
4573 ByrefType += " void *__isa;\n";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004574 RewriteByRefString(ByrefType, Name, ND);
4575 ByrefType += " *__forwarding;\n";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004576 ByrefType += " int __flags;\n";
4577 ByrefType += " int __size;\n";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004578 // Add void *__Block_byref_id_object_copy;
4579 // void *__Block_byref_id_object_dispose; if needed.
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004580 QualType Ty = ND->getType();
4581 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4582 if (HasCopyAndDispose) {
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004583 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4584 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004585 }
4586
4587 Ty.getAsStringInternal(Name, Context->PrintingPolicy);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004588 ByrefType += " " + Name + ";\n";
4589 ByrefType += "};\n";
4590 // Insert this type in global scope. It is needed by helper function.
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004591 SourceLocation FunLocStart;
4592 if (CurFunctionDef)
4593 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4594 else {
4595 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4596 FunLocStart = CurMethodDef->getLocStart();
4597 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004598 InsertText(FunLocStart, ByrefType.c_str(), ByrefType.size());
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004599 if (Ty.isObjCGCWeak()) {
4600 flag |= BLOCK_FIELD_IS_WEAK;
4601 isa = 1;
4602 }
4603
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004604 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004605 flag = BLOCK_BYREF_CALLER;
4606 QualType Ty = ND->getType();
4607 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4608 if (Ty->isBlockPointerType())
4609 flag |= BLOCK_FIELD_IS_BLOCK;
4610 else
4611 flag |= BLOCK_FIELD_IS_OBJECT;
4612 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004613 if (!HF.empty())
4614 InsertText(FunLocStart, HF.c_str(), HF.size());
4615 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004616
4617 // struct __Block_byref_ND ND =
4618 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4619 // initializer-if-any};
4620 bool hasInit = (ND->getInit() != 0);
Fariborz Jahaniane1f84f82010-01-05 18:15:57 +00004621 unsigned flags = 0;
4622 if (HasCopyAndDispose)
4623 flags |= BLOCK_HAS_COPY_DISPOSE;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004624 Name = ND->getNameAsString();
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004625 ByrefType.clear();
4626 RewriteByRefString(ByrefType, Name, ND);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004627 std::string ForwardingCastType("(");
4628 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004629 if (!hasInit) {
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004630 ByrefType += " " + Name + " = {(void*)";
4631 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004632 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004633 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004634 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004635 ByrefType += "sizeof(";
4636 RewriteByRefString(ByrefType, Name, ND);
4637 ByrefType += ")";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004638 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004639 ByrefType += ", __Block_byref_id_object_copy_";
4640 ByrefType += utostr(flag);
4641 ByrefType += ", __Block_byref_id_object_dispose_";
4642 ByrefType += utostr(flag);
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004643 }
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004644 ByrefType += "};\n";
4645 ReplaceText(DeclLoc, endBuf-startBuf+Name.size(),
4646 ByrefType.c_str(), ByrefType.size());
4647 }
4648 else {
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004649 SourceLocation startLoc;
4650 Expr *E = ND->getInit();
4651 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4652 startLoc = ECE->getLParenLoc();
4653 else
4654 startLoc = E->getLocStart();
Fariborz Jahanian791b10d2010-01-05 23:06:29 +00004655 startLoc = SM->getInstantiationLoc(startLoc);
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004656 endBuf = SM->getCharacterData(startLoc);
4657
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004658 ByrefType += " " + Name;
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004659 ByrefType += " = {(void*)";
Fariborz Jahanian2086d542010-01-05 19:21:35 +00004660 ByrefType += utostr(isa);
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004661 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004662 ByrefType += utostr(flags);
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00004663 ByrefType += ", ";
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00004664 ByrefType += "sizeof(";
4665 RewriteByRefString(ByrefType, Name, ND);
4666 ByrefType += "), ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004667 if (HasCopyAndDispose) {
Fariborz Jahanianab10b2e2010-01-05 18:04:40 +00004668 ByrefType += "__Block_byref_id_object_copy_";
4669 ByrefType += utostr(flag);
4670 ByrefType += ", __Block_byref_id_object_dispose_";
4671 ByrefType += utostr(flag);
4672 ByrefType += ", ";
Fariborz Jahaniand2eb1fd2010-01-05 01:16:51 +00004673 }
Fariborz Jahaniandfa4fa02010-01-16 19:36:43 +00004674 ReplaceText(DeclLoc, endBuf-startBuf,
4675 ByrefType.c_str(), ByrefType.size());
Steve Naroffc5143c52009-12-23 17:24:33 +00004676
4677 // Complete the newly synthesized compound expression by inserting a right
4678 // curly brace before the end of the declaration.
4679 // FIXME: This approach avoids rewriting the initializer expression. It
4680 // also assumes there is only one declarator. For example, the following
4681 // isn't currently supported by this routine (in general):
4682 //
4683 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4684 //
4685 const char *startBuf = SM->getCharacterData(startLoc);
4686 const char *semiBuf = strchr(startBuf, ';');
4687 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4688 SourceLocation semiLoc =
4689 startLoc.getFileLocWithOffset(semiBuf-startBuf);
4690
4691 InsertText(semiLoc, "}", 1);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00004692 }
Fariborz Jahanian1be6b462009-12-22 00:48:54 +00004693 return;
4694}
4695
Mike Stump1eb44332009-09-09 15:08:12 +00004696void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff54055232008-10-27 17:20:55 +00004697 // Add initializers for any closure decl refs.
4698 GetBlockDeclRefExprs(Exp->getBody());
4699 if (BlockDeclRefs.size()) {
4700 // Unique all "by copy" declarations.
4701 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4702 if (!BlockDeclRefs[i]->isByRef())
4703 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4704 // Unique all "by ref" declarations.
4705 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4706 if (BlockDeclRefs[i]->isByRef()) {
4707 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4708 }
4709 // Find any imported blocks...they will need special attention.
4710 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahanian4fcc4fd2009-12-21 23:31:42 +00004711 if (BlockDeclRefs[i]->isByRef() ||
4712 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4713 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff00072682008-11-13 17:40:07 +00004714 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff54055232008-10-27 17:20:55 +00004715 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4716 }
4717 }
4718}
4719
Steve Narofffa15fd92008-10-28 20:29:00 +00004720FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4721 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregor72564e72009-02-26 23:50:07 +00004722 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump1eb44332009-09-09 15:08:12 +00004723 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidisa1d56622009-08-19 01:27:57 +00004724 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor2224f842009-02-25 16:33:18 +00004725 false);
Steve Narofffa15fd92008-10-28 20:29:00 +00004726}
4727
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004728Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004729 Blocks.push_back(Exp);
4730
4731 CollectBlockDeclRefInfo(Exp);
4732 std::string FuncName;
Mike Stump1eb44332009-09-09 15:08:12 +00004733
Steve Narofffa15fd92008-10-28 20:29:00 +00004734 if (CurFunctionDef)
Chris Lattner077bf5e2008-11-24 03:33:13 +00004735 FuncName = CurFunctionDef->getNameAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004736 else if (CurMethodDef) {
Chris Lattner077bf5e2008-11-24 03:33:13 +00004737 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofffa15fd92008-10-28 20:29:00 +00004738 // Convert colons to underscores.
4739 std::string::size_type loc = 0;
4740 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4741 FuncName.replace(loc, 1, "_");
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004742 } else if (GlobalVarDecl)
Chris Lattnerd9d22dd2008-11-24 05:29:24 +00004743 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump1eb44332009-09-09 15:08:12 +00004744
Steve Narofffa15fd92008-10-28 20:29:00 +00004745 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump1eb44332009-09-09 15:08:12 +00004746
Steve Narofffa15fd92008-10-28 20:29:00 +00004747 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4748 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump1eb44332009-09-09 15:08:12 +00004749
Steve Narofffa15fd92008-10-28 20:29:00 +00004750 // Get a pointer to the function type so we can cast appropriately.
4751 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4752
4753 FunctionDecl *FD;
4754 Expr *NewRep;
Mike Stump1eb44332009-09-09 15:08:12 +00004755
Steve Narofffa15fd92008-10-28 20:29:00 +00004756 // Simulate a contructor call...
4757 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004758 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump1eb44332009-09-09 15:08:12 +00004759
Steve Narofffa15fd92008-10-28 20:29:00 +00004760 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump1eb44332009-09-09 15:08:12 +00004761
Steve Narofffdc03722008-10-29 21:23:59 +00004762 // Initialize the block function.
Steve Narofffa15fd92008-10-28 20:29:00 +00004763 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004764 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4765 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004766 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4767 CastExpr::CK_Unknown, Arg);
Mike Stump1eb44332009-09-09 15:08:12 +00004768 InitExprs.push_back(castExpr);
4769
Steve Naroff01aec112009-12-06 21:14:13 +00004770 // Initialize the block descriptor.
4771 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump1eb44332009-09-09 15:08:12 +00004772
Steve Naroff01aec112009-12-06 21:14:13 +00004773 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4774 &Context->Idents.get(DescData.c_str()),
4775 Context->VoidPtrTy, 0,
4776 VarDecl::Static);
4777 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4778 new (Context) DeclRefExpr(NewVD,
4779 Context->VoidPtrTy, SourceLocation()),
4780 UnaryOperator::AddrOf,
4781 Context->getPointerType(Context->VoidPtrTy),
4782 SourceLocation());
4783 InitExprs.push_back(DescRefExpr);
4784
Steve Narofffa15fd92008-10-28 20:29:00 +00004785 // Add initializers for any closure decl refs.
4786 if (BlockDeclRefs.size()) {
Steve Narofffdc03722008-10-29 21:23:59 +00004787 Expr *Exp;
Steve Narofffa15fd92008-10-28 20:29:00 +00004788 // Output all "by copy" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004789 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004790 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofffa15fd92008-10-28 20:29:00 +00004791 if (isObjCType((*I)->getType())) {
Steve Narofffdc03722008-10-29 21:23:59 +00004792 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner8ec03f52008-11-24 03:54:41 +00004793 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004794 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroff01f2ffa2008-12-11 21:05:33 +00004795 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004796 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004797 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004798 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4799 CastExpr::CK_Unknown, Arg);
Steve Narofffa15fd92008-10-28 20:29:00 +00004800 } else {
Chris Lattner8ec03f52008-11-24 03:54:41 +00004801 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004802 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00004803 }
Mike Stump1eb44332009-09-09 15:08:12 +00004804 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004805 }
4806 // Output all "by ref" declarations.
Mike Stump1eb44332009-09-09 15:08:12 +00004807 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofffa15fd92008-10-28 20:29:00 +00004808 E = BlockByRefDecls.end(); I != E; ++I) {
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004809 ValueDecl *ND = (*I);
4810 std::string Name(ND->getNameAsString());
4811 std::string RecName;
4812 RewriteByRefString(RecName, Name, ND);
4813 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4814 + sizeof("struct"));
4815 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4816 SourceLocation(), II);
4817 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4818 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4819
Chris Lattner8ec03f52008-11-24 03:54:41 +00004820 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004821 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4822 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004823 Context->getPointerType(Exp->getType()),
Steve Narofffdc03722008-10-29 21:23:59 +00004824 SourceLocation());
Fariborz Jahanian2663f522010-02-04 00:07:58 +00004825 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CastExpr::CK_Unknown, Exp);
Mike Stump1eb44332009-09-09 15:08:12 +00004826 InitExprs.push_back(Exp);
Steve Narofffa15fd92008-10-28 20:29:00 +00004827 }
4828 }
Fariborz Jahanianff127882009-12-23 21:52:32 +00004829 if (ImportedBlockDecls.size()) {
4830 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4831 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
Steve Naroff01aec112009-12-06 21:14:13 +00004832 unsigned IntSize =
4833 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Fariborz Jahanianff127882009-12-23 21:52:32 +00004834 Expr *FlagExp = new (Context) IntegerLiteral(llvm::APInt(IntSize, flag),
4835 Context->IntTy, SourceLocation());
4836 InitExprs.push_back(FlagExp);
Steve Naroff01aec112009-12-06 21:14:13 +00004837 }
Ted Kremenek668bf912009-02-09 20:51:47 +00004838 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4839 FType, SourceLocation());
Ted Kremenek8189cde2009-02-07 01:47:29 +00004840 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump1eb44332009-09-09 15:08:12 +00004841 Context->getPointerType(NewRep->getType()),
Steve Narofffa15fd92008-10-28 20:29:00 +00004842 SourceLocation());
John McCall9d125032010-01-15 18:39:57 +00004843 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CastExpr::CK_Unknown,
4844 NewRep);
Steve Narofffa15fd92008-10-28 20:29:00 +00004845 BlockDeclRefs.clear();
4846 BlockByRefDecls.clear();
4847 BlockByCopyDecls.clear();
4848 ImportedBlockDecls.clear();
4849 return NewRep;
4850}
4851
4852//===----------------------------------------------------------------------===//
4853// Function Body / Expression rewriting
4854//===----------------------------------------------------------------------===//
4855
Steve Naroffc77a6362008-12-04 16:24:46 +00004856// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4857// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4858// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4859// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4860// Since the rewriter isn't capable of rewriting rewritten code, it's important
4861// we get this right.
4862void RewriteObjC::CollectPropertySetters(Stmt *S) {
4863 // Perform a bottom up traversal of all children.
4864 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4865 CI != E; ++CI)
4866 if (*CI)
4867 CollectPropertySetters(*CI);
4868
4869 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4870 if (BinOp->isAssignmentOp()) {
4871 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4872 PropSetters[PRE] = BinOp;
4873 }
4874 }
4875}
4876
Steve Narofffa15fd92008-10-28 20:29:00 +00004877Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump1eb44332009-09-09 15:08:12 +00004878 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00004879 isa<DoStmt>(S) || isa<ForStmt>(S))
4880 Stmts.push_back(S);
4881 else if (isa<ObjCForCollectionStmt>(S)) {
4882 Stmts.push_back(S);
Chris Lattner4824fcd2010-01-09 21:45:57 +00004883 ObjCBcLabelNo.push_back(++BcLabelCount);
Steve Narofffa15fd92008-10-28 20:29:00 +00004884 }
Mike Stump1eb44332009-09-09 15:08:12 +00004885
Steve Narofffa15fd92008-10-28 20:29:00 +00004886 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump1eb44332009-09-09 15:08:12 +00004887
Steve Narofffa15fd92008-10-28 20:29:00 +00004888 // Perform a bottom up rewrite of all children.
4889 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4890 CI != E; ++CI)
4891 if (*CI) {
Fariborz Jahanian2b9b0b22010-02-05 01:35:00 +00004892 Stmt *newStmt;
4893 Stmt *S = (*CI);
4894 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4895 Expr *OldBase = IvarRefExpr->getBase();
4896 bool replaced = false;
4897 newStmt = RewriteObjCNestedIvarRefExpr(S, replaced);
4898 if (replaced) {
4899 if (ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(newStmt))
4900 ReplaceStmt(OldBase, IRE->getBase());
4901 else
4902 ReplaceStmt(S, newStmt);
4903 }
4904 }
4905 else
4906 newStmt = RewriteFunctionBodyOrGlobalInitializer(S);
Mike Stump1eb44332009-09-09 15:08:12 +00004907 if (newStmt)
Steve Narofffa15fd92008-10-28 20:29:00 +00004908 *CI = newStmt;
4909 }
Mike Stump1eb44332009-09-09 15:08:12 +00004910
Steve Narofffa15fd92008-10-28 20:29:00 +00004911 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4912 // Rewrite the block body in place.
4913 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump1eb44332009-09-09 15:08:12 +00004914
Steve Narofffa15fd92008-10-28 20:29:00 +00004915 // Now we snarf the rewritten text and stash it away for later use.
Ted Kremenek6a12a142010-01-07 18:00:35 +00004916 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004917 RewrittenBlockExprs[BE] = Str;
Mike Stump1eb44332009-09-09 15:08:12 +00004918
Steve Narofffa15fd92008-10-28 20:29:00 +00004919 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4920 //blockTranscribed->dump();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00004921 ReplaceStmt(S, blockTranscribed);
Steve Narofffa15fd92008-10-28 20:29:00 +00004922 return blockTranscribed;
4923 }
4924 // Handle specific things.
4925 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4926 return RewriteAtEncode(AtEncode);
Mike Stump1eb44332009-09-09 15:08:12 +00004927
Steve Naroffc77a6362008-12-04 16:24:46 +00004928 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4929 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4930 if (BinOp) {
4931 // Because the rewriter doesn't allow us to rewrite rewritten code,
4932 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroffb619d952008-12-09 12:56:34 +00004933 DisableReplaceStmt = true;
4934 // Save the source range. Even if we disable the replacement, the
4935 // rewritten node will have been inserted into the tree. If the synthesized
4936 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump1eb44332009-09-09 15:08:12 +00004937 // self.errorHandler = handler ? handler :
Steve Naroffb619d952008-12-09 12:56:34 +00004938 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4939 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroffc77a6362008-12-04 16:24:46 +00004940 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroffb619d952008-12-09 12:56:34 +00004941 DisableReplaceStmt = false;
Steve Naroff4c3580e2008-12-04 23:50:32 +00004942 //
4943 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4944 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4945 // to see the original expression). Consider this example:
4946 //
4947 // Foo *obj1, *obj2;
4948 //
4949 // obj1.i = [obj2 rrrr];
4950 //
4951 // 'BinOp' for the previous expression looks like:
4952 //
4953 // (BinaryOperator 0x231ccf0 'int' '='
4954 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4955 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4956 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4957 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4958 //
4959 // 'newStmt' represents the rewritten message expression. For example:
4960 //
4961 // (CallExpr 0x231d300 'id':'struct objc_object *'
4962 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4963 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4964 // (CStyleCastExpr 0x231d220 'void *'
4965 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4966 //
4967 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4968 // can be used as the setter argument. ReplaceStmt() will still 'see'
4969 // the original RHS (since we haven't altered BinOp).
4970 //
Mike Stump1eb44332009-09-09 15:08:12 +00004971 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff4c3580e2008-12-04 23:50:32 +00004972 // node. As a result, we now leak the original AST nodes.
4973 //
Steve Naroffb619d952008-12-09 12:56:34 +00004974 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroffc77a6362008-12-04 16:24:46 +00004975 } else {
4976 return RewritePropertyGetter(PropRefExpr);
Steve Naroff15f081d2008-12-03 00:56:33 +00004977 }
4978 }
Steve Narofffa15fd92008-10-28 20:29:00 +00004979 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4980 return RewriteAtSelector(AtSelector);
Mike Stump1eb44332009-09-09 15:08:12 +00004981
Steve Narofffa15fd92008-10-28 20:29:00 +00004982 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4983 return RewriteObjCStringLiteral(AtString);
Mike Stump1eb44332009-09-09 15:08:12 +00004984
Steve Narofffa15fd92008-10-28 20:29:00 +00004985 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroffc77a6362008-12-04 16:24:46 +00004986#if 0
Steve Narofffa15fd92008-10-28 20:29:00 +00004987 // Before we rewrite it, put the original message expression in a comment.
4988 SourceLocation startLoc = MessExpr->getLocStart();
4989 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump1eb44332009-09-09 15:08:12 +00004990
Steve Narofffa15fd92008-10-28 20:29:00 +00004991 const char *startBuf = SM->getCharacterData(startLoc);
4992 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump1eb44332009-09-09 15:08:12 +00004993
Steve Narofffa15fd92008-10-28 20:29:00 +00004994 std::string messString;
4995 messString += "// ";
4996 messString.append(startBuf, endBuf-startBuf+1);
4997 messString += "\n";
Mike Stump1eb44332009-09-09 15:08:12 +00004998
4999 // FIXME: Missing definition of
Steve Narofffa15fd92008-10-28 20:29:00 +00005000 // InsertText(clang::SourceLocation, char const*, unsigned int).
5001 // InsertText(startLoc, messString.c_str(), messString.size());
5002 // Tried this, but it didn't work either...
5003 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroffc77a6362008-12-04 16:24:46 +00005004#endif
Steve Narofffa15fd92008-10-28 20:29:00 +00005005 return RewriteMessageExpr(MessExpr);
5006 }
Mike Stump1eb44332009-09-09 15:08:12 +00005007
Steve Narofffa15fd92008-10-28 20:29:00 +00005008 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5009 return RewriteObjCTryStmt(StmtTry);
5010
5011 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5012 return RewriteObjCSynchronizedStmt(StmtTry);
5013
5014 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5015 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump1eb44332009-09-09 15:08:12 +00005016
Steve Narofffa15fd92008-10-28 20:29:00 +00005017 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5018 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump1eb44332009-09-09 15:08:12 +00005019
5020 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofffa15fd92008-10-28 20:29:00 +00005021 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump1eb44332009-09-09 15:08:12 +00005022 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofffa15fd92008-10-28 20:29:00 +00005023 OrigStmtRange.getEnd());
5024 if (BreakStmt *StmtBreakStmt =
5025 dyn_cast<BreakStmt>(S))
5026 return RewriteBreakStmt(StmtBreakStmt);
5027 if (ContinueStmt *StmtContinueStmt =
5028 dyn_cast<ContinueStmt>(S))
5029 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump1eb44332009-09-09 15:08:12 +00005030
5031 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofffa15fd92008-10-28 20:29:00 +00005032 // and cast exprs.
5033 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5034 // FIXME: What we're doing here is modifying the type-specifier that
5035 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump1eb44332009-09-09 15:08:12 +00005036 // a separate type-specifier that we can rewrite.
Steve Naroff3d7e7862009-12-05 15:55:59 +00005037 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5038 // the context of an ObjCForCollectionStmt. For example:
5039 // NSArray *someArray;
5040 // for (id <FooProtocol> index in someArray) ;
5041 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5042 // and it depends on the original text locations/positions.
Benjamin Kramerb2041de2009-12-05 22:16:51 +00005043 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroff3d7e7862009-12-05 15:55:59 +00005044 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump1eb44332009-09-09 15:08:12 +00005045
Steve Narofffa15fd92008-10-28 20:29:00 +00005046 // Blocks rewrite rules.
5047 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5048 DI != DE; ++DI) {
Douglas Gregor4afa39d2009-01-20 01:17:11 +00005049 Decl *SD = *DI;
Steve Narofffa15fd92008-10-28 20:29:00 +00005050 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005051 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005052 RewriteBlockPointerDecl(ND);
Mike Stump1eb44332009-09-09 15:08:12 +00005053 else if (ND->getType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005054 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005055 if (VarDecl *VD = dyn_cast<VarDecl>(SD))
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005056 if (VD->hasAttr<BlocksAttr>()) {
5057 static unsigned uniqueByrefDeclCount = 0;
5058 assert(!BlockByRefDeclNo.count(ND) &&
5059 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5060 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian52b08f22009-12-23 02:07:37 +00005061 RewriteByRefVar(VD);
Fariborz Jahaniana73165e2010-01-14 23:05:52 +00005062 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005063 }
5064 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005065 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005066 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005067 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005068 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5069 }
5070 }
5071 }
Mike Stump1eb44332009-09-09 15:08:12 +00005072
Steve Narofffa15fd92008-10-28 20:29:00 +00005073 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5074 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump1eb44332009-09-09 15:08:12 +00005075
5076 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofffa15fd92008-10-28 20:29:00 +00005077 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5078 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump1eb44332009-09-09 15:08:12 +00005079 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5080 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005081 && "Statement stack mismatch");
5082 Stmts.pop_back();
5083 }
5084 // Handle blocks rewriting.
5085 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
5086 if (BDRE->isByRef())
Steve Naroff621edce2009-04-29 16:37:50 +00005087 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofffa15fd92008-10-28 20:29:00 +00005088 }
Fariborz Jahanianf381cc92010-01-04 19:50:07 +00005089 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5090 ValueDecl *VD = DRE->getDecl();
5091 if (VD->hasAttr<BlocksAttr>())
5092 return RewriteBlockDeclRefExpr(DRE);
5093 }
5094
Steve Narofffa15fd92008-10-28 20:29:00 +00005095 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005096 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahanian8a9e1702009-12-15 17:30:20 +00005097 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroffaa4d5ae2008-10-30 10:07:53 +00005098 ReplaceStmt(S, BlockCall);
5099 return BlockCall;
5100 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005101 }
Steve Naroffb2f9e512008-11-03 23:29:32 +00005102 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005103 RewriteCastExpr(CE);
5104 }
5105#if 0
5106 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek8189cde2009-02-07 01:47:29 +00005107 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofffa15fd92008-10-28 20:29:00 +00005108 // Get the new text.
5109 std::string SStr;
5110 llvm::raw_string_ostream Buf(SStr);
Eli Friedman3a9eb442009-05-30 05:19:26 +00005111 Replacement->printPretty(Buf, *Context);
Steve Narofffa15fd92008-10-28 20:29:00 +00005112 const std::string &Str = Buf.str();
5113
5114 printf("CAST = %s\n", &Str[0]);
5115 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5116 delete S;
5117 return Replacement;
5118 }
5119#endif
5120 // Return this stmt unmodified.
5121 return S;
5122}
5123
Steve Naroff3d7e7862009-12-05 15:55:59 +00005124void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
5125 for (RecordDecl::field_iterator i = RD->field_begin(),
5126 e = RD->field_end(); i != e; ++i) {
5127 FieldDecl *FD = *i;
5128 if (isTopLevelBlockPointerType(FD->getType()))
5129 RewriteBlockPointerDecl(FD);
5130 if (FD->getType()->isObjCQualifiedIdType() ||
5131 FD->getType()->isObjCQualifiedInterfaceType())
5132 RewriteObjCQualifiedInterfaceTypes(FD);
5133 }
5134}
5135
Steve Narofffa15fd92008-10-28 20:29:00 +00005136/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5137/// main file of the input.
5138void RewriteObjC::HandleDeclInMainFile(Decl *D) {
5139 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffcb735302008-12-17 00:20:22 +00005140 if (FD->isOverloadedOperator())
5141 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005142
Steve Narofffa15fd92008-10-28 20:29:00 +00005143 // Since function prototypes don't have ParmDecl's, we check the function
5144 // prototype. This enables us to rewrite function declarations and
5145 // definitions using the same code.
Douglas Gregor72564e72009-02-26 23:50:07 +00005146 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005147
Sebastian Redld3a413d2009-04-26 20:35:05 +00005148 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005149 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005150 CurFunctionDef = FD;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005151 CurFunctionDeclToDeclareForBlock = FD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005152 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005153 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005154 Body =
5155 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5156 FD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005157 CurrentBody = 0;
5158 if (PropParentMap) {
5159 delete PropParentMap;
5160 PropParentMap = 0;
5161 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005162 // This synthesizes and inserts the block "impl" struct, invoke function,
5163 // and any copy/dispose helper functions.
5164 InsertBlockLiteralsWithinFunction(FD);
5165 CurFunctionDef = 0;
Fariborz Jahanianabfd83e2010-01-14 00:35:56 +00005166 CurFunctionDeclToDeclareForBlock = 0;
Mike Stump1eb44332009-09-09 15:08:12 +00005167 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005168 return;
5169 }
5170 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00005171 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005172 CurMethodDef = MD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005173 CollectPropertySetters(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005174 CurrentBody = Body;
Ted Kremenekeaab2062009-03-12 18:33:24 +00005175 Body =
5176 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5177 MD->setBody(Body);
Steve Naroff8599e7a2008-12-08 16:43:47 +00005178 CurrentBody = 0;
5179 if (PropParentMap) {
5180 delete PropParentMap;
5181 PropParentMap = 0;
5182 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005183 InsertBlockLiteralsWithinMethod(MD);
5184 CurMethodDef = 0;
5185 }
5186 }
5187 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
5188 ClassImplementation.push_back(CI);
5189 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
5190 CategoryImplementation.push_back(CI);
5191 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
5192 RewriteForwardClassDecl(CD);
5193 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
5194 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005195 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005196 RewriteBlockPointerDecl(VD);
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005197 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005198 CheckFunctionPointerDecl(VD->getType(), VD);
5199 if (VD->getInit()) {
Steve Naroffb2f9e512008-11-03 23:29:32 +00005200 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005201 RewriteCastExpr(CE);
5202 }
5203 }
Steve Naroff3d7e7862009-12-05 15:55:59 +00005204 } else if (VD->getType()->isRecordType()) {
5205 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5206 if (RD->isDefinition())
5207 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005208 }
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005209 if (VD->getInit()) {
5210 GlobalVarDecl = VD;
Steve Naroffc77a6362008-12-04 16:24:46 +00005211 CollectPropertySetters(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005212 CurrentBody = VD->getInit();
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005213 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff8599e7a2008-12-08 16:43:47 +00005214 CurrentBody = 0;
5215 if (PropParentMap) {
5216 delete PropParentMap;
5217 PropParentMap = 0;
5218 }
Mike Stump1eb44332009-09-09 15:08:12 +00005219 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner8ec03f52008-11-24 03:54:41 +00005220 VD->getNameAsCString());
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005221 GlobalVarDecl = 0;
5222
5223 // This is needed for blocks.
Steve Naroffb2f9e512008-11-03 23:29:32 +00005224 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroff8e2f57a2008-10-29 18:15:37 +00005225 RewriteCastExpr(CE);
5226 }
5227 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005228 return;
5229 }
5230 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroff01f2ffa2008-12-11 21:05:33 +00005231 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofffa15fd92008-10-28 20:29:00 +00005232 RewriteBlockPointerDecl(TD);
Mike Stump1eb44332009-09-09 15:08:12 +00005233 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofffa15fd92008-10-28 20:29:00 +00005234 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroff3d7e7862009-12-05 15:55:59 +00005235 else if (TD->getUnderlyingType()->isRecordType()) {
5236 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
5237 if (RD->isDefinition())
5238 RewriteRecordBody(RD);
5239 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005240 return;
5241 }
5242 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroff3d7e7862009-12-05 15:55:59 +00005243 if (RD->isDefinition())
5244 RewriteRecordBody(RD);
Steve Narofffa15fd92008-10-28 20:29:00 +00005245 return;
5246 }
5247 // Nothing yet.
5248}
5249
Chris Lattnerdacbc5d2009-03-28 04:11:33 +00005250void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofffa15fd92008-10-28 20:29:00 +00005251 // Get the top-level buffer that this corresponds to.
Mike Stump1eb44332009-09-09 15:08:12 +00005252
Steve Narofffa15fd92008-10-28 20:29:00 +00005253 // Rewrite tabs if we care.
5254 //RewriteTabs();
Mike Stump1eb44332009-09-09 15:08:12 +00005255
Steve Narofffa15fd92008-10-28 20:29:00 +00005256 if (Diags.hasErrorOccurred())
5257 return;
Mike Stump1eb44332009-09-09 15:08:12 +00005258
Steve Narofffa15fd92008-10-28 20:29:00 +00005259 RewriteInclude();
Mike Stump1eb44332009-09-09 15:08:12 +00005260
Steve Naroff621edce2009-04-29 16:37:50 +00005261 // Here's a great place to add any extra declarations that may be needed.
5262 // Write out meta data for each @protocol(<expr>).
Mike Stump1eb44332009-09-09 15:08:12 +00005263 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroff621edce2009-04-29 16:37:50 +00005264 E = ProtocolExprDecls.end(); I != E; ++I)
5265 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
5266
Mike Stump1eb44332009-09-09 15:08:12 +00005267 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofffa15fd92008-10-28 20:29:00 +00005268 Preamble.c_str(), Preamble.size(), false);
Steve Naroff0aab7962008-11-14 14:10:01 +00005269 if (ClassImplementation.size() || CategoryImplementation.size())
5270 RewriteImplementations();
Steve Naroff621edce2009-04-29 16:37:50 +00005271
Steve Narofffa15fd92008-10-28 20:29:00 +00005272 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5273 // we are done.
Mike Stump1eb44332009-09-09 15:08:12 +00005274 if (const RewriteBuffer *RewriteBuf =
Steve Narofffa15fd92008-10-28 20:29:00 +00005275 Rewrite.getRewriteBufferFor(MainFileID)) {
5276 //printf("Changed:\n");
5277 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5278 } else {
5279 fprintf(stderr, "No changes\n");
5280 }
Steve Narofface66252008-11-13 20:07:04 +00005281
Steve Naroff621edce2009-04-29 16:37:50 +00005282 if (ClassImplementation.size() || CategoryImplementation.size() ||
5283 ProtocolExprDecls.size()) {
Steve Naroff0aab7962008-11-14 14:10:01 +00005284 // Rewrite Objective-c meta data*
5285 std::string ResultStr;
5286 SynthesizeMetaDataIntoBuffer(ResultStr);
5287 // Emit metadata.
5288 *OutFile << ResultStr;
5289 }
Steve Narofffa15fd92008-10-28 20:29:00 +00005290 OutFile->flush();
5291}
5292