blob: 027fa65e9f382ddaf66154225a31ec15eeaa5676 [file] [log] [blame]
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
Chris Lattnere99c8322007-10-11 00:43:27 +00002//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-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 Lattnere99c8322007-10-11 00:43:27 +00007//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Eli Friedman9f30fc32009-05-18 22:50:54 +000014#include "clang/Frontend/ASTConsumers.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000015#include "clang/Rewrite/Rewriter.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000016#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
Steve Naroff1042ff32008-12-08 16:43:47 +000018#include "clang/AST/ParentMap.h"
Chris Lattner16a0de42007-10-11 18:38:32 +000019#include "clang/Basic/SourceManager.h"
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000020#include "clang/Basic/IdentifierTable.h"
Chris Lattner4431a1b2007-11-30 22:53:43 +000021#include "clang/Basic/Diagnostic.h"
Chris Lattnerf3a59a12007-12-02 01:13:47 +000022#include "clang/Lex/Lexer.h"
Benjamin Kramer89b422c2009-08-23 12:08:50 +000023#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
Chris Lattner211f8b82007-10-25 17:07:24 +000025#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian99e96b02007-10-26 19:46:17 +000026#include "llvm/ADT/SmallPtrSet.h"
Ted Kremenek2d470fc2008-09-13 05:16:45 +000027#include "llvm/ADT/OwningPtr.h"
Chris Lattnere99c8322007-10-11 00:43:27 +000028using namespace clang;
Chris Lattner211f8b82007-10-25 17:07:24 +000029using llvm::utostr;
Chris Lattnere99c8322007-10-11 00:43:27 +000030
Chris Lattnere99c8322007-10-11 00:43:27 +000031namespace {
Steve Naroff1dc53ef2008-04-14 22:03:09 +000032 class RewriteObjC : public ASTConsumer {
Chris Lattner0bd1c972007-10-16 21:07:07 +000033 Rewriter Rewrite;
Chris Lattnere9c810c2007-11-30 22:25:36 +000034 Diagnostic &Diags;
Steve Naroff945a3b12008-03-10 20:43:59 +000035 const LangOptions &LangOpts;
Steve Naroff7b3579b2008-01-30 19:17:43 +000036 unsigned RewriteFailedDiag;
Steve Naroff6d6da252008-12-05 17:03:39 +000037 unsigned TryFinallyContainsReturnDiag;
Mike Stump11289f42009-09-09 15:08:12 +000038
Chris Lattnerc6d91c02007-10-17 22:35:30 +000039 ASTContext *Context;
Chris Lattnere99c8322007-10-11 00:43:27 +000040 SourceManager *SM;
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +000041 TranslationUnitDecl *TUDecl;
Chris Lattnerd32480d2009-01-17 06:22:33 +000042 FileID MainFileID;
Chris Lattnerf3a59a12007-12-02 01:13:47 +000043 const char *MainFileStart, *MainFileEnd;
Chris Lattner0bd1c972007-10-16 21:07:07 +000044 SourceLocation LastIncLoc;
Mike Stump11289f42009-09-09 15:08:12 +000045
Ted Kremenek1b0ea822008-01-07 19:49:32 +000046 llvm::SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
47 llvm::SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
48 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
Steve Naroff13e74872008-05-06 18:26:51 +000049 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Ted Kremenek1b0ea822008-01-07 19:49:32 +000050 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
51 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000052 llvm::SmallVector<Stmt *, 32> Stmts;
53 llvm::SmallVector<int, 8> ObjCBcLabelNo;
Steve Naroffd9803712009-04-29 16:37:50 +000054 // Remember all the @protocol(<expr>) expressions.
55 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
Mike Stump11289f42009-09-09 15:08:12 +000056
Steve Naroffce8e8862008-03-15 00:55:56 +000057 unsigned NumObjCStringLiterals;
Mike Stump11289f42009-09-09 15:08:12 +000058
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000059 FunctionDecl *MsgSendFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +000060 FunctionDecl *MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +000061 FunctionDecl *MsgSendStretFunctionDecl;
62 FunctionDecl *MsgSendSuperStretFunctionDecl;
Fariborz Jahanian4f76f222007-12-03 21:26:48 +000063 FunctionDecl *MsgSendFpretFunctionDecl;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +000064 FunctionDecl *GetClassFunctionDecl;
Steve Naroffb2f8ff12007-12-07 03:50:46 +000065 FunctionDecl *GetMetaClassFunctionDecl;
Steve Naroff574440f2007-10-24 22:48:43 +000066 FunctionDecl *SelGetUidFunctionDecl;
Steve Naroff265a6b92007-11-08 14:30:50 +000067 FunctionDecl *CFStringFunctionDecl;
Steve Naroff17978c42008-03-11 17:37:02 +000068 FunctionDecl *SuperContructorFunctionDecl;
Mike Stump11289f42009-09-09 15:08:12 +000069
Steve Naroffa397efd2007-11-03 11:27:19 +000070 // ObjC string constant support.
Steve Naroff08899ff2008-04-15 22:42:06 +000071 VarDecl *ConstantStringClassReference;
Steve Naroffa397efd2007-11-03 11:27:19 +000072 RecordDecl *NSStringRecord;
Mike Stump11289f42009-09-09 15:08:12 +000073
Fariborz Jahanian19d42bf2008-01-16 00:09:11 +000074 // ObjC foreach break/continue generation support.
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +000075 int BcLabelCount;
Mike Stump11289f42009-09-09 15:08:12 +000076
Steve Naroff7fa2f042007-11-15 10:28:18 +000077 // Needed for super.
Steve Naroff677ab3a2008-10-27 17:20:55 +000078 ObjCMethodDecl *CurMethodDef;
Steve Naroff7fa2f042007-11-15 10:28:18 +000079 RecordDecl *SuperStructDecl;
Steve Naroffce8e8862008-03-15 00:55:56 +000080 RecordDecl *ConstantStringDecl;
Mike Stump11289f42009-09-09 15:08:12 +000081
Steve Naroffd9803712009-04-29 16:37:50 +000082 TypeDecl *ProtocolTypeDecl;
83 QualType getProtocolType();
Mike Stump11289f42009-09-09 15:08:12 +000084
Fariborz Jahanian159ee392008-01-18 01:15:54 +000085 // Needed for header files being rewritten
86 bool IsHeader;
Mike Stump11289f42009-09-09 15:08:12 +000087
Steve Narofff9e7c902008-03-28 22:26:09 +000088 std::string InFileName;
Eli Friedman94cf21e2009-05-18 22:20:00 +000089 llvm::raw_ostream* OutFile;
Eli Friedmanf22439a2009-05-18 22:39:16 +000090
91 bool SilenceRewriteMacroWarning;
92
Steve Naroff00a31762008-03-27 22:29:16 +000093 std::string Preamble;
Steve Naroff677ab3a2008-10-27 17:20:55 +000094
95 // Block expressions.
96 llvm::SmallVector<BlockExpr *, 32> Blocks;
97 llvm::SmallVector<BlockDeclRefExpr *, 32> BlockDeclRefs;
98 llvm::DenseMap<BlockDeclRefExpr *, CallExpr *> BlockCallExprs;
Mike Stump11289f42009-09-09 15:08:12 +000099
Steve Naroff677ab3a2008-10-27 17:20:55 +0000100 // Block related declarations.
101 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDecls;
102 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDecls;
103 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
104
105 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
106
Steve Naroff4588d0f2008-12-04 16:24:46 +0000107 // This maps a property to it's assignment statement.
108 llvm::DenseMap<ObjCPropertyRefExpr *, BinaryOperator *> PropSetters;
Steve Naroff1042ff32008-12-08 16:43:47 +0000109 // This maps a property to it's synthesied message expression.
110 // This allows us to rewrite chained getters (e.g. o.a.b.c).
111 llvm::DenseMap<ObjCPropertyRefExpr *, Stmt *> PropGetters;
Mike Stump11289f42009-09-09 15:08:12 +0000112
Steve Naroff22216db2008-12-04 23:50:32 +0000113 // This maps an original source AST to it's rewritten form. This allows
114 // us to avoid rewriting the same node twice (which is very uncommon).
115 // This is needed to support some of the exotic property rewriting.
116 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
Steve Narofff326f402008-12-03 00:56:33 +0000117
Steve Naroff677ab3a2008-10-27 17:20:55 +0000118 FunctionDecl *CurFunctionDef;
Steve Naroffd8907b72008-10-29 18:15:37 +0000119 VarDecl *GlobalVarDecl;
Mike Stump11289f42009-09-09 15:08:12 +0000120
Steve Naroff08628db2008-12-09 12:56:34 +0000121 bool DisableReplaceStmt;
Mike Stump11289f42009-09-09 15:08:12 +0000122
Fariborz Jahanian93191af2007-10-18 19:23:00 +0000123 static const int OBJC_ABI_VERSION =7 ;
Chris Lattnere99c8322007-10-11 00:43:27 +0000124 public:
Ted Kremenek380df932008-05-31 20:11:04 +0000125 virtual void Initialize(ASTContext &context);
126
Chris Lattner3c799d72007-10-24 17:06:59 +0000127 // Top Level Driver code.
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000128 virtual void HandleTopLevelDecl(DeclGroupRef D) {
129 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I)
130 HandleTopLevelSingleDecl(*I);
131 }
132 void HandleTopLevelSingleDecl(Decl *D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000133 void HandleDeclInMainFile(Decl *D);
Eli Friedman94cf21e2009-05-18 22:20:00 +0000134 RewriteObjC(std::string inFile, llvm::raw_ostream *OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000135 Diagnostic &D, const LangOptions &LOpts,
136 bool silenceMacroWarn);
Ted Kremenek6231e7e2008-08-08 04:15:52 +0000137
138 ~RewriteObjC() {}
Mike Stump11289f42009-09-09 15:08:12 +0000139
Chris Lattnercf169832009-03-28 04:11:33 +0000140 virtual void HandleTranslationUnit(ASTContext &C);
Mike Stump11289f42009-09-09 15:08:12 +0000141
Chris Lattner2e0d2602008-01-31 19:37:57 +0000142 void ReplaceStmt(Stmt *Old, Stmt *New) {
Steve Naroff22216db2008-12-04 23:50:32 +0000143 Stmt *ReplacingStmt = ReplacedNodes[Old];
Mike Stump11289f42009-09-09 15:08:12 +0000144
Steve Naroff22216db2008-12-04 23:50:32 +0000145 if (ReplacingStmt)
146 return; // We can't rewrite the same node twice.
Chris Lattner2e0d2602008-01-31 19:37:57 +0000147
Steve Naroff08628db2008-12-09 12:56:34 +0000148 if (DisableReplaceStmt)
149 return; // Used when rewriting the assignment of a property setter.
150
Steve Naroff22216db2008-12-04 23:50:32 +0000151 // If replacement succeeded or warning disabled return with no warning.
152 if (!Rewrite.ReplaceStmt(Old, New)) {
153 ReplacedNodes[Old] = New;
154 return;
155 }
156 if (SilenceRewriteMacroWarning)
157 return;
Chris Lattner8488c822008-11-18 07:04:44 +0000158 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
159 << Old->getSourceRange();
Chris Lattner2e0d2602008-01-31 19:37:57 +0000160 }
Steve Naroff08628db2008-12-09 12:56:34 +0000161
162 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
163 // Measaure the old text.
164 int Size = Rewrite.getRangeSize(SrcRange);
165 if (Size == -1) {
166 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
167 << Old->getSourceRange();
168 return;
169 }
170 // Get the new text.
171 std::string SStr;
172 llvm::raw_string_ostream S(SStr);
Chris Lattnerc61089a2009-06-30 01:26:17 +0000173 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
Steve Naroff08628db2008-12-09 12:56:34 +0000174 const std::string &Str = S.str();
175
176 // If replacement succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000177 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
Steve Naroff08628db2008-12-09 12:56:34 +0000178 ReplacedNodes[Old] = New;
179 return;
180 }
181 if (SilenceRewriteMacroWarning)
182 return;
183 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
184 << Old->getSourceRange();
185 }
186
Steve Naroff00a31762008-03-27 22:29:16 +0000187 void InsertText(SourceLocation Loc, const char *StrData, unsigned StrLen,
188 bool InsertAfter = true) {
Chris Lattner9cc55f52008-01-31 19:51:04 +0000189 // If insertion succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000190 if (!Rewrite.InsertText(Loc, llvm::StringRef(StrData, StrLen),
191 InsertAfter) ||
Chris Lattner1780a852008-01-31 19:42:41 +0000192 SilenceRewriteMacroWarning)
193 return;
Mike Stump11289f42009-09-09 15:08:12 +0000194
Chris Lattner1780a852008-01-31 19:42:41 +0000195 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
196 }
Mike Stump11289f42009-09-09 15:08:12 +0000197
Chris Lattner9cc55f52008-01-31 19:51:04 +0000198 void RemoveText(SourceLocation Loc, unsigned StrLen) {
199 // If removal succeeded or warning disabled return with no warning.
200 if (!Rewrite.RemoveText(Loc, StrLen) || SilenceRewriteMacroWarning)
201 return;
Mike Stump11289f42009-09-09 15:08:12 +0000202
Chris Lattner9cc55f52008-01-31 19:51:04 +0000203 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
204 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000205
Chris Lattner9cc55f52008-01-31 19:51:04 +0000206 void ReplaceText(SourceLocation Start, unsigned OrigLength,
207 const char *NewStr, unsigned NewLength) {
208 // If removal succeeded or warning disabled return with no warning.
Daniel Dunbardec484a2009-08-19 19:10:30 +0000209 if (!Rewrite.ReplaceText(Start, OrigLength,
210 llvm::StringRef(NewStr, NewLength)) ||
Chris Lattner9cc55f52008-01-31 19:51:04 +0000211 SilenceRewriteMacroWarning)
212 return;
Mike Stump11289f42009-09-09 15:08:12 +0000213
Chris Lattner9cc55f52008-01-31 19:51:04 +0000214 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
215 }
Mike Stump11289f42009-09-09 15:08:12 +0000216
Chris Lattner3c799d72007-10-24 17:06:59 +0000217 // Syntactic Rewriting.
Steve Narofff36987c2007-11-04 22:37:50 +0000218 void RewritePrologue(SourceLocation Loc);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000219 void RewriteInclude();
Chris Lattner3c799d72007-10-24 17:06:59 +0000220 void RewriteTabs();
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000221 void RewriteForwardClassDecl(ObjCClassDecl *Dcl);
Steve Naroffc038b3a2008-12-02 17:36:43 +0000222 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
223 ObjCImplementationDecl *IMD,
224 ObjCCategoryImplDecl *CID);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000225 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000226 void RewriteImplementationDecl(Decl *Dcl);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000227 void RewriteObjCMethodDecl(ObjCMethodDecl *MDecl, std::string &ResultStr);
228 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
229 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
230 void RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *Dcl);
231 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000232 void RewriteProperty(ObjCPropertyDecl *prop);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000233 void RewriteFunctionDecl(FunctionDecl *FD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000234 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
Steve Naroff873bd842008-07-29 18:15:38 +0000235 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Steve Naroff50d42052007-11-01 13:24:47 +0000236 bool needToScanForQualifiers(QualType T);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000237 ObjCInterfaceDecl *isSuperReceiver(Expr *recExpr);
Steve Naroff7fa2f042007-11-15 10:28:18 +0000238 QualType getSuperStructType();
Steve Naroffce8e8862008-03-15 00:55:56 +0000239 QualType getConstantStringStructType();
Steve Naroffcd92aeb2008-05-31 14:15:04 +0000240 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
Mike Stump11289f42009-09-09 15:08:12 +0000241
Chris Lattner3c799d72007-10-24 17:06:59 +0000242 // Expression Rewriting.
Steve Naroff20113382007-11-09 15:20:18 +0000243 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000244 void CollectPropertySetters(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000245
Steve Naroff1042ff32008-12-08 16:43:47 +0000246 Stmt *CurrentBody;
247 ParentMap *PropParentMap; // created lazily.
Mike Stump11289f42009-09-09 15:08:12 +0000248
Chris Lattner69534692007-10-24 16:57:36 +0000249 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
Chris Lattner37f5b7d2008-05-23 20:40:52 +0000250 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV, SourceLocation OrigStart);
Steve Naroff4588d0f2008-12-04 16:24:46 +0000251 Stmt *RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr);
Mike Stump11289f42009-09-09 15:08:12 +0000252 Stmt *RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
Steve Naroff08628db2008-12-09 12:56:34 +0000253 SourceRange SrcRange);
Steve Naroffe4f9b232007-11-05 14:50:49 +0000254 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
Chris Lattner69534692007-10-24 16:57:36 +0000255 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
Steve Naroffa397efd2007-11-03 11:27:19 +0000256 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian33c0e812007-12-07 18:47:10 +0000257 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Steve Naroffec60b432009-12-05 21:43:12 +0000258 void WarnAboutReturnGotoStmts(Stmt *S);
259 void HasReturnStmts(Stmt *S, bool &hasReturns);
260 void RewriteTryReturnStmts(Stmt *S);
261 void RewriteSyncReturnStmts(Stmt *S, std::string buf);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000262 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian284011b2008-01-29 22:59:37 +0000263 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000264 Stmt *RewriteObjCCatchStmt(ObjCAtCatchStmt *S);
265 Stmt *RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S);
266 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
Chris Lattnera779d692008-01-31 05:10:40 +0000267 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
268 SourceLocation OrigEnd);
Mike Stump11289f42009-09-09 15:08:12 +0000269 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
Steve Naroff574440f2007-10-24 22:48:43 +0000270 Expr **args, unsigned nargs);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000271 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp);
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +0000272 Stmt *RewriteBreakStmt(BreakStmt *S);
273 Stmt *RewriteContinueStmt(ContinueStmt *S);
Fariborz Jahanian965a8962008-01-08 22:06:28 +0000274 void SynthCountByEnumWithState(std::string &buf);
Mike Stump11289f42009-09-09 15:08:12 +0000275
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000276 void SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +0000277 void SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000278 void SynthMsgSendStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +0000279 void SynthMsgSendFpretFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +0000280 void SynthMsgSendSuperStretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000281 void SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +0000282 void SynthGetMetaClassFunctionDecl();
Fariborz Jahanian31e18502007-12-04 21:47:40 +0000283 void SynthSelGetUidFunctionDecl();
Steve Naroff17978c42008-03-11 17:37:02 +0000284 void SynthSuperContructorFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000285
Chris Lattner3c799d72007-10-24 17:06:59 +0000286 // Metadata emission.
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000287 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000288 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000289
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000290 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +0000291 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000292
Douglas Gregor29bd76f2009-04-23 01:02:12 +0000293 template<typename MethodIterator>
294 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
295 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +0000296 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +0000297 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +0000298 const char *ClassName,
299 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000300
Steve Naroffd9803712009-04-29 16:37:50 +0000301 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
302 const char *prefix,
303 const char *ClassName,
304 std::string &Result);
305 void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
Mike Stump11289f42009-09-09 15:08:12 +0000306 const char *prefix,
Steve Naroffd9803712009-04-29 16:37:50 +0000307 const char *ClassName,
308 std::string &Result);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000309 void SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000310 std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000311 void SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
312 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +0000313 std::string &Result);
Steve Narofff8cfd162008-11-13 20:07:04 +0000314 void RewriteImplementations();
315 void SynthesizeMetaDataIntoBuffer(std::string &Result);
Mike Stump11289f42009-09-09 15:08:12 +0000316
Steve Naroff677ab3a2008-10-27 17:20:55 +0000317 // Block rewriting.
Mike Stump11289f42009-09-09 15:08:12 +0000318 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000319 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
Mike Stump11289f42009-09-09 15:08:12 +0000320
Steve Naroff677ab3a2008-10-27 17:20:55 +0000321 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
322 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
Mike Stump11289f42009-09-09 15:08:12 +0000323
324 // Block specific rewrite rules.
Steve Naroff677ab3a2008-10-27 17:20:55 +0000325 void RewriteBlockCall(CallExpr *Exp);
326 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian81203462009-12-22 00:48:54 +0000327 void RewriteByRefVar(NamedDecl *VD);
Steve Naroffd9803712009-04-29 16:37:50 +0000328 Stmt *RewriteBlockDeclRefExpr(BlockDeclRefExpr *VD);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000329 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
Mike Stump11289f42009-09-09 15:08:12 +0000330
331 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000332 const char *funcName, std::string Tag);
Mike Stump11289f42009-09-09 15:08:12 +0000333 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
Steve Naroff677ab3a2008-10-27 17:20:55 +0000334 const char *funcName, std::string Tag);
Steve Naroff30484702009-12-06 21:14:13 +0000335 std::string SynthesizeBlockImpl(BlockExpr *CE,
336 std::string Tag, std::string Desc);
337 std::string SynthesizeBlockDescriptor(std::string DescTag,
338 std::string ImplTag,
339 int i, const char *funcName,
340 unsigned hasCopy);
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +0000341 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000342 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
343 const char *FunName);
Steve Naroffe70a52a2009-12-05 15:55:59 +0000344 void RewriteRecordBody(RecordDecl *RD);
Mike Stump11289f42009-09-09 15:08:12 +0000345
Steve Naroff677ab3a2008-10-27 17:20:55 +0000346 void CollectBlockDeclRefInfo(BlockExpr *Exp);
347 void GetBlockCallExprs(Stmt *S);
348 void GetBlockDeclRefExprs(Stmt *S);
Mike Stump11289f42009-09-09 15:08:12 +0000349
Steve Naroff677ab3a2008-10-27 17:20:55 +0000350 // We avoid calling Type::isBlockPointerType(), since it operates on the
351 // canonical type. We only care if the top-level type is a closure pointer.
Ted Kremenek5a201952009-02-07 01:47:29 +0000352 bool isTopLevelBlockPointerType(QualType T) {
353 return isa<BlockPointerType>(T);
354 }
Mike Stump11289f42009-09-09 15:08:12 +0000355
Steve Naroff677ab3a2008-10-27 17:20:55 +0000356 // FIXME: This predicate seems like it would be useful to add to ASTContext.
357 bool isObjCType(QualType T) {
358 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
359 return false;
Mike Stump11289f42009-09-09 15:08:12 +0000360
Steve Naroff677ab3a2008-10-27 17:20:55 +0000361 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
Mike Stump11289f42009-09-09 15:08:12 +0000362
Steve Naroff677ab3a2008-10-27 17:20:55 +0000363 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
364 OCT == Context->getCanonicalType(Context->getObjCClassType()))
365 return true;
Mike Stump11289f42009-09-09 15:08:12 +0000366
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000367 if (const PointerType *PT = OCT->getAs<PointerType>()) {
Mike Stump11289f42009-09-09 15:08:12 +0000368 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
Steve Narofffb4330f2009-06-17 22:40:22 +0000369 PT->getPointeeType()->isObjCQualifiedIdType())
Steve Naroff677ab3a2008-10-27 17:20:55 +0000370 return true;
371 }
372 return false;
373 }
374 bool PointerTypeTakesAnyBlockArguments(QualType QT);
Ted Kremenek5a201952009-02-07 01:47:29 +0000375 void GetExtentOfArgList(const char *Name, const char *&LParen,
376 const char *&RParen);
Steve Naroffc989a7b2008-11-03 23:29:32 +0000377 void RewriteCastExpr(CStyleCastExpr *CE);
Mike Stump11289f42009-09-09 15:08:12 +0000378
Steve Narofff4b992a2008-10-28 20:29:00 +0000379 FunctionDecl *SynthBlockInitFunctionDecl(const char *name);
Steve Naroffd8907b72008-10-29 18:15:37 +0000380 Stmt *SynthBlockInitExpr(BlockExpr *Exp);
Mike Stump11289f42009-09-09 15:08:12 +0000381
Steve Naroffd9803712009-04-29 16:37:50 +0000382 void QuoteDoublequotes(std::string &From, std::string &To) {
Mike Stump11289f42009-09-09 15:08:12 +0000383 for (unsigned i = 0; i < From.length(); i++) {
Steve Naroffd9803712009-04-29 16:37:50 +0000384 if (From[i] == '"')
385 To += "\\\"";
386 else
387 To += From[i];
388 }
389 }
Chris Lattnere99c8322007-10-11 00:43:27 +0000390 };
391}
392
Mike Stump11289f42009-09-09 15:08:12 +0000393void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
394 NamedDecl *D) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000395 if (FunctionProtoType *fproto = dyn_cast<FunctionProtoType>(funcType)) {
Mike Stump11289f42009-09-09 15:08:12 +0000396 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +0000397 E = fproto->arg_type_end(); I && (I != E); ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +0000398 if (isTopLevelBlockPointerType(*I)) {
Steve Naroff677ab3a2008-10-27 17:20:55 +0000399 // All the args are checked/rewritten. Don't call twice!
400 RewriteBlockPointerDecl(D);
401 break;
402 }
403 }
404}
405
406void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000407 const PointerType *PT = funcType->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +0000408 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000409 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
Steve Naroff677ab3a2008-10-27 17:20:55 +0000410}
411
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000412static bool IsHeaderFile(const std::string &Filename) {
413 std::string::size_type DotPos = Filename.rfind('.');
Mike Stump11289f42009-09-09 15:08:12 +0000414
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000415 if (DotPos == std::string::npos) {
416 // no file extension
Mike Stump11289f42009-09-09 15:08:12 +0000417 return false;
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000418 }
Mike Stump11289f42009-09-09 15:08:12 +0000419
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000420 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
421 // C header: .h
422 // C++ header: .hh or .H;
423 return Ext == "h" || Ext == "hh" || Ext == "H";
Mike Stump11289f42009-09-09 15:08:12 +0000424}
Fariborz Jahanian159ee392008-01-18 01:15:54 +0000425
Eli Friedman94cf21e2009-05-18 22:20:00 +0000426RewriteObjC::RewriteObjC(std::string inFile, llvm::raw_ostream* OS,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000427 Diagnostic &D, const LangOptions &LOpts,
428 bool silenceMacroWarn)
429 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
430 SilenceRewriteMacroWarning(silenceMacroWarn) {
Steve Narofff9e7c902008-03-28 22:26:09 +0000431 IsHeader = IsHeaderFile(inFile);
Mike Stump11289f42009-09-09 15:08:12 +0000432 RewriteFailedDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Steve Narofff9e7c902008-03-28 22:26:09 +0000433 "rewriting sub-expression within a macro (may not be correct)");
Mike Stump11289f42009-09-09 15:08:12 +0000434 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(Diagnostic::Warning,
Ted Kremenek5a201952009-02-07 01:47:29 +0000435 "rewriter doesn't support user-specified control flow semantics "
436 "for @try/@finally (code may not execute properly)");
Steve Narofff9e7c902008-03-28 22:26:09 +0000437}
438
Eli Friedmana63ab2d2009-05-18 22:29:17 +0000439ASTConsumer *clang::CreateObjCRewriter(const std::string& InFile,
440 llvm::raw_ostream* OS,
Mike Stump11289f42009-09-09 15:08:12 +0000441 Diagnostic &Diags,
Eli Friedmanf22439a2009-05-18 22:39:16 +0000442 const LangOptions &LOpts,
443 bool SilenceRewriteMacroWarning) {
444 return new RewriteObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
Chris Lattnere9c810c2007-11-30 22:25:36 +0000445}
Chris Lattnere99c8322007-10-11 00:43:27 +0000446
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000447void RewriteObjC::Initialize(ASTContext &context) {
Chris Lattner187f6262008-01-31 19:38:44 +0000448 Context = &context;
449 SM = &Context->getSourceManager();
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +0000450 TUDecl = Context->getTranslationUnitDecl();
Chris Lattner187f6262008-01-31 19:38:44 +0000451 MsgSendFunctionDecl = 0;
452 MsgSendSuperFunctionDecl = 0;
453 MsgSendStretFunctionDecl = 0;
454 MsgSendSuperStretFunctionDecl = 0;
455 MsgSendFpretFunctionDecl = 0;
456 GetClassFunctionDecl = 0;
457 GetMetaClassFunctionDecl = 0;
458 SelGetUidFunctionDecl = 0;
459 CFStringFunctionDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000460 ConstantStringClassReference = 0;
461 NSStringRecord = 0;
Steve Naroff677ab3a2008-10-27 17:20:55 +0000462 CurMethodDef = 0;
463 CurFunctionDef = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000464 GlobalVarDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000465 SuperStructDecl = 0;
Steve Naroffd9803712009-04-29 16:37:50 +0000466 ProtocolTypeDecl = 0;
Steve Naroff60a9ef62008-03-27 22:59:54 +0000467 ConstantStringDecl = 0;
Chris Lattner187f6262008-01-31 19:38:44 +0000468 BcLabelCount = 0;
Steve Naroff17978c42008-03-11 17:37:02 +0000469 SuperContructorFunctionDecl = 0;
Steve Naroffce8e8862008-03-15 00:55:56 +0000470 NumObjCStringLiterals = 0;
Steve Narofff1ab6002008-12-08 20:01:41 +0000471 PropParentMap = 0;
472 CurrentBody = 0;
Steve Naroff08628db2008-12-09 12:56:34 +0000473 DisableReplaceStmt = false;
Mike Stump11289f42009-09-09 15:08:12 +0000474
Chris Lattner187f6262008-01-31 19:38:44 +0000475 // Get the ID and start/end of the main file.
476 MainFileID = SM->getMainFileID();
477 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
478 MainFileStart = MainBuf->getBufferStart();
479 MainFileEnd = MainBuf->getBufferEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000480
Chris Lattner184e65d2009-04-14 23:22:57 +0000481 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOptions());
Mike Stump11289f42009-09-09 15:08:12 +0000482
Chris Lattner187f6262008-01-31 19:38:44 +0000483 // declaring objc_selector outside the parameter list removes a silly
484 // scope related warning...
Steve Naroff00a31762008-03-27 22:29:16 +0000485 if (IsHeader)
Steve Narofffcc6fd52009-02-03 20:39:18 +0000486 Preamble = "#pragma once\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000487 Preamble += "struct objc_selector; struct objc_class;\n";
Steve Naroff6ab6dc72008-12-23 20:11:22 +0000488 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
Steve Naroff00a31762008-03-27 22:29:16 +0000489 Preamble += "struct objc_object *superClass; ";
Steve Naroff17978c42008-03-11 17:37:02 +0000490 if (LangOpts.Microsoft) {
491 // Add a constructor for creating temporary objects.
Ted Kremenek5a201952009-02-07 01:47:29 +0000492 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
493 ": ";
Steve Naroff00a31762008-03-27 22:29:16 +0000494 Preamble += "object(o), superClass(s) {} ";
Steve Naroff17978c42008-03-11 17:37:02 +0000495 }
Steve Naroff00a31762008-03-27 22:29:16 +0000496 Preamble += "};\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000497 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
498 Preamble += "typedef struct objc_object Protocol;\n";
499 Preamble += "#define _REWRITER_typedef_Protocol\n";
500 Preamble += "#endif\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000501 if (LangOpts.Microsoft) {
502 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
503 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
504 } else
505 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
506 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
Steve Naroff00a31762008-03-27 22:29:16 +0000507 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000508 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
Steve Naroff00a31762008-03-27 22:29:16 +0000509 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000510 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000511 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000512 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper_stret";
Steve Naroff00a31762008-03-27 22:29:16 +0000513 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000514 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
Steve Naroff00a31762008-03-27 22:29:16 +0000515 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000516 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000517 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000518 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
Steve Naroff00a31762008-03-27 22:29:16 +0000519 Preamble += "(const char *);\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000520 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
521 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
522 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
523 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
524 Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
Steve Naroffd30f8c52008-05-09 21:17:56 +0000525 Preamble += "(struct objc_class *, struct objc_object *);\n";
Steve Naroff8dd15252008-07-16 18:58:11 +0000526 // @synchronized hooks.
Steve Narofff122ff02008-12-08 17:30:33 +0000527 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter(struct objc_object *);\n";
528 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit(struct objc_object *);\n";
529 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000530 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
531 Preamble += "struct __objcFastEnumerationState {\n\t";
532 Preamble += "unsigned long state;\n\t";
Steve Naroff4dbab8a2008-04-04 22:58:22 +0000533 Preamble += "void **itemsPtr;\n\t";
Steve Naroff00a31762008-03-27 22:29:16 +0000534 Preamble += "unsigned long *mutationsPtr;\n\t";
535 Preamble += "unsigned long extra[5];\n};\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000536 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000537 Preamble += "#define __FASTENUMERATIONSTATE\n";
538 Preamble += "#endif\n";
539 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
540 Preamble += "struct __NSConstantStringImpl {\n";
541 Preamble += " int *isa;\n";
542 Preamble += " int flags;\n";
543 Preamble += " char *str;\n";
544 Preamble += " long length;\n";
545 Preamble += "};\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000546 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
547 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
548 Preamble += "#else\n";
Steve Narofff122ff02008-12-08 17:30:33 +0000549 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
Steve Naroffdd514e02008-08-05 20:04:48 +0000550 Preamble += "#endif\n";
Steve Naroff00a31762008-03-27 22:29:16 +0000551 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
552 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000553 // Blocks preamble.
554 Preamble += "#ifndef BLOCK_IMPL\n";
555 Preamble += "#define BLOCK_IMPL\n";
556 Preamble += "struct __block_impl {\n";
557 Preamble += " void *isa;\n";
558 Preamble += " int Flags;\n";
Steve Naroff30484702009-12-06 21:14:13 +0000559 Preamble += " int Reserved;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000560 Preamble += " void *FuncPtr;\n";
561 Preamble += "};\n";
Steve Naroff61d879e2008-12-16 15:50:30 +0000562 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
Steve Naroff287a2bf2009-12-06 01:52:22 +0000563 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000564 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_assign(void *, const void *, const int);\n";
565 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
566 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
567 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
568 Preamble += "#else\n";
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +0000569 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_assign(void *, const void *, const int);\n";
570 Preamble += "__OBJC_RW_DLLIMPORT \"C\" void _Block_object_dispose(const void *, const int);\n";
Steve Naroff2b3843d2009-12-06 01:33:56 +0000571 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
572 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
573 Preamble += "#endif\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +0000574 Preamble += "#endif\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000575 if (LangOpts.Microsoft) {
Steve Narofff122ff02008-12-08 17:30:33 +0000576 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
577 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
Steve Naroffcb04e882008-10-27 18:50:14 +0000578 Preamble += "#define __attribute__(X)\n";
579 }
Chris Lattner187f6262008-01-31 19:38:44 +0000580}
581
582
Chris Lattner3c799d72007-10-24 17:06:59 +0000583//===----------------------------------------------------------------------===//
584// Top Level Driver Code
585//===----------------------------------------------------------------------===//
586
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000587void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
Chris Lattner0bd1c972007-10-16 21:07:07 +0000588 // Two cases: either the decl could be in the main file, or it could be in a
589 // #included file. If the former, rewrite it now. If the later, check to see
590 // if we rewrote the #include/#import.
591 SourceLocation Loc = D->getLocation();
Chris Lattner8a425862009-01-16 07:36:28 +0000592 Loc = SM->getInstantiationLoc(Loc);
Mike Stump11289f42009-09-09 15:08:12 +0000593
Chris Lattner0bd1c972007-10-16 21:07:07 +0000594 // If this is for a builtin, ignore it.
595 if (Loc.isInvalid()) return;
596
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000597 // Look for built-in declarations that we need to refer during the rewrite.
598 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +0000599 RewriteFunctionDecl(FD);
Steve Naroff08899ff2008-04-15 22:42:06 +0000600 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000601 // declared in <Foundation/NSString.h>
Chris Lattner86d7d912008-11-24 03:54:41 +0000602 if (strcmp(FVD->getNameAsCString(), "_NSConstantStringClassReference") == 0) {
Steve Naroffa397efd2007-11-03 11:27:19 +0000603 ConstantStringClassReference = FVD;
604 return;
605 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000606 } else if (ObjCInterfaceDecl *MD = dyn_cast<ObjCInterfaceDecl>(D)) {
Steve Naroff161a92b2007-10-26 20:53:56 +0000607 RewriteInterfaceDecl(MD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000608 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000609 RewriteCategoryDecl(CD);
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000610 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
Steve Narofff921385f2007-10-30 16:42:30 +0000611 RewriteProtocolDecl(PD);
Mike Stump11289f42009-09-09 15:08:12 +0000612 } else if (ObjCForwardProtocolDecl *FP =
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000613 dyn_cast<ObjCForwardProtocolDecl>(D)){
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000614 RewriteForwardProtocolDecl(FP);
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000615 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
616 // Recurse into linkage specifications
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000617 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
618 DIEnd = LSD->decls_end();
Douglas Gregorc25d7a72009-01-09 00:49:46 +0000619 DI != DIEnd; ++DI)
Chris Lattner5bbb3c82009-03-29 16:50:03 +0000620 HandleTopLevelSingleDecl(*DI);
Steve Naroffdb1ab1c2007-10-23 23:50:29 +0000621 }
Chris Lattner3c799d72007-10-24 17:06:59 +0000622 // If we have a decl in the main file, see if we should rewrite it.
Ted Kremenekd61ed3b2008-04-14 21:24:13 +0000623 if (SM->isFromMainFile(Loc))
Chris Lattner0bd1c972007-10-16 21:07:07 +0000624 return HandleDeclInMainFile(D);
Chris Lattner0bd1c972007-10-16 21:07:07 +0000625}
626
Chris Lattner3c799d72007-10-24 17:06:59 +0000627//===----------------------------------------------------------------------===//
628// Syntactic (non-AST) Rewriting Code
629//===----------------------------------------------------------------------===//
630
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000631void RewriteObjC::RewriteInclude() {
Chris Lattnerd32480d2009-01-17 06:22:33 +0000632 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000633 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
634 const char *MainBufStart = MainBuf.first;
635 const char *MainBufEnd = MainBuf.second;
636 size_t ImportLen = strlen("import");
637 size_t IncludeLen = strlen("include");
Mike Stump11289f42009-09-09 15:08:12 +0000638
Fariborz Jahanian137d6932008-01-19 01:03:17 +0000639 // Loop over the whole file, looking for includes.
Fariborz Jahanian80258362008-01-19 00:30:35 +0000640 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
641 if (*BufPtr == '#') {
642 if (++BufPtr == MainBufEnd)
643 return;
644 while (*BufPtr == ' ' || *BufPtr == '\t')
645 if (++BufPtr == MainBufEnd)
646 return;
647 if (!strncmp(BufPtr, "import", ImportLen)) {
648 // replace import with include
Mike Stump11289f42009-09-09 15:08:12 +0000649 SourceLocation ImportLoc =
Fariborz Jahanian80258362008-01-19 00:30:35 +0000650 LocStart.getFileLocWithOffset(BufPtr-MainBufStart);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000651 ReplaceText(ImportLoc, ImportLen, "include", IncludeLen);
Fariborz Jahanian80258362008-01-19 00:30:35 +0000652 BufPtr += ImportLen;
653 }
654 }
655 }
Chris Lattner0bd1c972007-10-16 21:07:07 +0000656}
657
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000658void RewriteObjC::RewriteTabs() {
Chris Lattner3c799d72007-10-24 17:06:59 +0000659 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
660 const char *MainBufStart = MainBuf.first;
661 const char *MainBufEnd = MainBuf.second;
Mike Stump11289f42009-09-09 15:08:12 +0000662
Chris Lattner3c799d72007-10-24 17:06:59 +0000663 // Loop over the whole file, looking for tabs.
664 for (const char *BufPtr = MainBufStart; BufPtr != MainBufEnd; ++BufPtr) {
665 if (*BufPtr != '\t')
666 continue;
Mike Stump11289f42009-09-09 15:08:12 +0000667
Chris Lattner3c799d72007-10-24 17:06:59 +0000668 // Okay, we found a tab. This tab will turn into at least one character,
669 // but it depends on which 'virtual column' it is in. Compute that now.
670 unsigned VCol = 0;
671 while (BufPtr-VCol != MainBufStart && BufPtr[-VCol-1] != '\t' &&
672 BufPtr[-VCol-1] != '\n' && BufPtr[-VCol-1] != '\r')
673 ++VCol;
Mike Stump11289f42009-09-09 15:08:12 +0000674
Chris Lattner3c799d72007-10-24 17:06:59 +0000675 // Okay, now that we know the virtual column, we know how many spaces to
676 // insert. We assume 8-character tab-stops.
677 unsigned Spaces = 8-(VCol & 7);
Mike Stump11289f42009-09-09 15:08:12 +0000678
Chris Lattner3c799d72007-10-24 17:06:59 +0000679 // Get the location of the tab.
Chris Lattnerd32480d2009-01-17 06:22:33 +0000680 SourceLocation TabLoc = SM->getLocForStartOfFile(MainFileID);
681 TabLoc = TabLoc.getFileLocWithOffset(BufPtr-MainBufStart);
Mike Stump11289f42009-09-09 15:08:12 +0000682
Chris Lattner3c799d72007-10-24 17:06:59 +0000683 // Rewrite the single tab character into a sequence of spaces.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000684 ReplaceText(TabLoc, 1, " ", Spaces);
Chris Lattner3c799d72007-10-24 17:06:59 +0000685 }
Chris Lattner16a0de42007-10-11 18:38:32 +0000686}
687
Steve Naroff9af94912008-12-02 15:48:25 +0000688static std::string getIvarAccessString(ObjCInterfaceDecl *ClassDecl,
689 ObjCIvarDecl *OID) {
690 std::string S;
691 S = "((struct ";
692 S += ClassDecl->getIdentifier()->getName();
693 S += "_IMPL *)self)->";
Daniel Dunbar70e7ead2009-10-18 20:26:27 +0000694 S += OID->getName();
Steve Naroff9af94912008-12-02 15:48:25 +0000695 return S;
696}
697
Steve Naroffc038b3a2008-12-02 17:36:43 +0000698void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
699 ObjCImplementationDecl *IMD,
700 ObjCCategoryImplDecl *CID) {
Steve Naroffe1908e32008-12-01 20:33:01 +0000701 SourceLocation startLoc = PID->getLocStart();
702 InsertText(startLoc, "// ", 3);
Steve Naroff9af94912008-12-02 15:48:25 +0000703 const char *startBuf = SM->getCharacterData(startLoc);
704 assert((*startBuf == '@') && "bogus @synthesize location");
705 const char *semiBuf = strchr(startBuf, ';');
706 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
Ted Kremenek5a201952009-02-07 01:47:29 +0000707 SourceLocation onePastSemiLoc =
708 startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
Steve Naroff9af94912008-12-02 15:48:25 +0000709
710 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
711 return; // FIXME: is this correct?
Mike Stump11289f42009-09-09 15:08:12 +0000712
Steve Naroff9af94912008-12-02 15:48:25 +0000713 // Generate the 'getter' function.
Steve Naroff9af94912008-12-02 15:48:25 +0000714 ObjCPropertyDecl *PD = PID->getPropertyDecl();
Steve Naroff9af94912008-12-02 15:48:25 +0000715 ObjCInterfaceDecl *ClassDecl = PD->getGetterMethodDecl()->getClassInterface();
Steve Naroff9af94912008-12-02 15:48:25 +0000716 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Mike Stump11289f42009-09-09 15:08:12 +0000717
Steve Naroff003d00e2008-12-02 16:05:55 +0000718 if (!OID)
719 return;
Mike Stump11289f42009-09-09 15:08:12 +0000720
Steve Naroff003d00e2008-12-02 16:05:55 +0000721 std::string Getr;
722 RewriteObjCMethodDecl(PD->getGetterMethodDecl(), Getr);
723 Getr += "{ ";
724 // Synthesize an explicit cast to gain access to the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000725 // FIXME: deal with code generation implications for various property
726 // attributes (copy, retain, nonatomic).
Steve Naroff06297042008-12-02 17:54:50 +0000727 // See objc-act.c:objc_synthesize_new_getter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000728 Getr += "return " + getIvarAccessString(ClassDecl, OID);
729 Getr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000730 InsertText(onePastSemiLoc, Getr.c_str(), Getr.size());
Steve Naroff9af94912008-12-02 15:48:25 +0000731 if (PD->isReadOnly())
732 return;
Mike Stump11289f42009-09-09 15:08:12 +0000733
Steve Naroff9af94912008-12-02 15:48:25 +0000734 // Generate the 'setter' function.
735 std::string Setr;
736 RewriteObjCMethodDecl(PD->getSetterMethodDecl(), Setr);
Steve Naroff9af94912008-12-02 15:48:25 +0000737 Setr += "{ ";
Steve Naroff003d00e2008-12-02 16:05:55 +0000738 // Synthesize an explicit cast to initialize the ivar.
Mike Stump11289f42009-09-09 15:08:12 +0000739 // FIXME: deal with code generation implications for various property
740 // attributes (copy, retain, nonatomic).
Steve Narofff326f402008-12-03 00:56:33 +0000741 // See objc-act.c:objc_synthesize_new_setter() for details.
Steve Naroff003d00e2008-12-02 16:05:55 +0000742 Setr += getIvarAccessString(ClassDecl, OID) + " = ";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000743 Setr += PD->getNameAsCString();
Steve Naroff003d00e2008-12-02 16:05:55 +0000744 Setr += "; }";
Steve Naroff9af94912008-12-02 15:48:25 +0000745 InsertText(onePastSemiLoc, Setr.c_str(), Setr.size());
Steve Naroffe1908e32008-12-01 20:33:01 +0000746}
Chris Lattner16a0de42007-10-11 18:38:32 +0000747
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000748void RewriteObjC::RewriteForwardClassDecl(ObjCClassDecl *ClassDecl) {
Chris Lattner3c799d72007-10-24 17:06:59 +0000749 // Get the start location and compute the semi location.
750 SourceLocation startLoc = ClassDecl->getLocation();
751 const char *startBuf = SM->getCharacterData(startLoc);
752 const char *semiPtr = strchr(startBuf, ';');
Mike Stump11289f42009-09-09 15:08:12 +0000753
Chris Lattner3c799d72007-10-24 17:06:59 +0000754 // Translate to typedef's that forward reference structs with the same name
755 // as the class. As a convenience, we include the original declaration
756 // as a comment.
757 std::string typedefString;
758 typedefString += "// ";
Steve Naroff574440f2007-10-24 22:48:43 +0000759 typedefString.append(startBuf, semiPtr-startBuf+1);
760 typedefString += "\n";
Chris Lattner9ee23b72009-02-20 18:04:31 +0000761 for (ObjCClassDecl::iterator I = ClassDecl->begin(), E = ClassDecl->end();
762 I != E; ++I) {
Ted Kremenek9b124e12009-11-18 00:28:11 +0000763 ObjCInterfaceDecl *ForwardDecl = I->getInterface();
Steve Naroff1b232132007-11-09 12:50:28 +0000764 typedefString += "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000765 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000766 typedefString += "\n";
767 typedefString += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000768 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000769 typedefString += "\n";
Steve Naroff98eb8d12007-11-05 14:36:37 +0000770 typedefString += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000771 typedefString += ForwardDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +0000772 typedefString += ";\n#endif\n";
Steve Naroff574440f2007-10-24 22:48:43 +0000773 }
Mike Stump11289f42009-09-09 15:08:12 +0000774
Steve Naroff574440f2007-10-24 22:48:43 +0000775 // Replace the @class with typedefs corresponding to the classes.
Mike Stump11289f42009-09-09 15:08:12 +0000776 ReplaceText(startLoc, semiPtr-startBuf+1,
Chris Lattner9cc55f52008-01-31 19:51:04 +0000777 typedefString.c_str(), typedefString.size());
Chris Lattner3c799d72007-10-24 17:06:59 +0000778}
779
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000780void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
Steve Naroff3ce37a62007-12-14 23:37:57 +0000781 SourceLocation LocStart = Method->getLocStart();
782 SourceLocation LocEnd = Method->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +0000783
Chris Lattner88ea93e2009-02-04 01:06:56 +0000784 if (SM->getInstantiationLineNumber(LocEnd) >
785 SM->getInstantiationLineNumber(LocStart)) {
Steve Naroffe020fa12008-10-21 13:37:27 +0000786 InsertText(LocStart, "#if 0\n", 6);
787 ReplaceText(LocEnd, 1, ";\n#endif\n", 9);
Steve Naroff3ce37a62007-12-14 23:37:57 +0000788 } else {
Chris Lattner1780a852008-01-31 19:42:41 +0000789 InsertText(LocStart, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000790 }
791}
792
Mike Stump11289f42009-09-09 15:08:12 +0000793void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000794 SourceLocation Loc = prop->getLocation();
Mike Stump11289f42009-09-09 15:08:12 +0000795
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000796 ReplaceText(Loc, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000797
Steve Naroff0c0f5ba2009-01-11 01:06:09 +0000798 // FIXME: handle properties that are declared across multiple lines.
Fariborz Jahaniane8a30162007-11-07 00:09:37 +0000799}
800
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000801void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
Steve Naroff5448cf62007-10-30 13:30:57 +0000802 SourceLocation LocStart = CatDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000803
Steve Naroff5448cf62007-10-30 13:30:57 +0000804 // FIXME: handle category headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000805 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000806
807 for (ObjCCategoryDecl::instmeth_iterator
808 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000809 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000810 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +0000811 for (ObjCCategoryDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000812 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000813 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000814 RewriteMethodDeclaration(*I);
815
Steve Naroff5448cf62007-10-30 13:30:57 +0000816 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000817 ReplaceText(CatDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff5448cf62007-10-30 13:30:57 +0000818}
819
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000820void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000821 std::pair<const char*, const char*> MainBuf = SM->getBufferData(MainFileID);
Mike Stump11289f42009-09-09 15:08:12 +0000822
Steve Narofff921385f2007-10-30 16:42:30 +0000823 SourceLocation LocStart = PDecl->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +0000824
Steve Narofff921385f2007-10-30 16:42:30 +0000825 // FIXME: handle protocol headers that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000826 ReplaceText(LocStart, 0, "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000827
828 for (ObjCProtocolDecl::instmeth_iterator
829 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000830 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000831 RewriteMethodDeclaration(*I);
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000832 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +0000833 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +0000834 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +0000835 RewriteMethodDeclaration(*I);
836
Steve Narofff921385f2007-10-30 16:42:30 +0000837 // Lastly, comment out the @end.
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000838 SourceLocation LocEnd = PDecl->getAtEndLoc();
Chris Lattner9cc55f52008-01-31 19:51:04 +0000839 ReplaceText(LocEnd, 0, "// ", 3);
Steve Naroffa509f042007-11-14 15:03:57 +0000840
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000841 // Must comment out @optional/@required
842 const char *startBuf = SM->getCharacterData(LocStart);
843 const char *endBuf = SM->getCharacterData(LocEnd);
844 for (const char *p = startBuf; p < endBuf; p++) {
845 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
846 std::string CommentedOptional = "/* @optional */";
Steve Naroffa509f042007-11-14 15:03:57 +0000847 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000848 ReplaceText(OptionalLoc, strlen("@optional"),
849 CommentedOptional.c_str(), CommentedOptional.size());
Mike Stump11289f42009-09-09 15:08:12 +0000850
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000851 }
852 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
853 std::string CommentedRequired = "/* @required */";
Steve Naroffa509f042007-11-14 15:03:57 +0000854 SourceLocation OptionalLoc = LocStart.getFileLocWithOffset(p-startBuf);
Chris Lattner9cc55f52008-01-31 19:51:04 +0000855 ReplaceText(OptionalLoc, strlen("@required"),
856 CommentedRequired.c_str(), CommentedRequired.size());
Mike Stump11289f42009-09-09 15:08:12 +0000857
Fariborz Jahanianfe38ba22007-11-14 01:37:46 +0000858 }
859 }
Steve Narofff921385f2007-10-30 16:42:30 +0000860}
861
Steve Naroff1dc53ef2008-04-14 22:03:09 +0000862void RewriteObjC::RewriteForwardProtocolDecl(ObjCForwardProtocolDecl *PDecl) {
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000863 SourceLocation LocStart = PDecl->getLocation();
Steve Naroffc17b0562007-11-14 03:37:28 +0000864 if (LocStart.isInvalid())
865 assert(false && "Invalid SourceLocation");
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000866 // FIXME: handle forward protocol that are declared across multiple lines.
Chris Lattner9cc55f52008-01-31 19:51:04 +0000867 ReplaceText(LocStart, 0, "// ", 3);
Fariborz Jahanianda6165c2007-11-14 00:42:16 +0000868}
869
Mike Stump11289f42009-09-09 15:08:12 +0000870void RewriteObjC::RewriteObjCMethodDecl(ObjCMethodDecl *OMD,
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000871 std::string &ResultStr) {
Steve Naroff295570a2008-10-30 12:09:33 +0000872 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
Steve Naroffb067bbd2008-07-16 14:40:40 +0000873 const FunctionType *FPRetType = 0;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000874 ResultStr += "\nstatic ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000875 if (OMD->getResultType()->isObjCQualifiedIdType())
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000876 ResultStr += "id";
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000877 else if (OMD->getResultType()->isFunctionPointerType() ||
878 OMD->getResultType()->isBlockPointerType()) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000879 // needs special handling, since pointer-to-functions have special
880 // syntax (where a decaration models use).
881 QualType retType = OMD->getResultType();
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000882 QualType PointeeTy;
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000883 if (const PointerType* PT = retType->getAs<PointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000884 PointeeTy = PT->getPointeeType();
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000885 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000886 PointeeTy = BPT->getPointeeType();
John McCall9dd450b2009-09-21 23:43:11 +0000887 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Steve Naroff1fa7bd12008-12-11 19:29:16 +0000888 ResultStr += FPRetType->getResultType().getAsString();
889 ResultStr += "(*";
Steve Naroffb067bbd2008-07-16 14:40:40 +0000890 }
891 } else
Fariborz Jahanian24cb52c2007-12-17 21:03:50 +0000892 ResultStr += OMD->getResultType().getAsString();
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000893 ResultStr += " ";
Mike Stump11289f42009-09-09 15:08:12 +0000894
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000895 // Unique method name
Fariborz Jahanian56338352007-11-13 21:02:00 +0000896 std::string NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000897
Douglas Gregorffca3a22009-01-09 17:18:27 +0000898 if (OMD->isInstanceMethod())
Fariborz Jahanian56338352007-11-13 21:02:00 +0000899 NameStr += "_I_";
900 else
901 NameStr += "_C_";
Mike Stump11289f42009-09-09 15:08:12 +0000902
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000903 NameStr += OMD->getClassInterface()->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000904 NameStr += "_";
Mike Stump11289f42009-09-09 15:08:12 +0000905
906 if (ObjCCategoryImplDecl *CID =
Steve Naroff11b387f2009-01-08 19:41:02 +0000907 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000908 NameStr += CID->getNameAsString();
Fariborz Jahanian56338352007-11-13 21:02:00 +0000909 NameStr += "_";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000910 }
Mike Stump11289f42009-09-09 15:08:12 +0000911 // Append selector names, replacing ':' with '_'
Chris Lattnere4b95692008-11-24 03:33:13 +0000912 {
913 std::string selString = OMD->getSelector().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000914 int len = selString.size();
915 for (int i = 0; i < len; i++)
916 if (selString[i] == ':')
917 selString[i] = '_';
Fariborz Jahanian56338352007-11-13 21:02:00 +0000918 NameStr += selString;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000919 }
Fariborz Jahanian56338352007-11-13 21:02:00 +0000920 // Remember this name for metadata emission
921 MethodInternalNames[OMD] = NameStr;
922 ResultStr += NameStr;
Mike Stump11289f42009-09-09 15:08:12 +0000923
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000924 // Rewrite arguments
925 ResultStr += "(";
Mike Stump11289f42009-09-09 15:08:12 +0000926
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000927 // invisible arguments
Douglas Gregorffca3a22009-01-09 17:18:27 +0000928 if (OMD->isInstanceMethod()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000929 QualType selfTy = Context->getObjCInterfaceType(OMD->getClassInterface());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000930 selfTy = Context->getPointerType(selfTy);
Steve Naroffdc5b6b22008-03-12 00:25:36 +0000931 if (!LangOpts.Microsoft) {
932 if (ObjCSynthesizedStructs.count(OMD->getClassInterface()))
933 ResultStr += "struct ";
934 }
935 // When rewriting for Microsoft, explicitly omit the structure name.
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000936 ResultStr += OMD->getClassInterface()->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +0000937 ResultStr += " *";
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000938 }
939 else
Steve Naroffd9803712009-04-29 16:37:50 +0000940 ResultStr += Context->getObjCClassType().getAsString();
Mike Stump11289f42009-09-09 15:08:12 +0000941
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000942 ResultStr += " self, ";
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000943 ResultStr += Context->getObjCSelType().getAsString();
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000944 ResultStr += " _cmd";
Mike Stump11289f42009-09-09 15:08:12 +0000945
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000946 // Method arguments.
Chris Lattnera4997152009-02-20 18:43:26 +0000947 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
948 E = OMD->param_end(); PI != E; ++PI) {
949 ParmVarDecl *PDecl = *PI;
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000950 ResultStr += ", ";
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000951 if (PDecl->getType()->isObjCQualifiedIdType()) {
952 ResultStr += "id ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000953 ResultStr += PDecl->getNameAsString();
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000954 } else {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +0000955 std::string Name = PDecl->getNameAsString();
Steve Naroffa5c0db82008-12-11 21:05:33 +0000956 if (isTopLevelBlockPointerType(PDecl->getType())) {
Steve Naroff44df6a22008-10-30 14:45:29 +0000957 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Ted Kremenekc23c7e62009-07-29 21:53:49 +0000958 const BlockPointerType *BPT = PDecl->getType()->getAs<BlockPointerType>();
Douglas Gregor7de59662009-05-29 20:38:28 +0000959 Context->getPointerType(BPT->getPointeeType()).getAsStringInternal(Name,
960 Context->PrintingPolicy);
Steve Naroff44df6a22008-10-30 14:45:29 +0000961 } else
Douglas Gregor7de59662009-05-29 20:38:28 +0000962 PDecl->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Steve Naroffdcdcdcd2008-04-18 21:13:19 +0000963 ResultStr += Name;
964 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000965 }
Fariborz Jahanianeab81cd2008-01-21 20:14:23 +0000966 if (OMD->isVariadic())
967 ResultStr += ", ...";
Fariborz Jahanian7262fca2008-01-10 01:39:52 +0000968 ResultStr += ") ";
Mike Stump11289f42009-09-09 15:08:12 +0000969
Steve Naroffb067bbd2008-07-16 14:40:40 +0000970 if (FPRetType) {
971 ResultStr += ")"; // close the precedence "scope" for "*".
Mike Stump11289f42009-09-09 15:08:12 +0000972
Steve Naroffb067bbd2008-07-16 14:40:40 +0000973 // Now, emit the argument types (if any).
Douglas Gregordeaad8c2009-02-26 23:50:07 +0000974 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
Steve Naroffb067bbd2008-07-16 14:40:40 +0000975 ResultStr += "(";
976 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
977 if (i) ResultStr += ", ";
978 std::string ParamStr = FT->getArgType(i).getAsString();
979 ResultStr += ParamStr;
980 }
981 if (FT->isVariadic()) {
982 if (FT->getNumArgs()) ResultStr += ", ";
983 ResultStr += "...";
984 }
985 ResultStr += ")";
986 } else {
987 ResultStr += "()";
988 }
989 }
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +0000990}
Douglas Gregor6e6ad602009-01-20 01:17:11 +0000991void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +0000992 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
993 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
Mike Stump11289f42009-09-09 15:08:12 +0000994
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000995 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +0000996 InsertText(IMD->getLocStart(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +0000997 else
Chris Lattner1780a852008-01-31 19:42:41 +0000998 InsertText(CID->getLocStart(), "// ", 3);
Mike Stump11289f42009-09-09 15:08:12 +0000999
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001000 for (ObjCCategoryImplDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001001 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1002 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001003 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001004 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001005 ObjCMethodDecl *OMD = *I;
1006 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001007 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001008 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Sebastian Redla7b98a72009-04-26 20:35:05 +00001009
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001010 const char *startBuf = SM->getCharacterData(LocStart);
1011 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001012 ReplaceText(LocStart, endBuf-startBuf,
1013 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001014 }
Mike Stump11289f42009-09-09 15:08:12 +00001015
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001016 for (ObjCCategoryImplDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001017 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1018 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001019 I != E; ++I) {
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001020 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001021 ObjCMethodDecl *OMD = *I;
1022 RewriteObjCMethodDecl(OMD, ResultStr);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001023 SourceLocation LocStart = OMD->getLocStart();
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00001024 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
Mike Stump11289f42009-09-09 15:08:12 +00001025
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001026 const char *startBuf = SM->getCharacterData(LocStart);
1027 const char *endBuf = SM->getCharacterData(LocEnd);
Chris Lattner9cc55f52008-01-31 19:51:04 +00001028 ReplaceText(LocStart, endBuf-startBuf,
Mike Stump11289f42009-09-09 15:08:12 +00001029 ResultStr.c_str(), ResultStr.size());
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001030 }
Steve Naroffe1908e32008-12-01 20:33:01 +00001031 for (ObjCCategoryImplDecl::propimpl_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001032 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
Mike Stump11289f42009-09-09 15:08:12 +00001033 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00001034 I != E; ++I) {
Steve Naroffc038b3a2008-12-02 17:36:43 +00001035 RewritePropertyImplDecl(*I, IMD, CID);
Steve Naroffe1908e32008-12-01 20:33:01 +00001036 }
1037
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001038 if (IMD)
Chris Lattner1780a852008-01-31 19:42:41 +00001039 InsertText(IMD->getLocEnd(), "// ", 3);
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00001040 else
Mike Stump11289f42009-09-09 15:08:12 +00001041 InsertText(CID->getLocEnd(), "// ", 3);
Fariborz Jahanian1e5f64e2007-11-13 18:44:14 +00001042}
1043
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001044void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Steve Naroffc5484042007-10-30 02:23:23 +00001045 std::string ResultStr;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001046 if (!ObjCForwardDecls.count(ClassDecl)) {
Steve Naroff2f55b982007-11-01 03:35:41 +00001047 // we haven't seen a forward decl - generate a typedef.
Steve Naroff03f27672007-11-14 23:02:56 +00001048 ResultStr = "#ifndef _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001049 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001050 ResultStr += "\n";
1051 ResultStr += "#define _REWRITER_typedef_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001052 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001053 ResultStr += "\n";
Steve Naroffa1e115e2008-03-10 23:16:54 +00001054 ResultStr += "typedef struct objc_object ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001055 ResultStr += ClassDecl->getNameAsString();
Steve Naroff1b232132007-11-09 12:50:28 +00001056 ResultStr += ";\n#endif\n";
Steve Naroff2f55b982007-11-01 03:35:41 +00001057 // Mark this typedef as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001058 ObjCForwardDecls.insert(ClassDecl);
Steve Naroff2f55b982007-11-01 03:35:41 +00001059 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001060 SynthesizeObjCInternalStruct(ClassDecl, ResultStr);
Mike Stump11289f42009-09-09 15:08:12 +00001061
1062 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001063 E = ClassDecl->prop_end(); I != E; ++I)
Steve Naroff0c0f5ba2009-01-11 01:06:09 +00001064 RewriteProperty(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001065 for (ObjCInterfaceDecl::instmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00001066 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001067 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001068 RewriteMethodDeclaration(*I);
Mike Stump11289f42009-09-09 15:08:12 +00001069 for (ObjCInterfaceDecl::classmeth_iterator
1070 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001071 I != E; ++I)
Steve Naroff3ce37a62007-12-14 23:37:57 +00001072 RewriteMethodDeclaration(*I);
1073
Steve Naroff4cd61ac2007-10-30 03:43:13 +00001074 // Lastly, comment out the @end.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001075 ReplaceText(ClassDecl->getAtEndLoc(), 0, "// ", 3);
Steve Naroff161a92b2007-10-26 20:53:56 +00001076}
1077
Steve Naroff08628db2008-12-09 12:56:34 +00001078Stmt *RewriteObjC::RewritePropertySetter(BinaryOperator *BinOp, Expr *newStmt,
1079 SourceRange SrcRange) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00001080 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1081 // This allows us to reuse all the fun and games in SynthMessageExpr().
1082 ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS());
1083 ObjCMessageExpr *MsgExpr;
1084 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
1085 llvm::SmallVector<Expr *, 1> ExprVec;
1086 ExprVec.push_back(newStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001087
Steve Naroff1042ff32008-12-08 16:43:47 +00001088 Stmt *Receiver = PropRefExpr->getBase();
1089 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1090 if (PRE && PropGetters[PRE]) {
1091 // This allows us to handle chain/nested property getters.
1092 Receiver = PropGetters[PRE];
1093 }
Mike Stump11289f42009-09-09 15:08:12 +00001094 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1095 PDecl->getSetterName(), PDecl->getType(),
1096 PDecl->getSetterMethodDecl(),
1097 SourceLocation(), SourceLocation(),
Steve Naroff4588d0f2008-12-04 16:24:46 +00001098 &ExprVec[0], 1);
1099 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001100
Steve Naroff4588d0f2008-12-04 16:24:46 +00001101 // Now do the actual rewrite.
Steve Naroff08628db2008-12-09 12:56:34 +00001102 ReplaceStmtWithRange(BinOp, ReplacingStmt, SrcRange);
Steve Naroffdf705772008-12-10 14:53:27 +00001103 //delete BinOp;
Ted Kremenek5a201952009-02-07 01:47:29 +00001104 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1105 // to things that stay around.
1106 Context->Deallocate(MsgExpr);
Steve Naroff4588d0f2008-12-04 16:24:46 +00001107 return ReplacingStmt;
Steve Narofff326f402008-12-03 00:56:33 +00001108}
1109
Steve Naroff4588d0f2008-12-04 16:24:46 +00001110Stmt *RewriteObjC::RewritePropertyGetter(ObjCPropertyRefExpr *PropRefExpr) {
Steve Narofff326f402008-12-03 00:56:33 +00001111 // Synthesize a ObjCMessageExpr from a ObjCPropertyRefExpr.
1112 // This allows us to reuse all the fun and games in SynthMessageExpr().
1113 ObjCMessageExpr *MsgExpr;
1114 ObjCPropertyDecl *PDecl = PropRefExpr->getProperty();
Mike Stump11289f42009-09-09 15:08:12 +00001115
Steve Naroff1042ff32008-12-08 16:43:47 +00001116 Stmt *Receiver = PropRefExpr->getBase();
Mike Stump11289f42009-09-09 15:08:12 +00001117
Steve Naroff1042ff32008-12-08 16:43:47 +00001118 ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(Receiver);
1119 if (PRE && PropGetters[PRE]) {
1120 // This allows us to handle chain/nested property getters.
1121 Receiver = PropGetters[PRE];
1122 }
Mike Stump11289f42009-09-09 15:08:12 +00001123 MsgExpr = new (Context) ObjCMessageExpr(dyn_cast<Expr>(Receiver),
1124 PDecl->getGetterName(), PDecl->getType(),
1125 PDecl->getGetterMethodDecl(),
1126 SourceLocation(), SourceLocation(),
Steve Narofff326f402008-12-03 00:56:33 +00001127 0, 0);
1128
Steve Naroff22216db2008-12-04 23:50:32 +00001129 Stmt *ReplacingStmt = SynthMessageExpr(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001130
1131 if (!PropParentMap)
1132 PropParentMap = new ParentMap(CurrentBody);
1133
1134 Stmt *Parent = PropParentMap->getParent(PropRefExpr);
1135 if (Parent && isa<ObjCPropertyRefExpr>(Parent)) {
1136 // We stash away the ReplacingStmt since actually doing the
1137 // replacement/rewrite won't work for nested getters (e.g. obj.p.i)
1138 PropGetters[PropRefExpr] = ReplacingStmt;
Ted Kremenek5a201952009-02-07 01:47:29 +00001139 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1140 // to things that stay around.
1141 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001142 return PropRefExpr; // return the original...
1143 } else {
1144 ReplaceStmt(PropRefExpr, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00001145 // delete PropRefExpr; elsewhere...
Ted Kremenek5a201952009-02-07 01:47:29 +00001146 // NOTE: We don't want to call MsgExpr->Destroy(), as it holds references
1147 // to things that stay around.
1148 Context->Deallocate(MsgExpr);
Steve Naroff1042ff32008-12-08 16:43:47 +00001149 return ReplacingStmt;
1150 }
Steve Narofff326f402008-12-03 00:56:33 +00001151}
1152
Mike Stump11289f42009-09-09 15:08:12 +00001153Stmt *RewriteObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV,
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001154 SourceLocation OrigStart) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001155 ObjCIvarDecl *D = IV->getDecl();
Steve Naroff677ab3a2008-10-27 17:20:55 +00001156 if (CurMethodDef) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001157 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001158 ObjCInterfaceType *iFaceDecl =
1159 dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001160 // lookup which class implements the instance variable.
1161 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001162 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001163 clsDeclared);
Steve Naroffb1c02372008-05-08 17:52:16 +00001164 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001165
Steve Naroffb1c02372008-05-08 17:52:16 +00001166 // Synthesize an explicit cast to gain access to the ivar.
1167 std::string RecName = clsDeclared->getIdentifier()->getName();
1168 RecName += "_IMPL";
1169 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001170 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001171 SourceLocation(), II);
Steve Naroffb1c02372008-05-08 17:52:16 +00001172 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1173 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001174 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001175 CastExpr::CK_Unknown,
1176 IV->getBase(),
1177 castT,SourceLocation(),
1178 SourceLocation());
Steve Naroffb1c02372008-05-08 17:52:16 +00001179 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001180 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
1181 IV->getBase()->getLocEnd(),
1182 castExpr);
Mike Stump11289f42009-09-09 15:08:12 +00001183 if (IV->isFreeIvar() &&
Steve Naroff677ab3a2008-10-27 17:20:55 +00001184 CurMethodDef->getClassInterface() == iFaceDecl->getDecl()) {
Ted Kremenek5a201952009-02-07 01:47:29 +00001185 MemberExpr *ME = new (Context) MemberExpr(PE, true, D,
1186 IV->getLocation(),
1187 D->getType());
Steve Naroffb1c02372008-05-08 17:52:16 +00001188 ReplaceStmt(IV, ME);
Steve Naroff22216db2008-12-04 23:50:32 +00001189 // delete IV; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffb1c02372008-05-08 17:52:16 +00001190 return ME;
Steve Naroff05caa482007-11-15 11:33:00 +00001191 }
Mike Stump11289f42009-09-09 15:08:12 +00001192
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001193 ReplaceStmt(IV->getBase(), PE);
1194 // Cannot delete IV->getBase(), since PE points to it.
1195 // Replace the old base with the cast. This is important when doing
1196 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001197 IV->setBase(PE);
Chris Lattner37f5b7d2008-05-23 20:40:52 +00001198 return IV;
Steve Naroff05caa482007-11-15 11:33:00 +00001199 }
Steve Naroff24840f62008-04-18 21:55:08 +00001200 } else { // we are outside a method.
Steve Naroff29ce4e52008-05-06 23:20:07 +00001201 assert(!IV->isFreeIvar() && "Cannot have a free standing ivar outside a method");
Mike Stump11289f42009-09-09 15:08:12 +00001202
Steve Naroff29ce4e52008-05-06 23:20:07 +00001203 // Explicit ivar refs need to have a cast inserted.
1204 // FIXME: consider sharing some of this code with the code above.
Ted Kremenekc23c7e62009-07-29 21:53:49 +00001205 if (const PointerType *pType = IV->getBase()->getType()->getAs<PointerType>()) {
Steve Naroffb1c02372008-05-08 17:52:16 +00001206 ObjCInterfaceType *iFaceDecl = dyn_cast<ObjCInterfaceType>(pType->getPointeeType());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001207 // lookup which class implements the instance variable.
1208 ObjCInterfaceDecl *clsDeclared = 0;
Mike Stump11289f42009-09-09 15:08:12 +00001209 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
Douglas Gregorbcced4e2009-04-09 21:40:53 +00001210 clsDeclared);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001211 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
Mike Stump11289f42009-09-09 15:08:12 +00001212
Steve Naroff29ce4e52008-05-06 23:20:07 +00001213 // Synthesize an explicit cast to gain access to the ivar.
1214 std::string RecName = clsDeclared->getIdentifier()->getName();
1215 RecName += "_IMPL";
1216 IdentifierInfo *II = &Context->Idents.get(RecName.c_str());
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00001217 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Ted Kremenek47923c72008-09-05 01:34:33 +00001218 SourceLocation(), II);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001219 assert(RD && "RewriteObjCIvarRefExpr(): Can't find RecordDecl");
1220 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
Mike Stump11289f42009-09-09 15:08:12 +00001221 CastExpr *castExpr = new (Context) CStyleCastExpr(castT,
Anders Carlssona2615922009-07-31 00:48:10 +00001222 CastExpr::CK_Unknown,
1223 IV->getBase(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001224 castT, SourceLocation(),
1225 SourceLocation());
Steve Naroff29ce4e52008-05-06 23:20:07 +00001226 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00001227 ParenExpr *PE = new (Context) ParenExpr(IV->getBase()->getLocStart(),
Chris Lattner34873d22008-05-28 16:38:23 +00001228 IV->getBase()->getLocEnd(), castExpr);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001229 ReplaceStmt(IV->getBase(), PE);
1230 // Cannot delete IV->getBase(), since PE points to it.
1231 // Replace the old base with the cast. This is important when doing
1232 // embedded rewrites. For example, [newInv->_container addObject:0].
Mike Stump11289f42009-09-09 15:08:12 +00001233 IV->setBase(PE);
Steve Naroff29ce4e52008-05-06 23:20:07 +00001234 return IV;
1235 }
Steve Naroff05caa482007-11-15 11:33:00 +00001236 }
Steve Naroff24840f62008-04-18 21:55:08 +00001237 return IV;
Steve Narofff60782b2007-11-15 02:58:25 +00001238}
1239
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001240/// SynthCountByEnumWithState - To print:
1241/// ((unsigned int (*)
1242/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001243/// (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001244/// sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001245/// "countByEnumeratingWithState:objects:count:"),
1246/// &enumState,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001247/// (id *)items, (unsigned int)16)
1248///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001249void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001250 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1251 "id *, unsigned int))(void *)objc_msgSend)";
1252 buf += "\n\t\t";
1253 buf += "((id)l_collection,\n\t\t";
1254 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1255 buf += "\n\t\t";
1256 buf += "&enumState, "
1257 "(id *)items, (unsigned int)16)";
1258}
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001259
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001260/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1261/// statement to exit to its outer synthesized loop.
1262///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001263Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001264 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1265 return S;
1266 // replace break with goto __break_label
1267 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001268
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001269 SourceLocation startLoc = S->getLocStart();
1270 buf = "goto __break_label_";
1271 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001272 ReplaceText(startLoc, strlen("break"), buf.c_str(), buf.size());
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001273
1274 return 0;
1275}
1276
1277/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1278/// statement to continue with its inner synthesized loop.
1279///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001280Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001281 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1282 return S;
1283 // replace continue with goto __continue_label
1284 std::string buf;
Mike Stump11289f42009-09-09 15:08:12 +00001285
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001286 SourceLocation startLoc = S->getLocStart();
1287 buf = "goto __continue_label_";
1288 buf += utostr(ObjCBcLabelNo.back());
Chris Lattner9cc55f52008-01-31 19:51:04 +00001289 ReplaceText(startLoc, strlen("continue"), buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001290
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001291 return 0;
1292}
1293
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001294/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001295/// It rewrites:
1296/// for ( type elem in collection) { stmts; }
Mike Stump11289f42009-09-09 15:08:12 +00001297
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001298/// Into:
1299/// {
Mike Stump11289f42009-09-09 15:08:12 +00001300/// type elem;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001301/// struct __objcFastEnumerationState enumState = { 0 };
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001302/// id items[16];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001303/// id l_collection = (id)collection;
Mike Stump11289f42009-09-09 15:08:12 +00001304/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001305/// objects:items count:16];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001306/// if (limit) {
1307/// unsigned long startMutations = *enumState.mutationsPtr;
1308/// do {
1309/// unsigned long counter = 0;
1310/// do {
Mike Stump11289f42009-09-09 15:08:12 +00001311/// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001312/// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001313/// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001314/// stmts;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001315/// __continue_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001316/// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001317/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001318/// objects:items count:16]);
1319/// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001320/// __break_label: ;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001321/// }
1322/// else
1323/// elem = nil;
1324/// }
1325///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001326Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
Chris Lattnera779d692008-01-31 05:10:40 +00001327 SourceLocation OrigEnd) {
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001328 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001329 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001330 "ObjCForCollectionStmt Statement stack mismatch");
Mike Stump11289f42009-09-09 15:08:12 +00001331 assert(!ObjCBcLabelNo.empty() &&
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001332 "ObjCForCollectionStmt - Label No stack empty");
Mike Stump11289f42009-09-09 15:08:12 +00001333
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001334 SourceLocation startLoc = S->getLocStart();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001335 const char *startBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001336 const char *elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001337 std::string elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001338 std::string buf;
1339 buf = "\n{\n\t";
1340 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1341 // type elem;
Chris Lattner529efc72009-03-28 06:33:19 +00001342 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
Ted Kremenek292b3842008-10-06 22:16:13 +00001343 QualType ElementType = cast<ValueDecl>(D)->getType();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001344 if (ElementType->isObjCQualifiedIdType() ||
1345 ElementType->isObjCQualifiedInterfaceType())
1346 // Simply use 'id' for all qualified types.
1347 elementTypeAsString = "id";
1348 else
1349 elementTypeAsString = ElementType.getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001350 buf += elementTypeAsString;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001351 buf += " ";
Chris Lattner86d7d912008-11-24 03:54:41 +00001352 elementName = D->getNameAsCString();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001353 buf += elementName;
1354 buf += ";\n\t";
1355 }
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001356 else {
1357 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
Chris Lattner86d7d912008-11-24 03:54:41 +00001358 elementName = DR->getDecl()->getNameAsCString();
Steve Naroff3ce3af22009-12-04 21:18:19 +00001359 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1360 if (VD->getType()->isObjCQualifiedIdType() ||
1361 VD->getType()->isObjCQualifiedInterfaceType())
1362 // Simply use 'id' for all qualified types.
1363 elementTypeAsString = "id";
1364 else
1365 elementTypeAsString = VD->getType().getAsString();
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001366 }
Mike Stump11289f42009-09-09 15:08:12 +00001367
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001368 // struct __objcFastEnumerationState enumState = { 0 };
1369 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1370 // id items[16];
1371 buf += "id items[16];\n\t";
1372 // id l_collection = (id)
1373 buf += "id l_collection = (id)";
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001374 // Find start location of 'collection' the hard way!
1375 const char *startCollectionBuf = startBuf;
1376 startCollectionBuf += 3; // skip 'for'
1377 startCollectionBuf = strchr(startCollectionBuf, '(');
1378 startCollectionBuf++; // skip '('
1379 // find 'in' and skip it.
1380 while (*startCollectionBuf != ' ' ||
1381 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1382 (*(startCollectionBuf+3) != ' ' &&
1383 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1384 startCollectionBuf++;
1385 startCollectionBuf += 3;
Mike Stump11289f42009-09-09 15:08:12 +00001386
1387 // Replace: "for (type element in" with string constructed thus far.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001388 ReplaceText(startLoc, startCollectionBuf - startBuf,
1389 buf.c_str(), buf.size());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001390 // Replace ')' in for '(' type elem in collection ')' with ';'
Fariborz Jahanian82ae0152008-01-10 00:24:29 +00001391 SourceLocation rightParenLoc = S->getRParenLoc();
1392 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1393 SourceLocation lparenLoc = startLoc.getFileLocWithOffset(rparenBuf-startBuf);
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001394 buf = ";\n\t";
Mike Stump11289f42009-09-09 15:08:12 +00001395
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001396 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1397 // objects:items count:16];
1398 // which is synthesized into:
Mike Stump11289f42009-09-09 15:08:12 +00001399 // unsigned int limit =
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001400 // ((unsigned int (*)
1401 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
Mike Stump11289f42009-09-09 15:08:12 +00001402 // (void *)objc_msgSend)((id)l_collection,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001403 // sel_registerName(
Mike Stump11289f42009-09-09 15:08:12 +00001404 // "countByEnumeratingWithState:objects:count:"),
1405 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001406 // (id *)items, (unsigned int)16);
1407 buf += "unsigned long limit =\n\t\t";
1408 SynthCountByEnumWithState(buf);
1409 buf += ";\n\t";
1410 /// if (limit) {
1411 /// unsigned long startMutations = *enumState.mutationsPtr;
1412 /// do {
1413 /// unsigned long counter = 0;
1414 /// do {
Mike Stump11289f42009-09-09 15:08:12 +00001415 /// if (startMutations != *enumState.mutationsPtr)
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001416 /// objc_enumerationMutation(l_collection);
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001417 /// elem = (type)enumState.itemsPtr[counter++];
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001418 buf += "if (limit) {\n\t";
1419 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1420 buf += "do {\n\t\t";
1421 buf += "unsigned long counter = 0;\n\t\t";
1422 buf += "do {\n\t\t\t";
1423 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1424 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1425 buf += elementName;
Fariborz Jahanian6fa75162008-01-09 18:15:42 +00001426 buf += " = (";
1427 buf += elementTypeAsString;
1428 buf += ")enumState.itemsPtr[counter++];";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001429 // Replace ')' in for '(' type elem in collection ')' with all of these.
Chris Lattner9cc55f52008-01-31 19:51:04 +00001430 ReplaceText(lparenLoc, 1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001431
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001432 /// __continue_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001433 /// } while (counter < limit);
Mike Stump11289f42009-09-09 15:08:12 +00001434 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001435 /// objects:items count:16]);
1436 /// elem = nil;
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001437 /// __break_label: ;
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001438 /// }
1439 /// else
1440 /// elem = nil;
1441 /// }
Mike Stump11289f42009-09-09 15:08:12 +00001442 ///
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001443 buf = ";\n\t";
1444 buf += "__continue_label_";
1445 buf += utostr(ObjCBcLabelNo.back());
1446 buf += ": ;";
1447 buf += "\n\t\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001448 buf += "} while (counter < limit);\n\t";
1449 buf += "} while (limit = ";
1450 SynthCountByEnumWithState(buf);
1451 buf += ");\n\t";
1452 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001453 buf += " = ((id)0);\n\t";
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001454 buf += "__break_label_";
1455 buf += utostr(ObjCBcLabelNo.back());
1456 buf += ": ;\n\t";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001457 buf += "}\n\t";
1458 buf += "else\n\t\t";
1459 buf += elementName;
Steve Naroffd1a36792008-12-17 14:24:39 +00001460 buf += " = ((id)0);\n";
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001461 buf += "}\n";
Mike Stump11289f42009-09-09 15:08:12 +00001462
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001463 // Insert all these *after* the statement body.
Sebastian Redla7b98a72009-04-26 20:35:05 +00001464 // FIXME: If this should support Obj-C++, support CXXTryStmt
Steve Narofff0ff8792008-07-21 18:26:02 +00001465 if (isa<CompoundStmt>(S->getBody())) {
1466 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(1);
1467 InsertText(endBodyLoc, buf.c_str(), buf.size());
1468 } else {
1469 /* Need to treat single statements specially. For example:
1470 *
1471 * for (A *a in b) if (stuff()) break;
1472 * for (A *a in b) xxxyy;
1473 *
1474 * The following code simply scans ahead to the semi to find the actual end.
1475 */
1476 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1477 const char *semiBuf = strchr(stmtBuf, ';');
1478 assert(semiBuf && "Can't find ';'");
1479 SourceLocation endBodyLoc = OrigEnd.getFileLocWithOffset(semiBuf-stmtBuf+1);
1480 InsertText(endBodyLoc, buf.c_str(), buf.size());
1481 }
Fariborz Jahanianb860cbf2008-01-15 23:58:23 +00001482 Stmts.pop_back();
1483 ObjCBcLabelNo.pop_back();
Fariborz Jahanian965a8962008-01-08 22:06:28 +00001484 return 0;
Fariborz Jahaniandc917b92008-01-07 21:40:22 +00001485}
1486
Mike Stump11289f42009-09-09 15:08:12 +00001487/// RewriteObjCSynchronizedStmt -
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001488/// This routine rewrites @synchronized(expr) stmt;
1489/// into:
1490/// objc_sync_enter(expr);
1491/// @try stmt @finally { objc_sync_exit(expr); }
1492///
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001493Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001494 // Get the start location and compute the semi location.
1495 SourceLocation startLoc = S->getLocStart();
1496 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001497
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001498 assert((*startBuf == '@') && "bogus @synchronized location");
Mike Stump11289f42009-09-09 15:08:12 +00001499
1500 std::string buf;
Steve Naroffb2fc0522008-08-21 13:03:03 +00001501 buf = "objc_sync_enter((id)";
1502 const char *lparenBuf = startBuf;
1503 while (*lparenBuf != '(') lparenBuf++;
1504 ReplaceText(startLoc, lparenBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001505 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1506 // the sync expression is typically a message expression that's already
Steve Naroffad7013b2008-08-19 13:04:19 +00001507 // been rewritten! (which implies the SourceLocation's are invalid).
1508 SourceLocation endLoc = S->getSynchBody()->getLocStart();
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001509 const char *endBuf = SM->getCharacterData(endLoc);
Steve Naroffad7013b2008-08-19 13:04:19 +00001510 while (*endBuf != ')') endBuf--;
1511 SourceLocation rparenLoc = startLoc.getFileLocWithOffset(endBuf-startBuf);
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001512 buf = ");\n";
1513 // declare a new scope with two variables, _stack and _rethrow.
1514 buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1515 buf += "int buf[18/*32-bit i386*/];\n";
1516 buf += "char *pointers[4];} _stack;\n";
1517 buf += "id volatile _rethrow = 0;\n";
1518 buf += "objc_exception_try_enter(&_stack);\n";
1519 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001520 ReplaceText(rparenLoc, 1, buf.c_str(), buf.size());
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001521 startLoc = S->getSynchBody()->getLocEnd();
1522 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001523
Steve Naroffad7013b2008-08-19 13:04:19 +00001524 assert((*startBuf == '}') && "bogus @synchronized block");
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001525 SourceLocation lastCurlyLoc = startLoc;
1526 buf = "}\nelse {\n";
1527 buf += " _rethrow = objc_exception_extract(&_stack);\n";
Steve Naroffd9803712009-04-29 16:37:50 +00001528 buf += "}\n";
1529 buf += "{ /* implicit finally clause */\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001530 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Steve Naroffec60b432009-12-05 21:43:12 +00001531
1532 std::string syncBuf;
1533 syncBuf += " objc_sync_exit(";
Mike Stump11289f42009-09-09 15:08:12 +00001534 Expr *syncExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00001535 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001536 S->getSynchExpr(),
Ted Kremenek5a201952009-02-07 01:47:29 +00001537 Context->getObjCIdType(),
1538 SourceLocation(),
1539 SourceLocation());
Ted Kremenek2d470fc2008-09-13 05:16:45 +00001540 std::string syncExprBufS;
1541 llvm::raw_string_ostream syncExprBuf(syncExprBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00001542 syncExpr->printPretty(syncExprBuf, *Context, 0,
1543 PrintingPolicy(LangOpts));
Steve Naroffec60b432009-12-05 21:43:12 +00001544 syncBuf += syncExprBuf.str();
1545 syncBuf += ");";
1546
1547 buf += syncBuf;
1548 buf += "\n if (_rethrow) objc_exception_throw(_rethrow);\n";
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001549 buf += "}\n";
1550 buf += "}";
Mike Stump11289f42009-09-09 15:08:12 +00001551
Chris Lattner9cc55f52008-01-31 19:51:04 +00001552 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001553
1554 bool hasReturns = false;
1555 HasReturnStmts(S->getSynchBody(), hasReturns);
1556 if (hasReturns)
1557 RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1558
Fariborz Jahanian284011b2008-01-29 22:59:37 +00001559 return 0;
1560}
1561
Steve Naroffec60b432009-12-05 21:43:12 +00001562void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1563{
Steve Naroff6d6da252008-12-05 17:03:39 +00001564 // Perform a bottom up traversal of all children.
1565 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1566 CI != E; ++CI)
1567 if (*CI)
Steve Naroffec60b432009-12-05 21:43:12 +00001568 WarnAboutReturnGotoStmts(*CI);
Steve Naroff6d6da252008-12-05 17:03:39 +00001569
Steve Naroffec60b432009-12-05 21:43:12 +00001570 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
Mike Stump11289f42009-09-09 15:08:12 +00001571 Diags.Report(Context->getFullLoc(S->getLocStart()),
Steve Naroff6d6da252008-12-05 17:03:39 +00001572 TryFinallyContainsReturnDiag);
1573 }
1574 return;
1575}
1576
Steve Naroffec60b432009-12-05 21:43:12 +00001577void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1578{
1579 // Perform a bottom up traversal of all children.
1580 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1581 CI != E; ++CI)
1582 if (*CI)
1583 HasReturnStmts(*CI, hasReturns);
1584
1585 if (isa<ReturnStmt>(S))
1586 hasReturns = true;
1587 return;
1588}
1589
1590void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1591 // Perform a bottom up traversal of all children.
1592 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1593 CI != E; ++CI)
1594 if (*CI) {
1595 RewriteTryReturnStmts(*CI);
1596 }
1597 if (isa<ReturnStmt>(S)) {
1598 SourceLocation startLoc = S->getLocStart();
1599 const char *startBuf = SM->getCharacterData(startLoc);
1600
1601 const char *semiBuf = strchr(startBuf, ';');
1602 assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1603 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1604
1605 std::string buf;
1606 buf = "{ objc_exception_try_exit(&_stack); return";
1607
1608 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1609 InsertText(onePastSemiLoc, "}", 1);
1610 }
1611 return;
1612}
1613
1614void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1615 // Perform a bottom up traversal of all children.
1616 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
1617 CI != E; ++CI)
1618 if (*CI) {
1619 RewriteSyncReturnStmts(*CI, syncExitBuf);
1620 }
1621 if (isa<ReturnStmt>(S)) {
1622 SourceLocation startLoc = S->getLocStart();
1623 const char *startBuf = SM->getCharacterData(startLoc);
1624
1625 const char *semiBuf = strchr(startBuf, ';');
1626 assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1627 SourceLocation onePastSemiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf+1);
1628
1629 std::string buf;
1630 buf = "{ objc_exception_try_exit(&_stack);";
1631 buf += syncExitBuf;
1632 buf += " return";
1633
1634 ReplaceText(startLoc, 6, buf.c_str(), buf.size());
1635 InsertText(onePastSemiLoc, "}", 1);
1636 }
1637 return;
1638}
1639
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001640Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001641 // Get the start location and compute the semi location.
1642 SourceLocation startLoc = S->getLocStart();
1643 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001644
Steve Naroffbf478ec2007-11-07 04:08:17 +00001645 assert((*startBuf == '@') && "bogus @try location");
1646
1647 std::string buf;
1648 // declare a new scope with two variables, _stack and _rethrow.
1649 buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1650 buf += "int buf[18/*32-bit i386*/];\n";
1651 buf += "char *pointers[4];} _stack;\n";
1652 buf += "id volatile _rethrow = 0;\n";
1653 buf += "objc_exception_try_enter(&_stack);\n";
Steve Naroff16018582007-11-07 18:43:40 +00001654 buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
Steve Naroffbf478ec2007-11-07 04:08:17 +00001655
Chris Lattner9cc55f52008-01-31 19:51:04 +00001656 ReplaceText(startLoc, 4, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001657
Steve Naroffbf478ec2007-11-07 04:08:17 +00001658 startLoc = S->getTryBody()->getLocEnd();
1659 startBuf = SM->getCharacterData(startLoc);
1660
1661 assert((*startBuf == '}') && "bogus @try block");
Mike Stump11289f42009-09-09 15:08:12 +00001662
Steve Naroffbf478ec2007-11-07 04:08:17 +00001663 SourceLocation lastCurlyLoc = startLoc;
Steve Naroffce2dca12008-07-16 15:31:30 +00001664 ObjCAtCatchStmt *catchList = S->getCatchStmts();
1665 if (catchList) {
1666 startLoc = startLoc.getFileLocWithOffset(1);
1667 buf = " /* @catch begin */ else {\n";
1668 buf += " id _caught = objc_exception_extract(&_stack);\n";
1669 buf += " objc_exception_try_enter (&_stack);\n";
1670 buf += " if (_setjmp(_stack.buf))\n";
1671 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1672 buf += " else { /* @catch continue */";
Mike Stump11289f42009-09-09 15:08:12 +00001673
Steve Naroffce2dca12008-07-16 15:31:30 +00001674 InsertText(startLoc, buf.c_str(), buf.size());
Steve Narofffac18fe2008-09-09 19:59:12 +00001675 } else { /* no catch list */
1676 buf = "}\nelse {\n";
1677 buf += " _rethrow = objc_exception_extract(&_stack);\n";
1678 buf += "}";
1679 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffce2dca12008-07-16 15:31:30 +00001680 }
Steve Naroffbf478ec2007-11-07 04:08:17 +00001681 bool sawIdTypedCatch = false;
1682 Stmt *lastCatchBody = 0;
Steve Naroffbf478ec2007-11-07 04:08:17 +00001683 while (catchList) {
Steve Naroff371b8fb2009-03-03 19:52:17 +00001684 ParmVarDecl *catchDecl = catchList->getCatchParamDecl();
Steve Naroffbf478ec2007-11-07 04:08:17 +00001685
Mike Stump11289f42009-09-09 15:08:12 +00001686 if (catchList == S->getCatchStmts())
Steve Naroffbf478ec2007-11-07 04:08:17 +00001687 buf = "if ("; // we are generating code for the first catch clause
1688 else
1689 buf = "else if (";
1690 startLoc = catchList->getLocStart();
1691 startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001692
Steve Naroffbf478ec2007-11-07 04:08:17 +00001693 assert((*startBuf == '@') && "bogus @catch location");
Mike Stump11289f42009-09-09 15:08:12 +00001694
Steve Naroffbf478ec2007-11-07 04:08:17 +00001695 const char *lParenLoc = strchr(startBuf, '(');
1696
Steve Naroffe6b7ffd2008-02-01 22:08:12 +00001697 if (catchList->hasEllipsis()) {
Steve Naroffedb5bc62008-02-01 20:02:07 +00001698 // Now rewrite the body...
1699 lastCatchBody = catchList->getCatchBody();
Steve Naroffedb5bc62008-02-01 20:02:07 +00001700 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1701 const char *bodyBuf = SM->getCharacterData(bodyLoc);
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001702 assert(*SM->getCharacterData(catchList->getRParenLoc()) == ')' &&
1703 "bogus @catch paren location");
Steve Naroffedb5bc62008-02-01 20:02:07 +00001704 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001705
Steve Naroffedb5bc62008-02-01 20:02:07 +00001706 buf += "1) { id _tmp = _caught;";
Daniel Dunbardec484a2009-08-19 19:10:30 +00001707 Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
Steve Naroff371b8fb2009-03-03 19:52:17 +00001708 } else if (catchDecl) {
1709 QualType t = catchDecl->getType();
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001710 if (t == Context->getObjCIdType()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001711 buf += "1) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001712 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001713 sawIdTypedCatch = true;
Mike Stump11289f42009-09-09 15:08:12 +00001714 } else if (const PointerType *pType = t->getAs<PointerType>()) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001715 ObjCInterfaceType *cls; // Should be a pointer to a class.
Mike Stump11289f42009-09-09 15:08:12 +00001716
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001717 cls = dyn_cast<ObjCInterfaceType>(pType->getPointeeType().getTypePtr());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001718 if (cls) {
Steve Naroff16018582007-11-07 18:43:40 +00001719 buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00001720 buf += cls->getDecl()->getNameAsString();
Steve Naroff16018582007-11-07 18:43:40 +00001721 buf += "\"), (struct objc_object *)_caught)) { ";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001722 ReplaceText(startLoc, lParenLoc-startBuf+1, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001723 }
1724 }
1725 // Now rewrite the body...
1726 lastCatchBody = catchList->getCatchBody();
1727 SourceLocation rParenLoc = catchList->getRParenLoc();
1728 SourceLocation bodyLoc = lastCatchBody->getLocStart();
1729 const char *bodyBuf = SM->getCharacterData(bodyLoc);
1730 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1731 assert((*rParenBuf == ')') && "bogus @catch paren location");
1732 assert((*bodyBuf == '{') && "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001733
Steve Naroffbf478ec2007-11-07 04:08:17 +00001734 buf = " = _caught;";
Mike Stump11289f42009-09-09 15:08:12 +00001735 // Here we replace ") {" with "= _caught;" (which initializes and
Steve Naroffbf478ec2007-11-07 04:08:17 +00001736 // declares the @catch parameter).
Chris Lattner9cc55f52008-01-31 19:51:04 +00001737 ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, buf.c_str(), buf.size());
Steve Naroff371b8fb2009-03-03 19:52:17 +00001738 } else {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001739 assert(false && "@catch rewrite bug");
Steve Naroffa733c7f2007-11-07 15:32:26 +00001740 }
Steve Naroffedb5bc62008-02-01 20:02:07 +00001741 // make sure all the catch bodies get rewritten!
Steve Naroffbf478ec2007-11-07 04:08:17 +00001742 catchList = catchList->getNextCatchStmt();
1743 }
1744 // Complete the catch list...
1745 if (lastCatchBody) {
1746 SourceLocation bodyLoc = lastCatchBody->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001747 assert(*SM->getCharacterData(bodyLoc) == '}' &&
1748 "bogus @catch body location");
Mike Stump11289f42009-09-09 15:08:12 +00001749
Steve Naroff4adbe312008-09-11 15:29:03 +00001750 // Insert the last (implicit) else clause *before* the right curly brace.
1751 bodyLoc = bodyLoc.getFileLocWithOffset(-1);
1752 buf = "} /* last catch end */\n";
1753 buf += "else {\n";
1754 buf += " _rethrow = _caught;\n";
1755 buf += " objc_exception_try_exit(&_stack);\n";
1756 buf += "} } /* @catch end */\n";
1757 if (!S->getFinallyStmt())
1758 buf += "}\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001759 InsertText(bodyLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001760
Steve Naroffbf478ec2007-11-07 04:08:17 +00001761 // Set lastCurlyLoc
1762 lastCurlyLoc = lastCatchBody->getLocEnd();
1763 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00001764 if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
Steve Naroffbf478ec2007-11-07 04:08:17 +00001765 startLoc = finalStmt->getLocStart();
1766 startBuf = SM->getCharacterData(startLoc);
1767 assert((*startBuf == '@') && "bogus @finally start");
Mike Stump11289f42009-09-09 15:08:12 +00001768
Steve Naroffbf478ec2007-11-07 04:08:17 +00001769 buf = "/* @finally */";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001770 ReplaceText(startLoc, 8, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001771
Steve Naroffbf478ec2007-11-07 04:08:17 +00001772 Stmt *body = finalStmt->getFinallyBody();
1773 SourceLocation startLoc = body->getLocStart();
1774 SourceLocation endLoc = body->getLocEnd();
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001775 assert(*SM->getCharacterData(startLoc) == '{' &&
1776 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001777 assert(*SM->getCharacterData(endLoc) == '}' &&
Chris Lattner4fdfbf72008-04-08 05:52:18 +00001778 "bogus @finally body location");
Mike Stump11289f42009-09-09 15:08:12 +00001779
Steve Naroffbf478ec2007-11-07 04:08:17 +00001780 startLoc = startLoc.getFileLocWithOffset(1);
1781 buf = " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001782 InsertText(startLoc, buf.c_str(), buf.size());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001783 endLoc = endLoc.getFileLocWithOffset(-1);
1784 buf = " if (_rethrow) objc_exception_throw(_rethrow);\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001785 InsertText(endLoc, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001786
Steve Naroffbf478ec2007-11-07 04:08:17 +00001787 // Set lastCurlyLoc
1788 lastCurlyLoc = body->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00001789
Steve Naroff6d6da252008-12-05 17:03:39 +00001790 // Now check for any return/continue/go statements within the @try.
Steve Naroffec60b432009-12-05 21:43:12 +00001791 WarnAboutReturnGotoStmts(S->getTryBody());
Steve Naroff4adbe312008-09-11 15:29:03 +00001792 } else { /* no finally clause - make sure we synthesize an implicit one */
1793 buf = "{ /* implicit finally clause */\n";
1794 buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1795 buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1796 buf += "}";
1797 ReplaceText(lastCurlyLoc, 1, buf.c_str(), buf.size());
Steve Naroffec60b432009-12-05 21:43:12 +00001798
1799 // Now check for any return/continue/go statements within the @try.
1800 // The implicit finally clause won't called if the @try contains any
1801 // jump statements.
1802 bool hasReturns = false;
1803 HasReturnStmts(S->getTryBody(), hasReturns);
1804 if (hasReturns)
1805 RewriteTryReturnStmts(S->getTryBody());
Steve Naroffbf478ec2007-11-07 04:08:17 +00001806 }
1807 // Now emit the final closing curly brace...
1808 lastCurlyLoc = lastCurlyLoc.getFileLocWithOffset(1);
1809 buf = " } /* @try scope end */\n";
Chris Lattner1780a852008-01-31 19:42:41 +00001810 InsertText(lastCurlyLoc, buf.c_str(), buf.size());
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001811 return 0;
1812}
1813
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001814Stmt *RewriteObjC::RewriteObjCCatchStmt(ObjCAtCatchStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001815 return 0;
1816}
1817
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001818Stmt *RewriteObjC::RewriteObjCFinallyStmt(ObjCAtFinallyStmt *S) {
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001819 return 0;
1820}
1821
Mike Stump11289f42009-09-09 15:08:12 +00001822// This can't be done with ReplaceStmt(S, ThrowExpr), since
1823// the throw expression is typically a message expression that's already
Steve Naroffa733c7f2007-11-07 15:32:26 +00001824// been rewritten! (which implies the SourceLocation's are invalid).
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001825Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
Steve Naroffa733c7f2007-11-07 15:32:26 +00001826 // Get the start location and compute the semi location.
1827 SourceLocation startLoc = S->getLocStart();
1828 const char *startBuf = SM->getCharacterData(startLoc);
Mike Stump11289f42009-09-09 15:08:12 +00001829
Steve Naroffa733c7f2007-11-07 15:32:26 +00001830 assert((*startBuf == '@') && "bogus @throw location");
1831
1832 std::string buf;
1833 /* void objc_exception_throw(id) __attribute__((noreturn)); */
Steve Naroffc7d2df22008-01-19 00:42:38 +00001834 if (S->getThrowExpr())
1835 buf = "objc_exception_throw(";
1836 else // add an implicit argument
1837 buf = "objc_exception_throw(_caught";
Mike Stump11289f42009-09-09 15:08:12 +00001838
Steve Naroff29788342008-07-25 15:41:30 +00001839 // handle "@ throw" correctly.
1840 const char *wBuf = strchr(startBuf, 'w');
1841 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1842 ReplaceText(startLoc, wBuf-startBuf+1, buf.c_str(), buf.size());
Mike Stump11289f42009-09-09 15:08:12 +00001843
Steve Naroffa733c7f2007-11-07 15:32:26 +00001844 const char *semiBuf = strchr(startBuf, ';');
1845 assert((*semiBuf == ';') && "@throw: can't find ';'");
1846 SourceLocation semiLoc = startLoc.getFileLocWithOffset(semiBuf-startBuf);
1847 buf = ");";
Chris Lattner9cc55f52008-01-31 19:51:04 +00001848 ReplaceText(semiLoc, 1, buf.c_str(), buf.size());
Steve Naroffa733c7f2007-11-07 15:32:26 +00001849 return 0;
1850}
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00001851
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001852Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
Chris Lattnerc6d91c02007-10-17 22:35:30 +00001853 // Create a new string expression.
1854 QualType StrType = Context->getPointerType(Context->CharTy);
Anders Carlssond8499822007-10-29 05:01:08 +00001855 std::string StrEncoding;
Daniel Dunbarfc1066d2008-10-17 20:21:44 +00001856 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00001857 Expr *Replacement = StringLiteral::Create(*Context,StrEncoding.c_str(),
1858 StrEncoding.length(), false,StrType,
1859 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001860 ReplaceStmt(Exp, Replacement);
Mike Stump11289f42009-09-09 15:08:12 +00001861
Chris Lattner4431a1b2007-11-30 22:53:43 +00001862 // Replace this subexpr in the parent.
Steve Naroff22216db2008-12-04 23:50:32 +00001863 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Chris Lattner69534692007-10-24 16:57:36 +00001864 return Replacement;
Chris Lattnera7c19fe2007-10-16 22:36:42 +00001865}
1866
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001867Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
Steve Naroff2654e182008-12-22 22:16:07 +00001868 if (!SelGetUidFunctionDecl)
1869 SynthSelGetUidFunctionDecl();
Steve Naroffe4f9b232007-11-05 14:50:49 +00001870 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1871 // Create a call to sel_registerName("selName").
1872 llvm::SmallVector<Expr*, 8> SelExprs;
1873 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00001874 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00001875 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00001876 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00001877 false, argType, SourceLocation()));
Steve Naroffe4f9b232007-11-05 14:50:49 +00001878 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1879 &SelExprs[0], SelExprs.size());
Chris Lattner2e0d2602008-01-31 19:37:57 +00001880 ReplaceStmt(Exp, SelExp);
Steve Naroff22216db2008-12-04 23:50:32 +00001881 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffe4f9b232007-11-05 14:50:49 +00001882 return SelExp;
1883}
1884
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001885CallExpr *RewriteObjC::SynthesizeCallToFunctionDecl(
Steve Naroff574440f2007-10-24 22:48:43 +00001886 FunctionDecl *FD, Expr **args, unsigned nargs) {
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001887 // Get the type, we will need to reference it in a couple spots.
Steve Naroff574440f2007-10-24 22:48:43 +00001888 QualType msgSendType = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00001889
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001890 // Create a reference to the objc_msgSend() declaration.
Ted Kremenek5a201952009-02-07 01:47:29 +00001891 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, msgSendType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00001892
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00001893 // Now, we cast the reference to a pointer to the objc_msgSend type.
Chris Lattner3c799d72007-10-24 17:06:59 +00001894 QualType pToFunc = Context->getPointerType(msgSendType);
Mike Stump11289f42009-09-09 15:08:12 +00001895 ImplicitCastExpr *ICE = new (Context) ImplicitCastExpr(pToFunc,
Anders Carlssona2615922009-07-31 00:48:10 +00001896 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00001897 DRE,
Douglas Gregora11693b2008-11-12 17:17:38 +00001898 /*isLvalue=*/false);
Mike Stump11289f42009-09-09 15:08:12 +00001899
John McCall9dd450b2009-09-21 23:43:11 +00001900 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Mike Stump11289f42009-09-09 15:08:12 +00001901
Ted Kremenekd7b4f402009-02-09 20:51:47 +00001902 return new (Context) CallExpr(*Context, ICE, args, nargs, FT->getResultType(),
1903 SourceLocation());
Steve Naroff574440f2007-10-24 22:48:43 +00001904}
1905
Steve Naroff50d42052007-11-01 13:24:47 +00001906static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1907 const char *&startRef, const char *&endRef) {
1908 while (startBuf < endBuf) {
1909 if (*startBuf == '<')
1910 startRef = startBuf; // mark the start.
1911 if (*startBuf == '>') {
Steve Naroff1b232132007-11-09 12:50:28 +00001912 if (startRef && *startRef == '<') {
1913 endRef = startBuf; // mark the end.
1914 return true;
1915 }
1916 return false;
Steve Naroff50d42052007-11-01 13:24:47 +00001917 }
1918 startBuf++;
1919 }
1920 return false;
1921}
1922
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001923static void scanToNextArgument(const char *&argRef) {
1924 int angle = 0;
1925 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1926 if (*argRef == '<')
1927 angle++;
1928 else if (*argRef == '>')
1929 angle--;
1930 argRef++;
1931 }
1932 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1933}
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00001934
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001935bool RewriteObjC::needToScanForQualifiers(QualType T) {
Steve Naroffc277ad12009-07-18 15:33:26 +00001936 return T->isObjCQualifiedIdType() || T->isObjCQualifiedInterfaceType();
Steve Naroff50d42052007-11-01 13:24:47 +00001937}
1938
Steve Naroff873bd842008-07-29 18:15:38 +00001939void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1940 QualType Type = E->getType();
1941 if (needToScanForQualifiers(Type)) {
Steve Naroffdbfc6932008-11-19 21:15:47 +00001942 SourceLocation Loc, EndLoc;
Mike Stump11289f42009-09-09 15:08:12 +00001943
Steve Naroffdbfc6932008-11-19 21:15:47 +00001944 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1945 Loc = ECE->getLParenLoc();
1946 EndLoc = ECE->getRParenLoc();
1947 } else {
1948 Loc = E->getLocStart();
1949 EndLoc = E->getLocEnd();
1950 }
1951 // This will defend against trying to rewrite synthesized expressions.
1952 if (Loc.isInvalid() || EndLoc.isInvalid())
1953 return;
1954
Steve Naroff873bd842008-07-29 18:15:38 +00001955 const char *startBuf = SM->getCharacterData(Loc);
Steve Naroffdbfc6932008-11-19 21:15:47 +00001956 const char *endBuf = SM->getCharacterData(EndLoc);
Steve Naroff873bd842008-07-29 18:15:38 +00001957 const char *startRef = 0, *endRef = 0;
1958 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
1959 // Get the locations of the startRef, endRef.
1960 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-startBuf);
1961 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-startBuf+1);
1962 // Comment out the protocol references.
1963 InsertText(LessLoc, "/*", 2);
1964 InsertText(GreaterLoc, "*/", 2);
1965 }
1966 }
1967}
1968
Steve Naroff1dc53ef2008-04-14 22:03:09 +00001969void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001970 SourceLocation Loc;
1971 QualType Type;
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001972 const FunctionProtoType *proto = 0;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001973 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
1974 Loc = VD->getLocation();
1975 Type = VD->getType();
1976 }
1977 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
1978 Loc = FD->getLocation();
1979 // Check for ObjC 'id' and class types that have been adorned with protocol
1980 // information (id<p>, C<p>*). The protocol references need to be rewritten!
John McCall9dd450b2009-09-21 23:43:11 +00001981 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001982 assert(funcType && "missing function type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00001983 proto = dyn_cast<FunctionProtoType>(funcType);
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001984 if (!proto)
1985 return;
1986 Type = proto->getResultType();
1987 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00001988 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
1989 Loc = FD->getLocation();
1990 Type = FD->getType();
1991 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001992 else
1993 return;
Mike Stump11289f42009-09-09 15:08:12 +00001994
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00001995 if (needToScanForQualifiers(Type)) {
Steve Naroff50d42052007-11-01 13:24:47 +00001996 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00001997
Steve Naroff50d42052007-11-01 13:24:47 +00001998 const char *endBuf = SM->getCharacterData(Loc);
1999 const char *startBuf = endBuf;
Steve Naroff930e0992008-05-31 05:02:17 +00002000 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
Steve Naroff50d42052007-11-01 13:24:47 +00002001 startBuf--; // scan backward (from the decl location) for return type.
2002 const char *startRef = 0, *endRef = 0;
2003 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2004 // Get the locations of the startRef, endRef.
2005 SourceLocation LessLoc = Loc.getFileLocWithOffset(startRef-endBuf);
2006 SourceLocation GreaterLoc = Loc.getFileLocWithOffset(endRef-endBuf+1);
2007 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002008 InsertText(LessLoc, "/*", 2);
2009 InsertText(GreaterLoc, "*/", 2);
Steve Naroff37e011c2007-10-31 04:38:33 +00002010 }
2011 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002012 if (!proto)
2013 return; // most likely, was a variable
Steve Naroff50d42052007-11-01 13:24:47 +00002014 // Now check arguments.
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002015 const char *startBuf = SM->getCharacterData(Loc);
2016 const char *startFuncBuf = startBuf;
Steve Naroff50d42052007-11-01 13:24:47 +00002017 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2018 if (needToScanForQualifiers(proto->getArgType(i))) {
2019 // Since types are unique, we need to scan the buffer.
Mike Stump11289f42009-09-09 15:08:12 +00002020
Steve Naroff50d42052007-11-01 13:24:47 +00002021 const char *endBuf = startBuf;
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002022 // scan forward (from the decl location) for argument types.
2023 scanToNextArgument(endBuf);
Steve Naroff50d42052007-11-01 13:24:47 +00002024 const char *startRef = 0, *endRef = 0;
2025 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2026 // Get the locations of the startRef, endRef.
Mike Stump11289f42009-09-09 15:08:12 +00002027 SourceLocation LessLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002028 Loc.getFileLocWithOffset(startRef-startFuncBuf);
Mike Stump11289f42009-09-09 15:08:12 +00002029 SourceLocation GreaterLoc =
Fariborz Jahanian16e703a2007-12-11 23:04:08 +00002030 Loc.getFileLocWithOffset(endRef-startFuncBuf+1);
Steve Naroff50d42052007-11-01 13:24:47 +00002031 // Comment out the protocol references.
Chris Lattner1780a852008-01-31 19:42:41 +00002032 InsertText(LessLoc, "/*", 2);
2033 InsertText(GreaterLoc, "*/", 2);
Steve Naroff50d42052007-11-01 13:24:47 +00002034 }
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002035 startBuf = ++endBuf;
2036 }
2037 else {
Steve Naroffc884aa82008-08-06 15:58:23 +00002038 // If the function name is derived from a macro expansion, then the
2039 // argument buffer will not follow the name. Need to speak with Chris.
2040 while (*startBuf && *startBuf != ')' && *startBuf != ',')
Fariborz Jahanian4e56ed52007-12-11 22:50:14 +00002041 startBuf++; // scan forward (from the decl location) for argument types.
2042 startBuf++;
2043 }
Steve Naroff50d42052007-11-01 13:24:47 +00002044 }
Steve Naroff37e011c2007-10-31 04:38:33 +00002045}
2046
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002047// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002048void RewriteObjC::SynthSelGetUidFunctionDecl() {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002049 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2050 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002051 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002052 QualType getFuncType = Context->getFunctionType(Context->getObjCSelType(),
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002053 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002054 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002055 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002056 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002057 SelGetUidIdent, getFuncType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002058 FunctionDecl::Extern, false);
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002059}
2060
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002061void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002062 // declared in <objc/objc.h>
Douglas Gregor1e21c192009-01-09 01:47:02 +00002063 if (FD->getIdentifier() &&
2064 strcmp(FD->getNameAsCString(), "sel_registerName") == 0) {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002065 SelGetUidFunctionDecl = FD;
Steve Naroff37e011c2007-10-31 04:38:33 +00002066 return;
2067 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002068 RewriteObjCQualifiedInterfaceTypes(FD);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002069}
2070
Steve Naroff17978c42008-03-11 17:37:02 +00002071// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002072void RewriteObjC::SynthSuperContructorFunctionDecl() {
Steve Naroff17978c42008-03-11 17:37:02 +00002073 if (SuperContructorFunctionDecl)
2074 return;
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002075 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
Steve Naroff17978c42008-03-11 17:37:02 +00002076 llvm::SmallVector<QualType, 16> ArgTys;
2077 QualType argT = Context->getObjCIdType();
2078 assert(!argT.isNull() && "Can't find 'id' type");
2079 ArgTys.push_back(argT);
2080 ArgTys.push_back(argT);
2081 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
2082 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002083 false, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002084 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002085 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002086 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002087 FunctionDecl::Extern, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002088}
2089
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002090// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002091void RewriteObjC::SynthMsgSendFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002092 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2093 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002094 QualType argT = Context->getObjCIdType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002095 assert(!argT.isNull() && "Can't find 'id' type");
2096 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002097 argT = Context->getObjCSelType();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002098 assert(!argT.isNull() && "Can't find 'SEL' type");
2099 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002100 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002101 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002102 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002103 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002104 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002105 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002106 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002107}
2108
Steve Naroff7fa2f042007-11-15 10:28:18 +00002109// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002110void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002111 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2112 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002113 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002114 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002115 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002116 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2117 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2118 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002119 argT = Context->getObjCSelType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002120 assert(!argT.isNull() && "Can't find 'SEL' type");
2121 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002122 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff7fa2f042007-11-15 10:28:18 +00002123 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002124 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002125 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002126 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002127 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002128 FunctionDecl::Extern, false);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002129}
2130
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002131// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002132void RewriteObjC::SynthMsgSendStretFunctionDecl() {
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002133 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2134 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002135 QualType argT = Context->getObjCIdType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002136 assert(!argT.isNull() && "Can't find 'id' type");
2137 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002138 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002139 assert(!argT.isNull() && "Can't find 'SEL' type");
2140 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002141 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002142 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002143 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002144 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002145 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002146 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002147 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002148}
2149
Mike Stump11289f42009-09-09 15:08:12 +00002150// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002151// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002152void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
Mike Stump11289f42009-09-09 15:08:12 +00002153 IdentifierInfo *msgSendIdent =
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002154 &Context->Idents.get("objc_msgSendSuper_stret");
2155 llvm::SmallVector<QualType, 16> ArgTys;
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002156 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Chris Lattnerc5ffed42008-04-04 06:12:32 +00002157 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002158 &Context->Idents.get("objc_super"));
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002159 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2160 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2161 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002162 argT = Context->getObjCSelType();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002163 assert(!argT.isNull() && "Can't find 'SEL' type");
2164 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002165 QualType msgSendType = Context->getFunctionType(Context->getObjCIdType(),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002166 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002167 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002168 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002169 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002170 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002171 FunctionDecl::Extern, false);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002172}
2173
Steve Naroff2e4e3852008-05-08 22:02:18 +00002174// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002175void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002176 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2177 llvm::SmallVector<QualType, 16> ArgTys;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002178 QualType argT = Context->getObjCIdType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002179 assert(!argT.isNull() && "Can't find 'id' type");
2180 ArgTys.push_back(argT);
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002181 argT = Context->getObjCSelType();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002182 assert(!argT.isNull() && "Can't find 'SEL' type");
2183 ArgTys.push_back(argT);
Steve Naroff2e4e3852008-05-08 22:02:18 +00002184 QualType msgSendType = Context->getFunctionType(Context->DoubleTy,
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002185 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002186 true /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002187 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002188 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002189 msgSendIdent, msgSendType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002190 FunctionDecl::Extern, false);
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002191}
2192
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002193// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002194void RewriteObjC::SynthGetClassFunctionDecl() {
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002195 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2196 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002197 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002198 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002199 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002200 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002201 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002202 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002203 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002204 FunctionDecl::Extern, false);
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002205}
2206
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002207// SynthGetMetaClassFunctionDecl - id objc_getClass(const char *name);
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002208void RewriteObjC::SynthGetMetaClassFunctionDecl() {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002209 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2210 llvm::SmallVector<QualType, 16> ArgTys;
John McCall8ccfcb52009-09-24 19:53:00 +00002211 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002212 QualType getClassType = Context->getFunctionType(Context->getObjCIdType(),
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002213 &ArgTys[0], ArgTys.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002214 false /*isVariadic*/, 0);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00002215 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002216 SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002217 getClassIdent, getClassType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002218 FunctionDecl::Extern, false);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002219}
2220
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002221Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
Steve Naroffce8e8862008-03-15 00:55:56 +00002222 QualType strType = getConstantStringStructType();
2223
2224 std::string S = "__NSConstantStringImpl_";
Steve Naroffa6141f02008-05-31 03:35:42 +00002225
2226 std::string tmpName = InFileName;
2227 unsigned i;
2228 for (i=0; i < tmpName.length(); i++) {
2229 char c = tmpName.at(i);
2230 // replace any non alphanumeric characters with '_'.
2231 if (!isalpha(c) && (c < '0' || c > '9'))
2232 tmpName[i] = '_';
2233 }
2234 S += tmpName;
2235 S += "_";
Steve Naroffce8e8862008-03-15 00:55:56 +00002236 S += utostr(NumObjCStringLiterals++);
2237
Steve Naroff00a31762008-03-27 22:29:16 +00002238 Preamble += "static __NSConstantStringImpl " + S;
2239 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2240 Preamble += "0x000007c8,"; // utf8_str
Steve Naroffce8e8862008-03-15 00:55:56 +00002241 // The pretty printer for StringLiteral handles escape characters properly.
Ted Kremenek2d470fc2008-09-13 05:16:45 +00002242 std::string prettyBufS;
2243 llvm::raw_string_ostream prettyBuf(prettyBufS);
Chris Lattnerc61089a2009-06-30 01:26:17 +00002244 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2245 PrintingPolicy(LangOpts));
Steve Naroff00a31762008-03-27 22:29:16 +00002246 Preamble += prettyBuf.str();
2247 Preamble += ",";
Steve Naroff94ed6dc2009-12-06 01:48:44 +00002248 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002249
2250 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2251 &Context->Idents.get(S.c_str()), strType, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002252 VarDecl::Static);
Ted Kremenek5a201952009-02-07 01:47:29 +00002253 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, strType, SourceLocation());
2254 Expr *Unop = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002255 Context->getPointerType(DRE->getType()),
Steve Naroffce8e8862008-03-15 00:55:56 +00002256 SourceLocation());
Steve Naroff265a6b92007-11-08 14:30:50 +00002257 // cast to NSConstantString *
Mike Stump11289f42009-09-09 15:08:12 +00002258 CastExpr *cast = new (Context) CStyleCastExpr(Exp->getType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002259 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002260 Unop, Exp->getType(),
2261 SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002262 SourceLocation());
Chris Lattner2e0d2602008-01-31 19:37:57 +00002263 ReplaceStmt(Exp, cast);
Steve Naroff22216db2008-12-04 23:50:32 +00002264 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroff265a6b92007-11-08 14:30:50 +00002265 return cast;
Steve Naroffa397efd2007-11-03 11:27:19 +00002266}
2267
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002268ObjCInterfaceDecl *RewriteObjC::isSuperReceiver(Expr *recExpr) {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002269 // check if we are sending a message to 'super'
Douglas Gregorffca3a22009-01-09 17:18:27 +00002270 if (!CurMethodDef || !CurMethodDef->isInstanceMethod()) return 0;
Mike Stump11289f42009-09-09 15:08:12 +00002271
Douglas Gregor8ea1f532008-11-04 14:56:14 +00002272 if (ObjCSuperExpr *Super = dyn_cast<ObjCSuperExpr>(recExpr)) {
Mike Stump11289f42009-09-09 15:08:12 +00002273 const ObjCObjectPointerType *OPT =
John McCall9dd450b2009-09-21 23:43:11 +00002274 Super->getType()->getAs<ObjCObjectPointerType>();
Steve Naroff7cae42b2009-07-10 23:34:53 +00002275 assert(OPT);
2276 const ObjCInterfaceType *IT = OPT->getInterfaceType();
Chris Lattnera9b3cae2008-06-21 18:04:54 +00002277 return IT->getDecl();
2278 }
2279 return 0;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002280}
2281
2282// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002283QualType RewriteObjC::getSuperStructType() {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002284 if (!SuperStructDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002285 SuperStructDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002286 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002287 &Context->Idents.get("objc_super"));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002288 QualType FieldTypes[2];
Mike Stump11289f42009-09-09 15:08:12 +00002289
Steve Naroff7fa2f042007-11-15 10:28:18 +00002290 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002291 FieldTypes[0] = Context->getObjCIdType();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002292 // struct objc_class *super;
Mike Stump11289f42009-09-09 15:08:12 +00002293 FieldTypes[1] = Context->getObjCClassType();
Douglas Gregor91f84212008-12-11 16:49:14 +00002294
Steve Naroff7fa2f042007-11-15 10:28:18 +00002295 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002296 for (unsigned i = 0; i < 2; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002297 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2298 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002299 FieldTypes[i], 0,
2300 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002301 /*Mutable=*/false));
Douglas Gregor91f84212008-12-11 16:49:14 +00002302 }
Mike Stump11289f42009-09-09 15:08:12 +00002303
Douglas Gregor91f84212008-12-11 16:49:14 +00002304 SuperStructDecl->completeDefinition(*Context);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002305 }
2306 return Context->getTagDeclType(SuperStructDecl);
2307}
2308
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002309QualType RewriteObjC::getConstantStringStructType() {
Steve Naroffce8e8862008-03-15 00:55:56 +00002310 if (!ConstantStringDecl) {
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00002311 ConstantStringDecl = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002312 SourceLocation(),
Ted Kremenek47923c72008-09-05 01:34:33 +00002313 &Context->Idents.get("__NSConstantStringImpl"));
Steve Naroffce8e8862008-03-15 00:55:56 +00002314 QualType FieldTypes[4];
Mike Stump11289f42009-09-09 15:08:12 +00002315
Steve Naroffce8e8862008-03-15 00:55:56 +00002316 // struct objc_object *receiver;
Mike Stump11289f42009-09-09 15:08:12 +00002317 FieldTypes[0] = Context->getObjCIdType();
Steve Naroffce8e8862008-03-15 00:55:56 +00002318 // int flags;
Mike Stump11289f42009-09-09 15:08:12 +00002319 FieldTypes[1] = Context->IntTy;
Steve Naroffce8e8862008-03-15 00:55:56 +00002320 // char *str;
Mike Stump11289f42009-09-09 15:08:12 +00002321 FieldTypes[2] = Context->getPointerType(Context->CharTy);
Steve Naroffce8e8862008-03-15 00:55:56 +00002322 // long length;
Mike Stump11289f42009-09-09 15:08:12 +00002323 FieldTypes[3] = Context->LongTy;
Douglas Gregor91f84212008-12-11 16:49:14 +00002324
Steve Naroffce8e8862008-03-15 00:55:56 +00002325 // Create fields
Douglas Gregor91f84212008-12-11 16:49:14 +00002326 for (unsigned i = 0; i < 4; ++i) {
Mike Stump11289f42009-09-09 15:08:12 +00002327 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2328 ConstantStringDecl,
Douglas Gregor91f84212008-12-11 16:49:14 +00002329 SourceLocation(), 0,
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00002330 FieldTypes[i], 0,
Douglas Gregor91f84212008-12-11 16:49:14 +00002331 /*BitWidth=*/0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00002332 /*Mutable=*/true));
Douglas Gregor91f84212008-12-11 16:49:14 +00002333 }
2334
2335 ConstantStringDecl->completeDefinition(*Context);
Steve Naroffce8e8862008-03-15 00:55:56 +00002336 }
2337 return Context->getTagDeclType(ConstantStringDecl);
2338}
2339
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002340Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian31e18502007-12-04 21:47:40 +00002341 if (!SelGetUidFunctionDecl)
2342 SynthSelGetUidFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002343 if (!MsgSendFunctionDecl)
2344 SynthMsgSendFunctionDecl();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002345 if (!MsgSendSuperFunctionDecl)
2346 SynthMsgSendSuperFunctionDecl();
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002347 if (!MsgSendStretFunctionDecl)
2348 SynthMsgSendStretFunctionDecl();
2349 if (!MsgSendSuperStretFunctionDecl)
2350 SynthMsgSendSuperStretFunctionDecl();
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002351 if (!MsgSendFpretFunctionDecl)
2352 SynthMsgSendFpretFunctionDecl();
Steve Naroff5cdcd9b2007-10-30 23:14:51 +00002353 if (!GetClassFunctionDecl)
2354 SynthGetClassFunctionDecl();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002355 if (!GetMetaClassFunctionDecl)
2356 SynthGetMetaClassFunctionDecl();
Mike Stump11289f42009-09-09 15:08:12 +00002357
Steve Naroff7fa2f042007-11-15 10:28:18 +00002358 // default to objc_msgSend().
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002359 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2360 // May need to use objc_msgSend_stret() as well.
2361 FunctionDecl *MsgSendStretFlavor = 0;
Steve Naroffd9803712009-04-29 16:37:50 +00002362 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2363 QualType resultType = mDecl->getResultType();
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002364 if (resultType->isStructureType() || resultType->isUnionType())
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002365 MsgSendStretFlavor = MsgSendStretFunctionDecl;
Chris Lattner3f6cd0b2008-07-26 22:36:27 +00002366 else if (resultType->isRealFloatingType())
Fariborz Jahanian4f76f222007-12-03 21:26:48 +00002367 MsgSendFlavor = MsgSendFpretFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002368 }
Mike Stump11289f42009-09-09 15:08:12 +00002369
Steve Naroff574440f2007-10-24 22:48:43 +00002370 // Synthesize a call to objc_msgSend().
2371 llvm::SmallVector<Expr*, 8> MsgExprs;
2372 IdentifierInfo *clsName = Exp->getClassName();
Mike Stump11289f42009-09-09 15:08:12 +00002373
Steve Naroff574440f2007-10-24 22:48:43 +00002374 // Derive/push the receiver/selector, 2 implicit arguments to objc_msgSend().
2375 if (clsName) { // class message.
Steve Naroff6c79f972008-07-24 19:44:33 +00002376 // FIXME: We need to fix Sema (and the AST for ObjCMessageExpr) to handle
2377 // the 'super' idiom within a class method.
Daniel Dunbar07d07852009-10-18 21:17:35 +00002378 if (clsName->getName() == "super") {
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002379 MsgSendFlavor = MsgSendSuperFunctionDecl;
2380 if (MsgSendStretFlavor)
2381 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2382 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002383
2384 ObjCInterfaceDecl *SuperDecl =
Steve Naroff677ab3a2008-10-27 17:20:55 +00002385 CurMethodDef->getClassInterface()->getSuperClass();
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002386
2387 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002388
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002389 // set the receiver to self, the first argument to all methods.
Steve Naroffd9803712009-04-29 16:37:50 +00002390 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002391 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002392 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002393 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroffd9803712009-04-29 16:37:50 +00002394 Context->getObjCIdType(),
2395 SourceLocation()),
2396 Context->getObjCIdType(),
2397 SourceLocation(), SourceLocation())); // set the 'receiver'.
2398
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002399 llvm::SmallVector<Expr*, 8> ClsExprs;
2400 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002401 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002402 SuperDecl->getIdentifier()->getNameStart(),
2403 SuperDecl->getIdentifier()->getLength(),
2404 false, argType, SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002405 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002406 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002407 ClsExprs.size());
2408 // To turn off a warning, type-cast to 'id'
Douglas Gregore200adc2008-10-27 19:41:14 +00002409 InitExprs.push_back( // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002410 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002411 CastExpr::CK_Unknown,
Douglas Gregore200adc2008-10-27 19:41:14 +00002412 Cls, Context->getObjCIdType(),
Mike Stump11289f42009-09-09 15:08:12 +00002413 SourceLocation(), SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002414 // struct objc_super
2415 QualType superType = getSuperStructType();
Steve Naroff0b844f02008-03-11 18:14:26 +00002416 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002417
Steve Naroff0b844f02008-03-11 18:14:26 +00002418 if (LangOpts.Microsoft) {
2419 SynthSuperContructorFunctionDecl();
2420 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002421 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff0b844f02008-03-11 18:14:26 +00002422 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002423 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002424 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002425 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002426 // The code for super is a little tricky to prevent collision with
2427 // the structure definition in the header. The rewriter has it's own
2428 // internal definition (__rw_objc_super) that is uses. This is why
2429 // we need the cast below. For example:
2430 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2431 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002432 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002433 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002434 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002435 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
2436 CastExpr::CK_Unknown, SuperRep,
Anders Carlssona2615922009-07-31 00:48:10 +00002437 Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002438 SourceLocation(), SourceLocation());
2439 } else {
Steve Naroff0b844f02008-03-11 18:14:26 +00002440 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002441 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2442 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002443 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002444 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE,
Chris Lattner07d754a2008-10-26 23:43:26 +00002445 false);
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002446 // struct objc_super *
Ted Kremenek5a201952009-02-07 01:47:29 +00002447 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002448 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002449 SourceLocation());
Steve Naroff0b844f02008-03-11 18:14:26 +00002450 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002451 MsgExprs.push_back(SuperRep);
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002452 } else {
2453 llvm::SmallVector<Expr*, 8> ClsExprs;
2454 QualType argType = Context->getPointerType(Context->CharTy);
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002455 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002456 clsName->getNameStart(),
Chris Lattnerf83b5af2009-02-18 06:40:38 +00002457 clsName->getLength(),
2458 false, argType,
2459 SourceLocation()));
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002460 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002461 &ClsExprs[0],
Steve Naroffb2f8ff12007-12-07 03:50:46 +00002462 ClsExprs.size());
2463 MsgExprs.push_back(Cls);
2464 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002465 } else { // instance message.
2466 Expr *recExpr = Exp->getReceiver();
Steve Naroff7fa2f042007-11-15 10:28:18 +00002467
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002468 if (ObjCInterfaceDecl *SuperDecl = isSuperReceiver(recExpr)) {
Steve Naroff7fa2f042007-11-15 10:28:18 +00002469 MsgSendFlavor = MsgSendSuperFunctionDecl;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002470 if (MsgSendStretFlavor)
2471 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
Steve Naroff7fa2f042007-11-15 10:28:18 +00002472 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
Mike Stump11289f42009-09-09 15:08:12 +00002473
Steve Naroff7fa2f042007-11-15 10:28:18 +00002474 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00002475
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002476 InitExprs.push_back(
Mike Stump11289f42009-09-09 15:08:12 +00002477 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002478 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002479 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
Steve Naroff97adf602008-07-16 22:35:27 +00002480 Context->getObjCIdType(),
Douglas Gregore200adc2008-10-27 19:41:14 +00002481 SourceLocation()),
2482 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002483 SourceLocation(), SourceLocation())); // set the 'receiver'.
Mike Stump11289f42009-09-09 15:08:12 +00002484
Steve Naroff7fa2f042007-11-15 10:28:18 +00002485 llvm::SmallVector<Expr*, 8> ClsExprs;
2486 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002487 ClsExprs.push_back(StringLiteral::Create(*Context,
Daniel Dunbar2c422dc92009-10-18 20:26:12 +00002488 SuperDecl->getIdentifier()->getNameStart(),
2489 SuperDecl->getIdentifier()->getLength(),
2490 false, argType, SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002491 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002492 &ClsExprs[0],
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002493 ClsExprs.size());
Fariborz Jahaniand5db92b2007-12-05 17:29:46 +00002494 // To turn off a warning, type-cast to 'id'
Fariborz Jahanian1e34ce12007-12-04 22:32:58 +00002495 InitExprs.push_back(
Douglas Gregore200adc2008-10-27 19:41:14 +00002496 // set 'super class', using objc_getClass().
Mike Stump11289f42009-09-09 15:08:12 +00002497 new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002498 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002499 Cls, Context->getObjCIdType(), SourceLocation(), SourceLocation()));
Steve Naroff7fa2f042007-11-15 10:28:18 +00002500 // struct objc_super
2501 QualType superType = getSuperStructType();
Steve Naroff17978c42008-03-11 17:37:02 +00002502 Expr *SuperRep;
Mike Stump11289f42009-09-09 15:08:12 +00002503
Steve Naroff17978c42008-03-11 17:37:02 +00002504 if (LangOpts.Microsoft) {
2505 SynthSuperContructorFunctionDecl();
2506 // Simulate a contructor call...
Mike Stump11289f42009-09-09 15:08:12 +00002507 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
Steve Naroff17978c42008-03-11 17:37:02 +00002508 superType, SourceLocation());
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002509 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002510 InitExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002511 superType, SourceLocation());
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002512 // The code for super is a little tricky to prevent collision with
2513 // the structure definition in the header. The rewriter has it's own
2514 // internal definition (__rw_objc_super) that is uses. This is why
2515 // we need the cast below. For example:
2516 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2517 //
Ted Kremenek5a201952009-02-07 01:47:29 +00002518 SuperRep = new (Context) UnaryOperator(SuperRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00002519 Context->getPointerType(SuperRep->getType()),
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002520 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002521 SuperRep = new (Context) CStyleCastExpr(Context->getPointerType(superType),
Anders Carlssona2615922009-07-31 00:48:10 +00002522 CastExpr::CK_Unknown,
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002523 SuperRep, Context->getPointerType(superType),
Mike Stump11289f42009-09-09 15:08:12 +00002524 SourceLocation(), SourceLocation());
Steve Naroff17978c42008-03-11 17:37:02 +00002525 } else {
2526 // (struct objc_super) { <exprs from above> }
Mike Stump11289f42009-09-09 15:08:12 +00002527 InitListExpr *ILE = new (Context) InitListExpr(SourceLocation(),
2528 &InitExprs[0], InitExprs.size(),
Douglas Gregor347f7ea2009-01-28 21:54:33 +00002529 SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00002530 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superType, ILE, false);
Steve Naroff17978c42008-03-11 17:37:02 +00002531 }
Steve Naroff6ab6dc72008-12-23 20:11:22 +00002532 MsgExprs.push_back(SuperRep);
Steve Naroff7fa2f042007-11-15 10:28:18 +00002533 } else {
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002534 // Remove all type-casts because it may contain objc-style types; e.g.
2535 // Foo<Proto> *.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002536 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
Fariborz Jahanianff6a4552007-12-07 21:21:21 +00002537 recExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002538 recExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002539 CastExpr::CK_Unknown, recExpr,
Mike Stump11289f42009-09-09 15:08:12 +00002540 Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002541 SourceLocation(), SourceLocation());
Steve Naroff7fa2f042007-11-15 10:28:18 +00002542 MsgExprs.push_back(recExpr);
2543 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002544 }
Steve Naroffa397efd2007-11-03 11:27:19 +00002545 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
Steve Naroff574440f2007-10-24 22:48:43 +00002546 llvm::SmallVector<Expr*, 8> SelExprs;
2547 QualType argType = Context->getPointerType(Context->CharTy);
Mike Stump11289f42009-09-09 15:08:12 +00002548 SelExprs.push_back(StringLiteral::Create(*Context,
Ted Kremenek6b7ecf62009-02-06 19:55:15 +00002549 Exp->getSelector().getAsString().c_str(),
Chris Lattnere4b95692008-11-24 03:33:13 +00002550 Exp->getSelector().getAsString().size(),
Chris Lattner630970d2009-02-18 05:49:11 +00002551 false, argType, SourceLocation()));
Steve Naroff574440f2007-10-24 22:48:43 +00002552 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2553 &SelExprs[0], SelExprs.size());
2554 MsgExprs.push_back(SelExp);
Mike Stump11289f42009-09-09 15:08:12 +00002555
Steve Naroff574440f2007-10-24 22:48:43 +00002556 // Now push any user supplied arguments.
2557 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
Steve Naroffe7f18192007-11-14 23:54:14 +00002558 Expr *userExpr = Exp->getArg(i);
Steve Narofff60782b2007-11-15 02:58:25 +00002559 // Make all implicit casts explicit...ICE comes in handy:-)
2560 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2561 // Reuse the ICE type, it is exactly what the doctor ordered.
Douglas Gregore200adc2008-10-27 19:41:14 +00002562 QualType type = ICE->getType()->isObjCQualifiedIdType()
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002563 ? Context->getObjCIdType()
Douglas Gregore200adc2008-10-27 19:41:14 +00002564 : ICE->getType();
Anders Carlssona2615922009-07-31 00:48:10 +00002565 userExpr = new (Context) CStyleCastExpr(type, CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002566 userExpr, type, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002567 SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002568 }
2569 // Make id<P...> cast into an 'id' cast.
Douglas Gregorf19b2312008-10-28 15:36:24 +00002570 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002571 if (CE->getType()->isObjCQualifiedIdType()) {
Douglas Gregorf19b2312008-10-28 15:36:24 +00002572 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002573 userExpr = CE->getSubExpr();
Mike Stump11289f42009-09-09 15:08:12 +00002574 userExpr = new (Context) CStyleCastExpr(Context->getObjCIdType(),
Anders Carlssona2615922009-07-31 00:48:10 +00002575 CastExpr::CK_Unknown,
Mike Stump11289f42009-09-09 15:08:12 +00002576 userExpr, Context->getObjCIdType(),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002577 SourceLocation(), SourceLocation());
Fariborz Jahanian9f0e3102007-12-18 21:33:44 +00002578 }
Mike Stump11289f42009-09-09 15:08:12 +00002579 }
Steve Naroffe7f18192007-11-14 23:54:14 +00002580 MsgExprs.push_back(userExpr);
Steve Naroffd9803712009-04-29 16:37:50 +00002581 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2582 // out the argument in the original expression (since we aren't deleting
2583 // the ObjCMessageExpr). See RewritePropertySetter() usage for more info.
2584 //Exp->setArg(i, 0);
Steve Naroff574440f2007-10-24 22:48:43 +00002585 }
Steve Narofff36987c2007-11-04 22:37:50 +00002586 // Generate the funky cast.
2587 CastExpr *cast;
2588 llvm::SmallVector<QualType, 8> ArgTypes;
2589 QualType returnType;
Mike Stump11289f42009-09-09 15:08:12 +00002590
Steve Narofff36987c2007-11-04 22:37:50 +00002591 // Push 'id' and 'SEL', the 2 implicit arguments.
Steve Naroff44864e42007-11-15 10:43:57 +00002592 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2593 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2594 else
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002595 ArgTypes.push_back(Context->getObjCIdType());
2596 ArgTypes.push_back(Context->getObjCSelType());
Chris Lattnera4997152009-02-20 18:43:26 +00002597 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
Steve Narofff36987c2007-11-04 22:37:50 +00002598 // Push any user argument types.
Chris Lattnera4997152009-02-20 18:43:26 +00002599 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2600 E = OMD->param_end(); PI != E; ++PI) {
2601 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
Mike Stump11289f42009-09-09 15:08:12 +00002602 ? Context->getObjCIdType()
Chris Lattnera4997152009-02-20 18:43:26 +00002603 : (*PI)->getType();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002604 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00002605 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00002606 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff52c65fa2008-10-29 14:49:46 +00002607 t = Context->getPointerType(BPT->getPointeeType());
2608 }
Steve Naroff98eb8d12007-11-05 14:36:37 +00002609 ArgTypes.push_back(t);
2610 }
Chris Lattnera4997152009-02-20 18:43:26 +00002611 returnType = OMD->getResultType()->isObjCQualifiedIdType()
2612 ? Context->getObjCIdType() : OMD->getResultType();
Steve Narofff36987c2007-11-04 22:37:50 +00002613 } else {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002614 returnType = Context->getObjCIdType();
Steve Narofff36987c2007-11-04 22:37:50 +00002615 }
2616 // Get the type, we will need to reference it in a couple spots.
Steve Naroff7fa2f042007-11-15 10:28:18 +00002617 QualType msgSendType = MsgSendFlavor->getType();
Mike Stump11289f42009-09-09 15:08:12 +00002618
Steve Narofff36987c2007-11-04 22:37:50 +00002619 // Create a reference to the objc_msgSend() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002620 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002621 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002622
Mike Stump11289f42009-09-09 15:08:12 +00002623 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
Steve Narofff36987c2007-11-04 22:37:50 +00002624 // If we don't do this cast, we get the following bizarre warning/note:
2625 // xx.m:13: warning: function called through a non-compatible type
2626 // xx.m:13: note: if this code is reached, the program will abort
Mike Stump11289f42009-09-09 15:08:12 +00002627 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2628 CastExpr::CK_Unknown, DRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002629 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002630 SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002631
Steve Narofff36987c2007-11-04 22:37:50 +00002632 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002633 QualType castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002634 &ArgTypes[0], ArgTypes.size(),
Steve Naroff327f0f42008-03-18 02:02:04 +00002635 // If we don't have a method decl, force a variadic cast.
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002636 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true, 0);
Steve Narofff36987c2007-11-04 22:37:50 +00002637 castType = Context->getPointerType(castType);
Mike Stump11289f42009-09-09 15:08:12 +00002638 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown, cast,
2639 castType, SourceLocation(),
Anders Carlssona2615922009-07-31 00:48:10 +00002640 SourceLocation());
Steve Narofff36987c2007-11-04 22:37:50 +00002641
2642 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002643 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002644
John McCall9dd450b2009-09-21 23:43:11 +00002645 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002646 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002647 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002648 FT->getResultType(), SourceLocation());
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002649 Stmt *ReplacingStmt = CE;
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002650 if (MsgSendStretFlavor) {
2651 // We have the method which returns a struct/union. Must also generate
2652 // call to objc_msgSend_stret and hang both varieties on a conditional
2653 // expression which dictate which one to envoke depending on size of
2654 // method's return type.
Mike Stump11289f42009-09-09 15:08:12 +00002655
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002656 // Create a reference to the objc_msgSend_stret() declaration.
Mike Stump11289f42009-09-09 15:08:12 +00002657 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor, msgSendType,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002658 SourceLocation());
2659 // Need to cast objc_msgSend_stret to "void *" (see above comment).
Mike Stump11289f42009-09-09 15:08:12 +00002660 cast = new (Context) CStyleCastExpr(Context->getPointerType(Context->VoidTy),
2661 CastExpr::CK_Unknown, STDRE,
Douglas Gregore200adc2008-10-27 19:41:14 +00002662 Context->getPointerType(Context->VoidTy),
Steve Naroffc989a7b2008-11-03 23:29:32 +00002663 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002664 // Now do the "normal" pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00002665 castType = Context->getFunctionType(returnType,
Fariborz Jahanian227c0d12007-12-06 19:49:56 +00002666 &ArgTypes[0], ArgTypes.size(),
Argyrios Kyrtzidis22a37352008-10-26 16:43:14 +00002667 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false, 0);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002668 castType = Context->getPointerType(castType);
Anders Carlssona2615922009-07-31 00:48:10 +00002669 cast = new (Context) CStyleCastExpr(castType, CastExpr::CK_Unknown,
2670 cast, castType, SourceLocation(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002671
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002672 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00002673 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
Mike Stump11289f42009-09-09 15:08:12 +00002674
John McCall9dd450b2009-09-21 23:43:11 +00002675 FT = msgSendType->getAs<FunctionType>();
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002676 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
Mike Stump11289f42009-09-09 15:08:12 +00002677 MsgExprs.size(),
Ted Kremenekd7b4f402009-02-09 20:51:47 +00002678 FT->getResultType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002679
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002680 // Build sizeof(returnType)
Mike Stump11289f42009-09-09 15:08:12 +00002681 SizeOfAlignOfExpr *sizeofExpr = new (Context) SizeOfAlignOfExpr(true,
John McCallbcd03502009-12-07 02:54:59 +00002682 Context->getTrivialTypeSourceInfo(returnType),
Sebastian Redl6f282892008-11-11 17:56:53 +00002683 Context->getSizeType(),
2684 SourceLocation(), SourceLocation());
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002685 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2686 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2687 // For X86 it is more complicated and some kind of target specific routine
2688 // is needed to decide what to do.
Mike Stump11289f42009-09-09 15:08:12 +00002689 unsigned IntSize =
Chris Lattner37e05872008-03-05 18:54:05 +00002690 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
Mike Stump11289f42009-09-09 15:08:12 +00002691 IntegerLiteral *limit = new (Context) IntegerLiteral(llvm::APInt(IntSize, 8),
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002692 Context->IntTy,
2693 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002694 BinaryOperator *lessThanExpr = new (Context) BinaryOperator(sizeofExpr, limit,
2695 BinaryOperator::LE,
2696 Context->IntTy,
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002697 SourceLocation());
2698 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
Mike Stump11289f42009-09-09 15:08:12 +00002699 ConditionalOperator *CondExpr =
Douglas Gregor7e112b02009-08-26 14:37:04 +00002700 new (Context) ConditionalOperator(lessThanExpr,
2701 SourceLocation(), CE,
2702 SourceLocation(), STCE, returnType);
Ted Kremenek5a201952009-02-07 01:47:29 +00002703 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(), CondExpr);
Fariborz Jahanian9e7b8482007-12-03 19:17:29 +00002704 }
Mike Stump11289f42009-09-09 15:08:12 +00002705 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002706 return ReplacingStmt;
2707}
2708
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002709Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002710 Stmt *ReplacingStmt = SynthMessageExpr(Exp);
Mike Stump11289f42009-09-09 15:08:12 +00002711
Steve Naroff574440f2007-10-24 22:48:43 +00002712 // Now do the actual rewrite.
Chris Lattner2e0d2602008-01-31 19:37:57 +00002713 ReplaceStmt(Exp, ReplacingStmt);
Mike Stump11289f42009-09-09 15:08:12 +00002714
2715 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Fariborz Jahanian965a8962008-01-08 22:06:28 +00002716 return ReplacingStmt;
Steve Naroffdb1ab1c2007-10-23 23:50:29 +00002717}
2718
Steve Naroffd9803712009-04-29 16:37:50 +00002719// typedef struct objc_object Protocol;
2720QualType RewriteObjC::getProtocolType() {
2721 if (!ProtocolTypeDecl) {
John McCallbcd03502009-12-07 02:54:59 +00002722 TypeSourceInfo *TInfo
2723 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
Steve Naroffd9803712009-04-29 16:37:50 +00002724 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
Mike Stump11289f42009-09-09 15:08:12 +00002725 SourceLocation(),
Steve Naroffd9803712009-04-29 16:37:50 +00002726 &Context->Idents.get("Protocol"),
John McCallbcd03502009-12-07 02:54:59 +00002727 TInfo);
Steve Naroffd9803712009-04-29 16:37:50 +00002728 }
2729 return Context->getTypeDeclType(ProtocolTypeDecl);
2730}
2731
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002732/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
Steve Naroffd9803712009-04-29 16:37:50 +00002733/// a synthesized/forward data reference (to the protocol's metadata).
2734/// The forward references (and metadata) are generated in
2735/// RewriteObjC::HandleTranslationUnit().
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002736Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Steve Naroffd9803712009-04-29 16:37:50 +00002737 std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
2738 IdentifierInfo *ID = &Context->Idents.get(Name);
Mike Stump11289f42009-09-09 15:08:12 +00002739 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
Douglas Gregored6c7442009-11-23 11:41:28 +00002740 ID, getProtocolType(), 0, VarDecl::Extern);
Steve Naroffd9803712009-04-29 16:37:50 +00002741 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, getProtocolType(), SourceLocation());
2742 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UnaryOperator::AddrOf,
2743 Context->getPointerType(DRE->getType()),
2744 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00002745 CastExpr *castExpr = new (Context) CStyleCastExpr(DerefExpr->getType(),
2746 CastExpr::CK_Unknown,
2747 DerefExpr, DerefExpr->getType(),
Steve Naroffd9803712009-04-29 16:37:50 +00002748 SourceLocation(), SourceLocation());
2749 ReplaceStmt(Exp, castExpr);
2750 ProtocolExprDecls.insert(Exp->getProtocol());
Mike Stump11289f42009-09-09 15:08:12 +00002751 // delete Exp; leak for now, see RewritePropertySetter() usage for more info.
Steve Naroffd9803712009-04-29 16:37:50 +00002752 return castExpr;
Mike Stump11289f42009-09-09 15:08:12 +00002753
Fariborz Jahanian33c0e812007-12-07 18:47:10 +00002754}
2755
Mike Stump11289f42009-09-09 15:08:12 +00002756bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002757 const char *endBuf) {
2758 while (startBuf < endBuf) {
2759 if (*startBuf == '#') {
2760 // Skip whitespace.
2761 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
2762 ;
2763 if (!strncmp(startBuf, "if", strlen("if")) ||
2764 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
2765 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
2766 !strncmp(startBuf, "define", strlen("define")) ||
2767 !strncmp(startBuf, "undef", strlen("undef")) ||
2768 !strncmp(startBuf, "else", strlen("else")) ||
2769 !strncmp(startBuf, "elif", strlen("elif")) ||
2770 !strncmp(startBuf, "endif", strlen("endif")) ||
2771 !strncmp(startBuf, "pragma", strlen("pragma")) ||
2772 !strncmp(startBuf, "include", strlen("include")) ||
2773 !strncmp(startBuf, "import", strlen("import")) ||
2774 !strncmp(startBuf, "include_next", strlen("include_next")))
2775 return true;
2776 }
2777 startBuf++;
2778 }
2779 return false;
2780}
2781
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002782/// SynthesizeObjCInternalStruct - Rewrite one internal struct corresponding to
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002783/// an objective-c class with ivars.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00002784void RewriteObjC::SynthesizeObjCInternalStruct(ObjCInterfaceDecl *CDecl,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002785 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002786 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
Mike Stump11289f42009-09-09 15:08:12 +00002787 assert(CDecl->getNameAsCString() &&
Douglas Gregor77324f32008-11-17 14:58:09 +00002788 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002789 // Do not synthesize more than once.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002790 if (ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanianc3cda762007-10-31 23:08:24 +00002791 return;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002792 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002793 int NumIvars = CDecl->ivar_size();
Steve Naroffdde78982007-11-14 19:25:57 +00002794 SourceLocation LocStart = CDecl->getLocStart();
2795 SourceLocation LocEnd = CDecl->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00002796
Steve Naroffdde78982007-11-14 19:25:57 +00002797 const char *startBuf = SM->getCharacterData(LocStart);
2798 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00002799
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002800 // If no ivars and no root or if its root, directly or indirectly,
2801 // have no ivars (thus not synthesized) then no need to synthesize this class.
Chris Lattner8d1c04f2008-03-16 21:08:55 +00002802 if ((CDecl->isForwardDecl() || NumIvars == 0) &&
2803 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
Chris Lattner184e65d2009-04-14 23:22:57 +00002804 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Chris Lattner9cc55f52008-01-31 19:51:04 +00002805 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002806 return;
2807 }
Mike Stump11289f42009-09-09 15:08:12 +00002808
2809 // FIXME: This has potential of causing problem. If
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002810 // SynthesizeObjCInternalStruct is ever called recursively.
Fariborz Jahaniana883d6e2007-11-26 19:52:57 +00002811 Result += "\nstruct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002812 Result += CDecl->getNameAsString();
Steve Naroffa1e115e2008-03-10 23:16:54 +00002813 if (LangOpts.Microsoft)
2814 Result += "_IMPL";
Steve Naroffdc5b6b22008-03-12 00:25:36 +00002815
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002816 if (NumIvars > 0) {
Steve Naroffdde78982007-11-14 19:25:57 +00002817 const char *cursor = strchr(startBuf, '{');
Mike Stump11289f42009-09-09 15:08:12 +00002818 assert((cursor && endBuf)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002819 && "SynthesizeObjCInternalStruct - malformed @interface");
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002820 // If the buffer contains preprocessor directives, we do more fine-grained
2821 // rewrites. This is intended to fix code that looks like (which occurs in
2822 // NSURL.h, for example):
2823 //
2824 // #ifdef XYZ
2825 // @interface Foo : NSObject
2826 // #else
2827 // @interface FooBar : NSObject
2828 // #endif
2829 // {
2830 // int i;
2831 // }
2832 // @end
2833 //
2834 // This clause is segregated to avoid breaking the common case.
2835 if (BufferContainsPPDirectives(startBuf, cursor)) {
Mike Stump11289f42009-09-09 15:08:12 +00002836 SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002837 CDecl->getClassLoc();
2838 const char *endHeader = SM->getCharacterData(L);
Chris Lattner184e65d2009-04-14 23:22:57 +00002839 endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002840
Chris Lattnerf5b77512009-02-20 18:18:36 +00002841 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002842 // advance to the end of the referenced protocols.
2843 while (endHeader < cursor && *endHeader != '>') endHeader++;
2844 endHeader++;
2845 }
2846 // rewrite the original header
2847 ReplaceText(LocStart, endHeader-startBuf, Result.c_str(), Result.size());
2848 } else {
2849 // rewrite the original header *without* disturbing the '{'
Steve Naroffb0e33902009-12-04 21:36:32 +00002850 ReplaceText(LocStart, cursor-startBuf, Result.c_str(), Result.size());
Steve Naroffcd92aeb2008-05-31 14:15:04 +00002851 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002852 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Steve Naroffdde78982007-11-14 19:25:57 +00002853 Result = "\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002854 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002855 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002856 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002857 Result += "_IVARS;\n";
Mike Stump11289f42009-09-09 15:08:12 +00002858
Steve Naroffdde78982007-11-14 19:25:57 +00002859 // insert the super class structure definition.
Chris Lattner1780a852008-01-31 19:42:41 +00002860 SourceLocation OnePastCurly =
2861 LocStart.getFileLocWithOffset(cursor-startBuf+1);
2862 InsertText(OnePastCurly, Result.c_str(), Result.size());
Steve Naroffdde78982007-11-14 19:25:57 +00002863 }
2864 cursor++; // past '{'
Mike Stump11289f42009-09-09 15:08:12 +00002865
Steve Naroffdde78982007-11-14 19:25:57 +00002866 // Now comment out any visibility specifiers.
2867 while (cursor < endBuf) {
2868 if (*cursor == '@') {
2869 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner174a8252007-11-14 22:57:51 +00002870 // Skip whitespace.
2871 for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; ++cursor)
2872 /*scan*/;
2873
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002874 // FIXME: presence of @public, etc. inside comment results in
2875 // this transformation as well, which is still correct c-code.
Steve Naroffdde78982007-11-14 19:25:57 +00002876 if (!strncmp(cursor, "public", strlen("public")) ||
2877 !strncmp(cursor, "private", strlen("private")) ||
Steve Naroffaf91b9a2008-04-04 22:34:24 +00002878 !strncmp(cursor, "package", strlen("package")) ||
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002879 !strncmp(cursor, "protected", strlen("protected")))
Chris Lattner1780a852008-01-31 19:42:41 +00002880 InsertText(atLoc, "// ", 3);
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002881 }
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002882 // FIXME: If there are cases where '<' is used in ivar declaration part
2883 // of user code, then scan the ivar list and use needToScanForQualifiers
2884 // for type checking.
2885 else if (*cursor == '<') {
2886 SourceLocation atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002887 InsertText(atLoc, "/* ", 3);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002888 cursor = strchr(cursor, '>');
2889 cursor++;
2890 atLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
Chris Lattner1780a852008-01-31 19:42:41 +00002891 InsertText(atLoc, " */", 3);
Steve Naroff295570a2008-10-30 12:09:33 +00002892 } else if (*cursor == '^') { // rewrite block specifier.
2893 SourceLocation caretLoc = LocStart.getFileLocWithOffset(cursor-startBuf);
2894 ReplaceText(caretLoc, 1, "*", 1);
Fariborz Jahanianc6225532007-11-14 22:26:25 +00002895 }
Steve Naroffdde78982007-11-14 19:25:57 +00002896 cursor++;
Fariborz Jahanianaff228df2007-10-31 17:29:28 +00002897 }
Steve Naroffdde78982007-11-14 19:25:57 +00002898 // Don't forget to add a ';'!!
Chris Lattner1780a852008-01-31 19:42:41 +00002899 InsertText(LocEnd.getFileLocWithOffset(1), ";", 1);
Steve Naroffdde78982007-11-14 19:25:57 +00002900 } else { // we don't have any instance variables - insert super struct.
Chris Lattner184e65d2009-04-14 23:22:57 +00002901 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
Steve Naroffdde78982007-11-14 19:25:57 +00002902 Result += " {\n struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002903 Result += RCDecl->getNameAsString();
Steve Naroff9f33bd22008-03-12 21:09:20 +00002904 Result += "_IMPL ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00002905 Result += RCDecl->getNameAsString();
Steve Naroffffb5f9a2008-03-12 21:22:52 +00002906 Result += "_IVARS;\n};\n";
Chris Lattner9cc55f52008-01-31 19:51:04 +00002907 ReplaceText(LocStart, endBuf-startBuf, Result.c_str(), Result.size());
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002908 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002909 // Mark this struct as having been generated.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002910 if (!ObjCSynthesizedStructs.insert(CDecl))
Steve Naroff13e74872008-05-06 18:26:51 +00002911 assert(false && "struct already synthesize- SynthesizeObjCInternalStruct");
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00002912}
2913
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002914// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002915/// class methods.
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002916template<typename MethodIterator>
2917void RewriteObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
2918 MethodIterator MethodEnd,
Fariborz Jahanian3df412a2007-10-25 00:14:44 +00002919 bool IsInstanceMethod,
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002920 const char *prefix,
Chris Lattner211f8b82007-10-25 17:07:24 +00002921 const char *ClassName,
2922 std::string &Result) {
Chris Lattner31bc07e2007-12-12 07:46:12 +00002923 if (MethodBegin == MethodEnd) return;
Mike Stump11289f42009-09-09 15:08:12 +00002924
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002925 static bool objc_impl_method = false;
Chris Lattner31bc07e2007-12-12 07:46:12 +00002926 if (!objc_impl_method) {
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002927 /* struct _objc_method {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002928 SEL _cmd;
2929 char *method_types;
2930 void *_imp;
2931 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002932 */
Chris Lattner211f8b82007-10-25 17:07:24 +00002933 Result += "\nstruct _objc_method {\n";
2934 Result += "\tSEL _cmd;\n";
2935 Result += "\tchar *method_types;\n";
2936 Result += "\tvoid *_imp;\n";
2937 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00002938
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002939 objc_impl_method = true;
Fariborz Jahanian74a1cfa2007-10-19 00:36:46 +00002940 }
Mike Stump11289f42009-09-09 15:08:12 +00002941
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002942 // Build _objc_method_list for class's methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00002943
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002944 /* struct {
2945 struct _objc_method_list *next_method;
2946 int method_count;
2947 struct _objc_method method_list[];
2948 }
2949 */
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002950 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002951 Result += "\nstatic struct {\n";
2952 Result += "\tstruct _objc_method_list *next_method;\n";
2953 Result += "\tint method_count;\n";
2954 Result += "\tstruct _objc_method method_list[";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002955 Result += utostr(NumMethods);
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002956 Result += "];\n} _OBJC_";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002957 Result += prefix;
2958 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
2959 Result += "_METHODS_";
2960 Result += ClassName;
Steve Naroffb327e492008-03-12 17:18:30 +00002961 Result += " __attribute__ ((used, section (\"__OBJC, __";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002962 Result += IsInstanceMethod ? "inst" : "cls";
2963 Result += "_meth\")))= ";
Douglas Gregor29bd76f2009-04-23 01:02:12 +00002964 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00002965
Chris Lattner31bc07e2007-12-12 07:46:12 +00002966 Result += "\t,{{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002967 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Chris Lattner31bc07e2007-12-12 07:46:12 +00002968 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002969 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Chris Lattner31bc07e2007-12-12 07:46:12 +00002970 Result += "\", \"";
2971 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002972 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002973 Result += MethodInternalNames[*MethodBegin];
2974 Result += "}\n";
2975 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
2976 Result += "\t ,{(SEL)\"";
Chris Lattnere4b95692008-11-24 03:33:13 +00002977 Result += (*MethodBegin)->getSelector().getAsString().c_str();
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002978 std::string MethodTypeString;
Ted Kremenek1b0ea822008-01-07 19:49:32 +00002979 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
Fariborz Jahanian797f24c2007-10-29 22:57:28 +00002980 Result += "\", \"";
2981 Result += MethodTypeString;
Steve Naroffc5b9cc72008-03-11 00:12:29 +00002982 Result += "\", (void *)";
Chris Lattner31bc07e2007-12-12 07:46:12 +00002983 Result += MethodInternalNames[*MethodBegin];
Fariborz Jahanian56338352007-11-13 21:02:00 +00002984 Result += "}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002985 }
Chris Lattner31bc07e2007-12-12 07:46:12 +00002986 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00002987}
2988
Steve Naroffd9803712009-04-29 16:37:50 +00002989/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Chris Lattner390d39a2008-07-21 21:32:27 +00002990void RewriteObjC::
Steve Naroffd9803712009-04-29 16:37:50 +00002991RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl, const char *prefix,
2992 const char *ClassName, std::string &Result) {
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00002993 static bool objc_protocol_methods = false;
Steve Naroffd9803712009-04-29 16:37:50 +00002994
2995 // Output struct protocol_methods holder of method selector and type.
2996 if (!objc_protocol_methods && !PDecl->isForwardDecl()) {
2997 /* struct protocol_methods {
2998 SEL _cmd;
2999 char *method_types;
3000 }
3001 */
3002 Result += "\nstruct _protocol_methods {\n";
3003 Result += "\tstruct objc_selector *_cmd;\n";
3004 Result += "\tchar *method_types;\n";
3005 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003006
Steve Naroffd9803712009-04-29 16:37:50 +00003007 objc_protocol_methods = true;
3008 }
3009 // Do not synthesize the protocol more than once.
3010 if (ObjCSynthesizedProtocols.count(PDecl))
3011 return;
Mike Stump11289f42009-09-09 15:08:12 +00003012
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003013 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
3014 unsigned NumMethods = std::distance(PDecl->instmeth_begin(),
3015 PDecl->instmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003016 /* struct _objc_protocol_method_list {
3017 int protocol_method_count;
3018 struct protocol_methods protocols[];
3019 }
Steve Naroff251084d2008-03-12 01:06:30 +00003020 */
Steve Naroffd9803712009-04-29 16:37:50 +00003021 Result += "\nstatic struct {\n";
3022 Result += "\tint protocol_method_count;\n";
3023 Result += "\tstruct _protocol_methods protocol_methods[";
3024 Result += utostr(NumMethods);
3025 Result += "];\n} _OBJC_PROTOCOL_INSTANCE_METHODS_";
3026 Result += PDecl->getNameAsString();
3027 Result += " __attribute__ ((used, section (\"__OBJC, __cat_inst_meth\")))= "
3028 "{\n\t" + utostr(NumMethods) + "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003029
Steve Naroffd9803712009-04-29 16:37:50 +00003030 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003031 for (ObjCProtocolDecl::instmeth_iterator
3032 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003033 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003034 if (I == PDecl->instmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003035 Result += "\t ,{{(struct objc_selector *)\"";
3036 else
3037 Result += "\t ,{(struct objc_selector *)\"";
3038 Result += (*I)->getSelector().getAsString().c_str();
3039 std::string MethodTypeString;
3040 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3041 Result += "\", \"";
3042 Result += MethodTypeString;
3043 Result += "\"}\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003044 }
Steve Naroffd9803712009-04-29 16:37:50 +00003045 Result += "\t }\n};\n";
3046 }
Mike Stump11289f42009-09-09 15:08:12 +00003047
Steve Naroffd9803712009-04-29 16:37:50 +00003048 // Output class methods declared in this protocol.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003049 unsigned NumMethods = std::distance(PDecl->classmeth_begin(),
3050 PDecl->classmeth_end());
Steve Naroffd9803712009-04-29 16:37:50 +00003051 if (NumMethods > 0) {
3052 /* struct _objc_protocol_method_list {
3053 int protocol_method_count;
3054 struct protocol_methods protocols[];
3055 }
3056 */
3057 Result += "\nstatic struct {\n";
3058 Result += "\tint protocol_method_count;\n";
3059 Result += "\tstruct _protocol_methods protocol_methods[";
3060 Result += utostr(NumMethods);
3061 Result += "];\n} _OBJC_PROTOCOL_CLASS_METHODS_";
3062 Result += PDecl->getNameAsString();
3063 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3064 "{\n\t";
3065 Result += utostr(NumMethods);
3066 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003067
Steve Naroffd9803712009-04-29 16:37:50 +00003068 // Output instance methods declared in this protocol.
Mike Stump11289f42009-09-09 15:08:12 +00003069 for (ObjCProtocolDecl::classmeth_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003070 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
Steve Naroffd9803712009-04-29 16:37:50 +00003071 I != E; ++I) {
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003072 if (I == PDecl->classmeth_begin())
Steve Naroffd9803712009-04-29 16:37:50 +00003073 Result += "\t ,{{(struct objc_selector *)\"";
3074 else
3075 Result += "\t ,{(struct objc_selector *)\"";
3076 Result += (*I)->getSelector().getAsString().c_str();
3077 std::string MethodTypeString;
3078 Context->getObjCEncodingForMethodDecl((*I), MethodTypeString);
3079 Result += "\", \"";
3080 Result += MethodTypeString;
3081 Result += "\"}\n";
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003082 }
Steve Naroffd9803712009-04-29 16:37:50 +00003083 Result += "\t }\n};\n";
3084 }
3085
3086 // Output:
3087 /* struct _objc_protocol {
3088 // Objective-C 1.0 extensions
3089 struct _objc_protocol_extension *isa;
3090 char *protocol_name;
3091 struct _objc_protocol **protocol_list;
3092 struct _objc_protocol_method_list *instance_methods;
3093 struct _objc_protocol_method_list *class_methods;
Mike Stump11289f42009-09-09 15:08:12 +00003094 };
Steve Naroffd9803712009-04-29 16:37:50 +00003095 */
3096 static bool objc_protocol = false;
3097 if (!objc_protocol) {
3098 Result += "\nstruct _objc_protocol {\n";
3099 Result += "\tstruct _objc_protocol_extension *isa;\n";
3100 Result += "\tchar *protocol_name;\n";
3101 Result += "\tstruct _objc_protocol **protocol_list;\n";
3102 Result += "\tstruct _objc_protocol_method_list *instance_methods;\n";
3103 Result += "\tstruct _objc_protocol_method_list *class_methods;\n";
Chris Lattner388f6e92008-07-21 21:33:21 +00003104 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003105
Steve Naroffd9803712009-04-29 16:37:50 +00003106 objc_protocol = true;
Chris Lattner388f6e92008-07-21 21:33:21 +00003107 }
Mike Stump11289f42009-09-09 15:08:12 +00003108
Steve Naroffd9803712009-04-29 16:37:50 +00003109 Result += "\nstatic struct _objc_protocol _OBJC_PROTOCOL_";
3110 Result += PDecl->getNameAsString();
3111 Result += " __attribute__ ((used, section (\"__OBJC, __protocol\")))= "
3112 "{\n\t0, \"";
3113 Result += PDecl->getNameAsString();
3114 Result += "\", 0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003115 if (PDecl->instmeth_begin() != PDecl->instmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003116 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
3117 Result += PDecl->getNameAsString();
3118 Result += ", ";
3119 }
3120 else
3121 Result += "0, ";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003122 if (PDecl->classmeth_begin() != PDecl->classmeth_end()) {
Steve Naroffd9803712009-04-29 16:37:50 +00003123 Result += "(struct _objc_protocol_method_list *)&_OBJC_PROTOCOL_CLASS_METHODS_";
3124 Result += PDecl->getNameAsString();
3125 Result += "\n";
3126 }
3127 else
3128 Result += "0\n";
3129 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003130
Steve Naroffd9803712009-04-29 16:37:50 +00003131 // Mark this protocol as having been generated.
3132 if (!ObjCSynthesizedProtocols.insert(PDecl))
3133 assert(false && "protocol already synthesized");
3134
3135}
3136
3137void RewriteObjC::
3138RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Protocols,
3139 const char *prefix, const char *ClassName,
3140 std::string &Result) {
3141 if (Protocols.empty()) return;
Mike Stump11289f42009-09-09 15:08:12 +00003142
Steve Naroffd9803712009-04-29 16:37:50 +00003143 for (unsigned i = 0; i != Protocols.size(); i++)
3144 RewriteObjCProtocolMetaData(Protocols[i], prefix, ClassName, Result);
3145
Chris Lattner388f6e92008-07-21 21:33:21 +00003146 // Output the top lovel protocol meta-data for the class.
3147 /* struct _objc_protocol_list {
3148 struct _objc_protocol_list *next;
3149 int protocol_count;
3150 struct _objc_protocol *class_protocols[];
3151 }
3152 */
3153 Result += "\nstatic struct {\n";
3154 Result += "\tstruct _objc_protocol_list *next;\n";
3155 Result += "\tint protocol_count;\n";
3156 Result += "\tstruct _objc_protocol *class_protocols[";
3157 Result += utostr(Protocols.size());
3158 Result += "];\n} _OBJC_";
3159 Result += prefix;
3160 Result += "_PROTOCOLS_";
3161 Result += ClassName;
3162 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
3163 "{\n\t0, ";
3164 Result += utostr(Protocols.size());
3165 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003166
Chris Lattner388f6e92008-07-21 21:33:21 +00003167 Result += "\t,{&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003168 Result += Protocols[0]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003169 Result += " \n";
Mike Stump11289f42009-09-09 15:08:12 +00003170
Chris Lattner388f6e92008-07-21 21:33:21 +00003171 for (unsigned i = 1; i != Protocols.size(); i++) {
3172 Result += "\t ,&_OBJC_PROTOCOL_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003173 Result += Protocols[i]->getNameAsString();
Chris Lattner388f6e92008-07-21 21:33:21 +00003174 Result += "\n";
3175 }
3176 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003177}
3178
Steve Naroffd9803712009-04-29 16:37:50 +00003179
Mike Stump11289f42009-09-09 15:08:12 +00003180/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003181/// implementation.
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003182void RewriteObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003183 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003184 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003185 // Find category declaration for this implementation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003186 ObjCCategoryDecl *CDecl;
Mike Stump11289f42009-09-09 15:08:12 +00003187 for (CDecl = ClassDecl->getCategoryList(); CDecl;
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003188 CDecl = CDecl->getNextClassCategory())
3189 if (CDecl->getIdentifier() == IDecl->getIdentifier())
3190 break;
Mike Stump11289f42009-09-09 15:08:12 +00003191
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003192 std::string FullCategoryName = ClassDecl->getNameAsString();
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003193 FullCategoryName += '_';
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003194 FullCategoryName += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003195
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003196 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003197 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003198 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003199
3200 // If any of our property implementations have associated getters or
3201 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003202 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3203 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003204 Prop != PropEnd; ++Prop) {
3205 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3206 continue;
3207 if (!(*Prop)->getPropertyIvarDecl())
3208 continue;
3209 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3210 if (!PD)
3211 continue;
3212 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3213 InstanceMethods.push_back(Getter);
3214 if (PD->isReadOnly())
3215 continue;
3216 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3217 InstanceMethods.push_back(Setter);
3218 }
3219 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003220 true, "CATEGORY_", FullCategoryName.c_str(),
3221 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003222
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003223 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003224 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattnerb907c3f2007-12-23 01:40:15 +00003225 false, "CATEGORY_", FullCategoryName.c_str(),
3226 Result);
Mike Stump11289f42009-09-09 15:08:12 +00003227
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003228 // Protocols referenced in class declaration?
Fariborz Jahanian989e0392007-11-13 22:09:49 +00003229 // Null CDecl is case of a category implementation with no category interface
3230 if (CDecl)
Steve Naroffd9803712009-04-29 16:37:50 +00003231 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(), "CATEGORY",
3232 FullCategoryName.c_str(), Result);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003233 /* struct _objc_category {
3234 char *category_name;
3235 char *class_name;
3236 struct _objc_method_list *instance_methods;
3237 struct _objc_method_list *class_methods;
3238 struct _objc_protocol_list *protocols;
3239 // Objective-C 1.0 extensions
3240 uint32_t size; // sizeof (struct _objc_category)
Mike Stump11289f42009-09-09 15:08:12 +00003241 struct _objc_property_list *instance_properties; // category's own
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003242 // @property decl.
Mike Stump11289f42009-09-09 15:08:12 +00003243 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003244 */
Mike Stump11289f42009-09-09 15:08:12 +00003245
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003246 static bool objc_category = false;
3247 if (!objc_category) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003248 Result += "\nstruct _objc_category {\n";
3249 Result += "\tchar *category_name;\n";
3250 Result += "\tchar *class_name;\n";
3251 Result += "\tstruct _objc_method_list *instance_methods;\n";
3252 Result += "\tstruct _objc_method_list *class_methods;\n";
3253 Result += "\tstruct _objc_protocol_list *protocols;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003254 Result += "\tunsigned int size;\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003255 Result += "\tstruct _objc_property_list *instance_properties;\n";
3256 Result += "};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003257 objc_category = true;
Fariborz Jahanian6eafb032007-10-22 21:41:37 +00003258 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003259 Result += "\nstatic struct _objc_category _OBJC_CATEGORY_";
3260 Result += FullCategoryName;
Steve Naroffb327e492008-03-12 17:18:30 +00003261 Result += " __attribute__ ((used, section (\"__OBJC, __category\")))= {\n\t\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003262 Result += IDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003263 Result += "\"\n\t, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003264 Result += ClassDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003265 Result += "\"\n";
Mike Stump11289f42009-09-09 15:08:12 +00003266
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003267 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003268 Result += "\t, (struct _objc_method_list *)"
3269 "&_OBJC_CATEGORY_INSTANCE_METHODS_";
3270 Result += FullCategoryName;
3271 Result += "\n";
3272 }
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003273 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003274 Result += "\t, 0\n";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003275 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003276 Result += "\t, (struct _objc_method_list *)"
3277 "&_OBJC_CATEGORY_CLASS_METHODS_";
3278 Result += FullCategoryName;
3279 Result += "\n";
3280 }
3281 else
3282 Result += "\t, 0\n";
Mike Stump11289f42009-09-09 15:08:12 +00003283
Chris Lattnerf5b77512009-02-20 18:18:36 +00003284 if (CDecl && CDecl->protocol_begin() != CDecl->protocol_end()) {
Mike Stump11289f42009-09-09 15:08:12 +00003285 Result += "\t, (struct _objc_protocol_list *)&_OBJC_CATEGORY_PROTOCOLS_";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003286 Result += FullCategoryName;
3287 Result += "\n";
3288 }
3289 else
3290 Result += "\t, 0\n";
3291 Result += "\t, sizeof(struct _objc_category), 0\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003292}
3293
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003294/// SynthesizeIvarOffsetComputation - This rutine synthesizes computation of
3295/// ivar offset.
Mike Stump11289f42009-09-09 15:08:12 +00003296void RewriteObjC::SynthesizeIvarOffsetComputation(ObjCImplementationDecl *IDecl,
3297 ObjCIvarDecl *ivar,
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003298 std::string &Result) {
Steve Naroffde7d0f62008-07-16 18:22:22 +00003299 if (ivar->isBitField()) {
3300 // FIXME: The hack below doesn't work for bitfields. For now, we simply
3301 // place all bitfields at offset 0.
3302 Result += "0";
3303 } else {
3304 Result += "__OFFSETOFIVAR__(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003305 Result += IDecl->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003306 if (LangOpts.Microsoft)
3307 Result += "_IMPL";
3308 Result += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003309 Result += ivar->getNameAsString();
Steve Naroffde7d0f62008-07-16 18:22:22 +00003310 Result += ")";
3311 }
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003312}
3313
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003314//===----------------------------------------------------------------------===//
3315// Meta Data Emission
3316//===----------------------------------------------------------------------===//
3317
Steve Naroff1dc53ef2008-04-14 22:03:09 +00003318void RewriteObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003319 std::string &Result) {
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003320 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
Mike Stump11289f42009-09-09 15:08:12 +00003321
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003322 // Explictly declared @interface's are already synthesized.
Steve Naroffaac654a2009-04-20 20:09:33 +00003323 if (CDecl->isImplicitInterfaceDecl()) {
Mike Stump11289f42009-09-09 15:08:12 +00003324 // FIXME: Implementation of a class with no @interface (legacy) doese not
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003325 // produce correct synthesis as yet.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003326 SynthesizeObjCInternalStruct(CDecl, Result);
Fariborz Jahanian96502af2007-11-26 20:59:57 +00003327 }
Mike Stump11289f42009-09-09 15:08:12 +00003328
Chris Lattner30d23e82007-12-12 07:56:42 +00003329 // Build _objc_ivar_list metadata for classes ivars if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003330 unsigned NumIvars = !IDecl->ivar_empty()
Mike Stump11289f42009-09-09 15:08:12 +00003331 ? IDecl->ivar_size()
Chris Lattner8d1c04f2008-03-16 21:08:55 +00003332 : (CDecl ? CDecl->ivar_size() : 0);
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003333 if (NumIvars > 0) {
3334 static bool objc_ivar = false;
3335 if (!objc_ivar) {
3336 /* struct _objc_ivar {
3337 char *ivar_name;
3338 char *ivar_type;
3339 int ivar_offset;
Mike Stump11289f42009-09-09 15:08:12 +00003340 };
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003341 */
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003342 Result += "\nstruct _objc_ivar {\n";
3343 Result += "\tchar *ivar_name;\n";
3344 Result += "\tchar *ivar_type;\n";
3345 Result += "\tint ivar_offset;\n";
3346 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003347
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003348 objc_ivar = true;
3349 }
3350
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003351 /* struct {
3352 int ivar_count;
3353 struct _objc_ivar ivar_list[nIvars];
Mike Stump11289f42009-09-09 15:08:12 +00003354 };
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003355 */
Mike Stump11289f42009-09-09 15:08:12 +00003356 Result += "\nstatic struct {\n";
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003357 Result += "\tint ivar_count;\n";
3358 Result += "\tstruct _objc_ivar ivar_list[";
3359 Result += utostr(NumIvars);
3360 Result += "];\n} _OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003361 Result += IDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003362 Result += " __attribute__ ((used, section (\"__OBJC, __instance_vars\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003363 "{\n\t";
3364 Result += utostr(NumIvars);
3365 Result += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00003366
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003367 ObjCInterfaceDecl::ivar_iterator IVI, IVE;
Douglas Gregor5f662052009-04-23 03:23:08 +00003368 llvm::SmallVector<ObjCIvarDecl *, 8> IVars;
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003369 if (!IDecl->ivar_empty()) {
Mike Stump11289f42009-09-09 15:08:12 +00003370 for (ObjCImplementationDecl::ivar_iterator
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003371 IV = IDecl->ivar_begin(), IVEnd = IDecl->ivar_end();
Douglas Gregor5f662052009-04-23 03:23:08 +00003372 IV != IVEnd; ++IV)
3373 IVars.push_back(*IV);
3374 IVI = IVars.begin();
3375 IVE = IVars.end();
Chris Lattner30d23e82007-12-12 07:56:42 +00003376 } else {
3377 IVI = CDecl->ivar_begin();
3378 IVE = CDecl->ivar_end();
3379 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003380 Result += "\t,{{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003381 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003382 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003383 std::string TmpString, StrEncoding;
3384 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3385 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003386 Result += StrEncoding;
3387 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003388 SynthesizeIvarOffsetComputation(IDecl, *IVI, Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003389 Result += "}\n";
Chris Lattner30d23e82007-12-12 07:56:42 +00003390 for (++IVI; IVI != IVE; ++IVI) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003391 Result += "\t ,{\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003392 Result += (*IVI)->getNameAsString();
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003393 Result += "\", \"";
Steve Naroffd9803712009-04-29 16:37:50 +00003394 std::string TmpString, StrEncoding;
3395 Context->getObjCEncodingForType((*IVI)->getType(), TmpString, *IVI);
3396 QuoteDoublequotes(TmpString, StrEncoding);
Fariborz Jahanianbc275932007-10-29 17:16:25 +00003397 Result += StrEncoding;
3398 Result += "\", ";
Chris Lattner30d23e82007-12-12 07:56:42 +00003399 SynthesizeIvarOffsetComputation(IDecl, (*IVI), Result);
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003400 Result += "}\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003401 }
Mike Stump11289f42009-09-09 15:08:12 +00003402
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003403 Result += "\t }\n};\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003404 }
Mike Stump11289f42009-09-09 15:08:12 +00003405
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003406 // Build _objc_method_list for class's instance methods if needed
Mike Stump11289f42009-09-09 15:08:12 +00003407 llvm::SmallVector<ObjCMethodDecl *, 32>
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003408 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003409
3410 // If any of our property implementations have associated getters or
3411 // setters, produce metadata for them as well.
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003412 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
3413 PropEnd = IDecl->propimpl_end();
Douglas Gregor29bd76f2009-04-23 01:02:12 +00003414 Prop != PropEnd; ++Prop) {
3415 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
3416 continue;
3417 if (!(*Prop)->getPropertyIvarDecl())
3418 continue;
3419 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
3420 if (!PD)
3421 continue;
3422 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
3423 InstanceMethods.push_back(Getter);
3424 if (PD->isReadOnly())
3425 continue;
3426 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
3427 InstanceMethods.push_back(Setter);
3428 }
3429 RewriteObjCMethodsMetaData(InstanceMethods.begin(), InstanceMethods.end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003430 true, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003431
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003432 // Build _objc_method_list for class's class methods if needed
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003433 RewriteObjCMethodsMetaData(IDecl->classmeth_begin(), IDecl->classmeth_end(),
Chris Lattner86d7d912008-11-24 03:54:41 +00003434 false, "", IDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003435
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003436 // Protocols referenced in class declaration?
Steve Naroffd9803712009-04-29 16:37:50 +00003437 RewriteObjCProtocolListMetaData(CDecl->getReferencedProtocols(),
3438 "CLASS", CDecl->getNameAsCString(), Result);
Mike Stump11289f42009-09-09 15:08:12 +00003439
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003440 // Declaration of class/meta-class metadata
3441 /* struct _objc_class {
3442 struct _objc_class *isa; // or const char *root_class_name when metadata
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003443 const char *super_class_name;
3444 char *name;
3445 long version;
3446 long info;
3447 long instance_size;
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003448 struct _objc_ivar_list *ivars;
3449 struct _objc_method_list *methods;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003450 struct objc_cache *cache;
3451 struct objc_protocol_list *protocols;
3452 const char *ivar_layout;
3453 struct _objc_class_ext *ext;
Mike Stump11289f42009-09-09 15:08:12 +00003454 };
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003455 */
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003456 static bool objc_class = false;
3457 if (!objc_class) {
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003458 Result += "\nstruct _objc_class {\n";
3459 Result += "\tstruct _objc_class *isa;\n";
3460 Result += "\tconst char *super_class_name;\n";
3461 Result += "\tchar *name;\n";
3462 Result += "\tlong version;\n";
3463 Result += "\tlong info;\n";
3464 Result += "\tlong instance_size;\n";
3465 Result += "\tstruct _objc_ivar_list *ivars;\n";
3466 Result += "\tstruct _objc_method_list *methods;\n";
3467 Result += "\tstruct objc_cache *cache;\n";
3468 Result += "\tstruct _objc_protocol_list *protocols;\n";
3469 Result += "\tconst char *ivar_layout;\n";
3470 Result += "\tstruct _objc_class_ext *ext;\n";
3471 Result += "};\n";
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003472 objc_class = true;
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003473 }
Mike Stump11289f42009-09-09 15:08:12 +00003474
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003475 // Meta-class metadata generation.
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003476 ObjCInterfaceDecl *RootClass = 0;
3477 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003478 while (SuperClass) {
3479 RootClass = SuperClass;
3480 SuperClass = SuperClass->getSuperClass();
3481 }
3482 SuperClass = CDecl->getSuperClass();
Mike Stump11289f42009-09-09 15:08:12 +00003483
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003484 Result += "\nstatic struct _objc_class _OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003485 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003486 Result += " __attribute__ ((used, section (\"__OBJC, __meta_class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003487 "{\n\t(struct _objc_class *)\"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003488 Result += (RootClass ? RootClass->getNameAsString() : CDecl->getNameAsString());
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003489 Result += "\"";
3490
3491 if (SuperClass) {
3492 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003493 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003494 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003495 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003496 Result += "\"";
3497 }
3498 else {
3499 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003500 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003501 Result += "\"";
3502 }
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003503 // Set 'ivars' field for root class to 0. ObjC1 runtime does not use it.
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003504 // 'info' field is initialized to CLS_META(2) for metaclass
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003505 Result += ", 0,2, sizeof(struct _objc_class), 0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003506 if (IDecl->classmeth_begin() != IDecl->classmeth_end()) {
Steve Naroff0b844f02008-03-11 18:14:26 +00003507 Result += "\n\t, (struct _objc_method_list *)&_OBJC_CLASS_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003508 Result += IDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003509 Result += "\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003510 }
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003511 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003512 Result += ", 0\n";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003513 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003514 Result += "\t,0, (struct _objc_protocol_list *)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003515 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003516 Result += ",0,0\n";
3517 }
Fariborz Jahanian486f7182007-10-24 20:54:23 +00003518 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003519 Result += "\t,0,0,0,0\n";
3520 Result += "};\n";
Mike Stump11289f42009-09-09 15:08:12 +00003521
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003522 // class metadata generation.
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003523 Result += "\nstatic struct _objc_class _OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003524 Result += CDecl->getNameAsString();
Steve Naroffb327e492008-03-12 17:18:30 +00003525 Result += " __attribute__ ((used, section (\"__OBJC, __class\")))= "
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003526 "{\n\t&_OBJC_METACLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003527 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003528 if (SuperClass) {
3529 Result += ", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003530 Result += SuperClass->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003531 Result += "\", \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003532 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003533 Result += "\"";
3534 }
3535 else {
3536 Result += ", 0, \"";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003537 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003538 Result += "\"";
3539 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003540 // 'info' field is initialized to CLS_CLASS(1) for class
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003541 Result += ", 0,1";
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003542 if (!ObjCSynthesizedStructs.count(CDecl))
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003543 Result += ",0";
3544 else {
3545 // class has size. Must synthesize its size.
Fariborz Jahanian63ac80e2007-11-05 17:47:33 +00003546 Result += ",sizeof(struct ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003547 Result += CDecl->getNameAsString();
Steve Naroff14a07462008-03-10 23:33:22 +00003548 if (LangOpts.Microsoft)
3549 Result += "_IMPL";
Fariborz Jahanian801b6352007-10-26 23:09:28 +00003550 Result += ")";
3551 }
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003552 if (NumIvars > 0) {
Steve Naroff17978c42008-03-11 17:37:02 +00003553 Result += ", (struct _objc_ivar_list *)&_OBJC_INSTANCE_VARIABLES_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003554 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003555 Result += "\n\t";
3556 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003557 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003558 Result += ",0";
Argyrios Kyrtzidiscfbfe782009-06-30 02:36:12 +00003559 if (IDecl->instmeth_begin() != IDecl->instmeth_end()) {
Steve Naroffc5b9cc72008-03-11 00:12:29 +00003560 Result += ", (struct _objc_method_list *)&_OBJC_INSTANCE_METHODS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003561 Result += CDecl->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003562 Result += ", 0\n\t";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003563 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003564 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003565 Result += ",0,0";
Chris Lattnerf5b77512009-02-20 18:18:36 +00003566 if (CDecl->protocol_begin() != CDecl->protocol_end()) {
Steve Naroff251084d2008-03-12 01:06:30 +00003567 Result += ", (struct _objc_protocol_list*)&_OBJC_CLASS_PROTOCOLS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003568 Result += CDecl->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003569 Result += ", 0,0\n";
3570 }
Fariborz Jahanianf3d5a542007-10-23 18:53:48 +00003571 else
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003572 Result += ",0,0,0\n";
3573 Result += "};\n";
Fariborz Jahaniand752eae2007-10-23 00:02:02 +00003574}
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003575
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003576/// RewriteImplementations - This routine rewrites all method implementations
3577/// and emits meta-data.
3578
Steve Narofff8cfd162008-11-13 20:07:04 +00003579void RewriteObjC::RewriteImplementations() {
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003580 int ClsDefCount = ClassImplementation.size();
3581 int CatDefCount = CategoryImplementation.size();
Mike Stump11289f42009-09-09 15:08:12 +00003582
Fariborz Jahanian98ba6cd2007-11-13 19:21:13 +00003583 // Rewrite implemented methods
3584 for (int i = 0; i < ClsDefCount; i++)
3585 RewriteImplementationDecl(ClassImplementation[i]);
Mike Stump11289f42009-09-09 15:08:12 +00003586
Fariborz Jahanianc54d8462007-11-13 20:04:28 +00003587 for (int i = 0; i < CatDefCount; i++)
3588 RewriteImplementationDecl(CategoryImplementation[i]);
Steve Narofff8cfd162008-11-13 20:07:04 +00003589}
Mike Stump11289f42009-09-09 15:08:12 +00003590
Steve Narofff8cfd162008-11-13 20:07:04 +00003591void RewriteObjC::SynthesizeMetaDataIntoBuffer(std::string &Result) {
3592 int ClsDefCount = ClassImplementation.size();
3593 int CatDefCount = CategoryImplementation.size();
3594
Steve Naroff30ac2222008-05-07 21:23:49 +00003595 // This is needed for determining instance variable offsets.
Mike Stump11289f42009-09-09 15:08:12 +00003596 Result += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((int) &((TYPE *)0)->MEMBER)\n";
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003597 // For each implemented class, write out all its meta data.
Fariborz Jahanianc34409c2007-10-18 22:09:03 +00003598 for (int i = 0; i < ClsDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003599 RewriteObjCClassMetaData(ClassImplementation[i], Result);
Mike Stump11289f42009-09-09 15:08:12 +00003600
Fariborz Jahanianb2f525d2007-10-24 19:23:36 +00003601 // For each implemented category, write out all its meta data.
3602 for (int i = 0; i < CatDefCount; i++)
Ted Kremenek1b0ea822008-01-07 19:49:32 +00003603 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
Steve Naroffd9803712009-04-29 16:37:50 +00003604
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003605 // Write objc_symtab metadata
3606 /*
3607 struct _objc_symtab
3608 {
3609 long sel_ref_cnt;
3610 SEL *refs;
3611 short cls_def_cnt;
3612 short cat_def_cnt;
3613 void *defs[cls_def_cnt + cat_def_cnt];
Mike Stump11289f42009-09-09 15:08:12 +00003614 };
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003615 */
Mike Stump11289f42009-09-09 15:08:12 +00003616
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003617 Result += "\nstruct _objc_symtab {\n";
3618 Result += "\tlong sel_ref_cnt;\n";
3619 Result += "\tSEL *refs;\n";
3620 Result += "\tshort cls_def_cnt;\n";
3621 Result += "\tshort cat_def_cnt;\n";
3622 Result += "\tvoid *defs[" + utostr(ClsDefCount + CatDefCount)+ "];\n";
3623 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003624
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003625 Result += "static struct _objc_symtab "
Steve Naroffb327e492008-03-12 17:18:30 +00003626 "_OBJC_SYMBOLS __attribute__((used, section (\"__OBJC, __symbols\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003627 Result += "\t0, 0, " + utostr(ClsDefCount)
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003628 + ", " + utostr(CatDefCount) + "\n";
3629 for (int i = 0; i < ClsDefCount; i++) {
3630 Result += "\t,&_OBJC_CLASS_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003631 Result += ClassImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003632 Result += "\n";
3633 }
Mike Stump11289f42009-09-09 15:08:12 +00003634
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003635 for (int i = 0; i < CatDefCount; i++) {
3636 Result += "\t,&_OBJC_CATEGORY_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003637 Result += CategoryImplementation[i]->getClassInterface()->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003638 Result += "_";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003639 Result += CategoryImplementation[i]->getNameAsString();
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003640 Result += "\n";
3641 }
Mike Stump11289f42009-09-09 15:08:12 +00003642
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003643 Result += "};\n\n";
Mike Stump11289f42009-09-09 15:08:12 +00003644
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003645 // Write objc_module metadata
Mike Stump11289f42009-09-09 15:08:12 +00003646
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003647 /*
3648 struct _objc_module {
3649 long version;
3650 long size;
3651 const char *name;
3652 struct _objc_symtab *symtab;
3653 }
3654 */
Mike Stump11289f42009-09-09 15:08:12 +00003655
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003656 Result += "\nstruct _objc_module {\n";
3657 Result += "\tlong version;\n";
3658 Result += "\tlong size;\n";
3659 Result += "\tconst char *name;\n";
3660 Result += "\tstruct _objc_symtab *symtab;\n";
3661 Result += "};\n\n";
3662 Result += "static struct _objc_module "
Steve Naroffb327e492008-03-12 17:18:30 +00003663 "_OBJC_MODULES __attribute__ ((used, section (\"__OBJC, __module_info\")))= {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003664 Result += "\t" + utostr(OBJC_ABI_VERSION) +
Fariborz Jahanian99e96b02007-10-26 19:46:17 +00003665 ", sizeof(struct _objc_module), \"\", &_OBJC_SYMBOLS\n";
Fariborz Jahanian51f21822007-10-25 20:55:25 +00003666 Result += "};\n\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003667
3668 if (LangOpts.Microsoft) {
Steve Naroffd9803712009-04-29 16:37:50 +00003669 if (ProtocolExprDecls.size()) {
3670 Result += "#pragma section(\".objc_protocol$B\",long,read,write)\n";
3671 Result += "#pragma data_seg(push, \".objc_protocol$B\")\n";
Mike Stump11289f42009-09-09 15:08:12 +00003672 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00003673 E = ProtocolExprDecls.end(); I != E; ++I) {
3674 Result += "static struct _objc_protocol *_POINTER_OBJC_PROTOCOL_";
3675 Result += (*I)->getNameAsString();
3676 Result += " = &_OBJC_PROTOCOL_";
3677 Result += (*I)->getNameAsString();
3678 Result += ";\n";
3679 }
3680 Result += "#pragma data_seg(pop)\n\n";
3681 }
Steve Naroff945a3b12008-03-10 20:43:59 +00003682 Result += "#pragma section(\".objc_module_info$B\",long,read,write)\n";
Steve Naroffcab93d52008-05-07 00:06:16 +00003683 Result += "#pragma data_seg(push, \".objc_module_info$B\")\n";
Steve Naroff945a3b12008-03-10 20:43:59 +00003684 Result += "static struct _objc_module *_POINTER_OBJC_MODULES = ";
3685 Result += "&_OBJC_MODULES;\n";
3686 Result += "#pragma data_seg(pop)\n\n";
3687 }
Fariborz Jahanian93191af2007-10-18 19:23:00 +00003688}
Chris Lattnera7c19fe2007-10-16 22:36:42 +00003689
Steve Naroff677ab3a2008-10-27 17:20:55 +00003690std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3691 const char *funcName,
3692 std::string Tag) {
3693 const FunctionType *AFT = CE->getFunctionType();
3694 QualType RT = AFT->getResultType();
3695 std::string StructRef = "struct " + Tag;
3696 std::string S = "static " + RT.getAsString() + " __" +
3697 funcName + "_" + "block_func_" + utostr(i);
Argyrios Kyrtzidisc3b69ae2008-04-17 14:40:12 +00003698
Steve Naroff677ab3a2008-10-27 17:20:55 +00003699 BlockDecl *BD = CE->getBlockDecl();
Mike Stump11289f42009-09-09 15:08:12 +00003700
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003701 if (isa<FunctionNoProtoType>(AFT)) {
Mike Stump11289f42009-09-09 15:08:12 +00003702 // No user-supplied arguments. Still need to pass in a pointer to the
Steve Narofff26a1d42009-02-02 17:19:26 +00003703 // block (to reference imported block decl refs).
3704 S += "(" + StructRef + " *__cself)";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003705 } else if (BD->param_empty()) {
3706 S += "(" + StructRef + " *__cself)";
3707 } else {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00003708 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003709 assert(FT && "SynthesizeBlockFunc: No function proto");
3710 S += '(';
3711 // first add the implicit argument.
3712 S += StructRef + " *__cself, ";
3713 std::string ParamStr;
3714 for (BlockDecl::param_iterator AI = BD->param_begin(),
3715 E = BD->param_end(); AI != E; ++AI) {
3716 if (AI != BD->param_begin()) S += ", ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003717 ParamStr = (*AI)->getNameAsString();
Douglas Gregor7de59662009-05-29 20:38:28 +00003718 (*AI)->getType().getAsStringInternal(ParamStr, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003719 S += ParamStr;
3720 }
3721 if (FT->isVariadic()) {
3722 if (!BD->param_empty()) S += ", ";
3723 S += "...";
3724 }
3725 S += ')';
3726 }
3727 S += " {\n";
Mike Stump11289f42009-09-09 15:08:12 +00003728
Steve Naroff677ab3a2008-10-27 17:20:55 +00003729 // Create local declarations to avoid rewriting all closure decl ref exprs.
3730 // First, emit a declaration for all "by ref" decls.
Mike Stump11289f42009-09-09 15:08:12 +00003731 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003732 E = BlockByRefDecls.end(); I != E; ++I) {
3733 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003734 std::string Name = (*I)->getNameAsString();
Mike Stump11289f42009-09-09 15:08:12 +00003735 Context->getPointerType((*I)->getType()).getAsStringInternal(Name,
Douglas Gregor7de59662009-05-29 20:38:28 +00003736 Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003737 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
Mike Stump11289f42009-09-09 15:08:12 +00003738 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00003739 // Next, emit a declaration for all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003740 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003741 E = BlockByCopyDecls.end(); I != E; ++I) {
3742 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003743 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003744 // Handle nested closure invocation. For example:
3745 //
3746 // void (^myImportedClosure)(void);
3747 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003748 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003749 // void (^anotherClosure)(void);
3750 // anotherClosure = ^(void) {
3751 // myImportedClosure(); // import and invoke the closure
3752 // };
3753 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003754 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003755 S += "struct __block_impl *";
3756 else
Douglas Gregor7de59662009-05-29 20:38:28 +00003757 (*I)->getType().getAsStringInternal(Name, Context->PrintingPolicy);
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003758 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003759 }
3760 std::string RewrittenStr = RewrittenBlockExprs[CE];
3761 const char *cstr = RewrittenStr.c_str();
3762 while (*cstr++ != '{') ;
3763 S += cstr;
3764 S += "\n";
3765 return S;
3766}
Argyrios Kyrtzidis554a07b2008-06-09 23:19:58 +00003767
Steve Naroff677ab3a2008-10-27 17:20:55 +00003768std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3769 const char *funcName,
3770 std::string Tag) {
3771 std::string StructRef = "struct " + Tag;
3772 std::string S = "static void __";
Mike Stump11289f42009-09-09 15:08:12 +00003773
Steve Naroff677ab3a2008-10-27 17:20:55 +00003774 S += funcName;
3775 S += "_block_copy_" + utostr(i);
3776 S += "(" + StructRef;
3777 S += "*dst, " + StructRef;
3778 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003779 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003780 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003781 S += "_Block_object_assign((void*)&dst->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003782 S += (*I)->getNameAsString();
Steve Naroff5ac4eac2008-12-11 20:51:38 +00003783 S += ", (void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003784 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003785 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);}";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003786 }
3787 S += "\nstatic void __";
3788 S += funcName;
3789 S += "_block_dispose_" + utostr(i);
3790 S += "(" + StructRef;
3791 S += "*src) {";
Mike Stump11289f42009-09-09 15:08:12 +00003792 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003793 E = ImportedBlockDecls.end(); I != E; ++I) {
Steve Naroff61d879e2008-12-16 15:50:30 +00003794 S += "_Block_object_dispose((void*)src->";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003795 S += (*I)->getNameAsString();
Steve Naroff61d879e2008-12-16 15:50:30 +00003796 S += ", 3/*BLOCK_FIELD_IS_OBJECT*/);";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003797 }
Mike Stump11289f42009-09-09 15:08:12 +00003798 S += "}\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003799 return S;
3800}
3801
Steve Naroff30484702009-12-06 21:14:13 +00003802std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3803 std::string Desc) {
Steve Naroff295570a2008-10-30 12:09:33 +00003804 std::string S = "\nstruct " + Tag;
Steve Naroff677ab3a2008-10-27 17:20:55 +00003805 std::string Constructor = " " + Tag;
Mike Stump11289f42009-09-09 15:08:12 +00003806
Steve Naroff677ab3a2008-10-27 17:20:55 +00003807 S += " {\n struct __block_impl impl;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003808 S += " struct " + Desc;
3809 S += "* Desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003810
Steve Naroff30484702009-12-06 21:14:13 +00003811 Constructor += "(void *fp, "; // Invoke function pointer.
3812 Constructor += "struct " + Desc; // Descriptor pointer.
3813 Constructor += " *desc";
Mike Stump11289f42009-09-09 15:08:12 +00003814
Steve Naroff677ab3a2008-10-27 17:20:55 +00003815 if (BlockDeclRefs.size()) {
3816 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003817 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003818 E = BlockByCopyDecls.end(); I != E; ++I) {
3819 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003820 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003821 std::string ArgName = "_" + FieldName;
3822 // Handle nested closure invocation. For example:
3823 //
3824 // void (^myImportedBlock)(void);
3825 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003826 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003827 // void (^anotherBlock)(void);
3828 // anotherBlock = ^(void) {
3829 // myImportedBlock(); // import and invoke the closure
3830 // };
3831 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003832 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003833 S += "struct __block_impl *";
3834 Constructor += ", void *" + ArgName;
3835 } else {
Douglas Gregor7de59662009-05-29 20:38:28 +00003836 (*I)->getType().getAsStringInternal(FieldName, Context->PrintingPolicy);
3837 (*I)->getType().getAsStringInternal(ArgName, Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003838 Constructor += ", " + ArgName;
3839 }
3840 S += FieldName + ";\n";
3841 }
3842 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00003843 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003844 E = BlockByRefDecls.end(); I != E; ++I) {
3845 S += " ";
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003846 std::string FieldName = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003847 std::string ArgName = "_" + FieldName;
3848 // Handle nested closure invocation. For example:
3849 //
3850 // void (^myImportedBlock)(void);
3851 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
Mike Stump11289f42009-09-09 15:08:12 +00003852 //
Steve Naroff677ab3a2008-10-27 17:20:55 +00003853 // void (^anotherBlock)(void);
3854 // anotherBlock = ^(void) {
3855 // myImportedBlock(); // import and invoke the closure
3856 // };
3857 //
Steve Naroffa5c0db82008-12-11 21:05:33 +00003858 if (isTopLevelBlockPointerType((*I)->getType())) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00003859 S += "struct __block_impl *";
3860 Constructor += ", void *" + ArgName;
3861 } else {
Mike Stump11289f42009-09-09 15:08:12 +00003862 Context->getPointerType((*I)->getType()).getAsStringInternal(FieldName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003863 Context->PrintingPolicy);
Mike Stump11289f42009-09-09 15:08:12 +00003864 Context->getPointerType((*I)->getType()).getAsStringInternal(ArgName,
Douglas Gregor7de59662009-05-29 20:38:28 +00003865 Context->PrintingPolicy);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003866 Constructor += ", " + ArgName;
3867 }
3868 S += FieldName + "; // by ref\n";
3869 }
3870 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003871 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003872 if (GlobalVarDecl)
3873 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3874 else
3875 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003876 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003877
Steve Naroff30484702009-12-06 21:14:13 +00003878 Constructor += " Desc = desc;\n";
Mike Stump11289f42009-09-09 15:08:12 +00003879
Steve Naroff677ab3a2008-10-27 17:20:55 +00003880 // Initialize all "by copy" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003881 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003882 E = BlockByCopyDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003883 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003884 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003885 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003886 Constructor += Name + " = (struct __block_impl *)_";
3887 else
3888 Constructor += Name + " = _";
3889 Constructor += Name + ";\n";
3890 }
3891 // Initialize all "by ref" arguments.
Mike Stump11289f42009-09-09 15:08:12 +00003892 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00003893 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00003894 std::string Name = (*I)->getNameAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003895 Constructor += " ";
Steve Naroffa5c0db82008-12-11 21:05:33 +00003896 if (isTopLevelBlockPointerType((*I)->getType()))
Steve Naroff677ab3a2008-10-27 17:20:55 +00003897 Constructor += Name + " = (struct __block_impl *)_";
3898 else
3899 Constructor += Name + " = _";
3900 Constructor += Name + ";\n";
3901 }
3902 } else {
3903 // Finish writing the constructor.
Steve Naroff677ab3a2008-10-27 17:20:55 +00003904 Constructor += ", int flags=0) {\n";
Steve Naroffd9803712009-04-29 16:37:50 +00003905 if (GlobalVarDecl)
3906 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3907 else
3908 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
Steve Naroff30484702009-12-06 21:14:13 +00003909 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3910 Constructor += " Desc = desc;\n";
Steve Naroff677ab3a2008-10-27 17:20:55 +00003911 }
3912 Constructor += " ";
3913 Constructor += "}\n";
3914 S += Constructor;
3915 S += "};\n";
3916 return S;
3917}
3918
Steve Naroff30484702009-12-06 21:14:13 +00003919std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3920 std::string ImplTag, int i,
3921 const char *FunName,
3922 unsigned hasCopy) {
3923 std::string S = "\nstatic struct " + DescTag;
3924
3925 S += " {\n unsigned long reserved;\n";
3926 S += " unsigned long Block_size;\n";
3927 if (hasCopy) {
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00003928 S += " void (*copy)(struct ";
3929 S += ImplTag; S += "*, struct ";
3930 S += ImplTag; S += "*);\n";
3931
3932 S += " void (*dispose)(struct ";
3933 S += ImplTag; S += "*);\n";
Steve Naroff30484702009-12-06 21:14:13 +00003934 }
3935 S += "} ";
3936
3937 S += DescTag + "_DATA = { 0, sizeof(struct ";
3938 S += ImplTag + ")";
3939 if (hasCopy) {
3940 S += ", __" + std::string(FunName) + "_block_copy_" + utostr(i);
3941 S += ", __" + std::string(FunName) + "_block_dispose_" + utostr(i);
3942 }
3943 S += "};\n";
3944 return S;
3945}
3946
Steve Naroff677ab3a2008-10-27 17:20:55 +00003947void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3948 const char *FunName) {
3949 // Insert closures that were part of the function.
3950 for (unsigned i = 0; i < Blocks.size(); i++) {
3951
3952 CollectBlockDeclRefInfo(Blocks[i]);
3953
Steve Naroff30484702009-12-06 21:14:13 +00003954 std::string ImplTag = "__" + std::string(FunName) + "_block_impl_" + utostr(i);
3955 std::string DescTag = "__" + std::string(FunName) + "_block_desc_" + utostr(i);
Mike Stump11289f42009-09-09 15:08:12 +00003956
Steve Naroff30484702009-12-06 21:14:13 +00003957 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003958
3959 InsertText(FunLocStart, CI.c_str(), CI.size());
3960
Steve Naroff30484702009-12-06 21:14:13 +00003961 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
Mike Stump11289f42009-09-09 15:08:12 +00003962
Steve Naroff677ab3a2008-10-27 17:20:55 +00003963 InsertText(FunLocStart, CF.c_str(), CF.size());
3964
3965 if (ImportedBlockDecls.size()) {
Steve Naroff30484702009-12-06 21:14:13 +00003966 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
Steve Naroff677ab3a2008-10-27 17:20:55 +00003967 InsertText(FunLocStart, HF.c_str(), HF.size());
3968 }
Steve Naroff30484702009-12-06 21:14:13 +00003969 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3970 ImportedBlockDecls.size() > 0);
3971 InsertText(FunLocStart, BD.c_str(), BD.size());
Mike Stump11289f42009-09-09 15:08:12 +00003972
Steve Naroff677ab3a2008-10-27 17:20:55 +00003973 BlockDeclRefs.clear();
3974 BlockByRefDecls.clear();
3975 BlockByCopyDecls.clear();
3976 BlockCallExprs.clear();
3977 ImportedBlockDecls.clear();
3978 }
3979 Blocks.clear();
3980 RewrittenBlockExprs.clear();
3981}
3982
3983void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3984 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
Chris Lattner86d7d912008-11-24 03:54:41 +00003985 const char *FuncName = FD->getNameAsCString();
Mike Stump11289f42009-09-09 15:08:12 +00003986
Steve Naroff677ab3a2008-10-27 17:20:55 +00003987 SynthesizeBlockLiterals(FunLocStart, FuncName);
3988}
3989
3990void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
Steve Naroff295570a2008-10-30 12:09:33 +00003991 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3992 //SourceLocation FunLocStart = MD->getLocStart();
3993 // FIXME: This hack works around a bug in Rewrite.InsertText().
3994 SourceLocation FunLocStart = MD->getLocStart().getFileLocWithOffset(-1);
Chris Lattnere4b95692008-11-24 03:33:13 +00003995 std::string FuncName = MD->getSelector().getAsString();
Steve Naroff677ab3a2008-10-27 17:20:55 +00003996 // Convert colons to underscores.
3997 std::string::size_type loc = 0;
3998 while ((loc = FuncName.find(":", loc)) != std::string::npos)
3999 FuncName.replace(loc, 1, "_");
Mike Stump11289f42009-09-09 15:08:12 +00004000
Steve Naroff677ab3a2008-10-27 17:20:55 +00004001 SynthesizeBlockLiterals(FunLocStart, FuncName.c_str());
4002}
4003
4004void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
4005 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4006 CI != E; ++CI)
4007 if (*CI) {
4008 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4009 GetBlockDeclRefExprs(CBE->getBody());
4010 else
4011 GetBlockDeclRefExprs(*CI);
4012 }
4013 // Handle specific things.
4014 if (BlockDeclRefExpr *CDRE = dyn_cast<BlockDeclRefExpr>(S))
4015 // FIXME: Handle enums.
4016 if (!isa<FunctionDecl>(CDRE->getDecl()))
4017 BlockDeclRefs.push_back(CDRE);
4018 return;
4019}
4020
4021void RewriteObjC::GetBlockCallExprs(Stmt *S) {
4022 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4023 CI != E; ++CI)
4024 if (*CI) {
4025 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4026 GetBlockCallExprs(CBE->getBody());
4027 else
4028 GetBlockCallExprs(*CI);
4029 }
Mike Stump11289f42009-09-09 15:08:12 +00004030
Steve Naroff677ab3a2008-10-27 17:20:55 +00004031 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4032 if (CE->getCallee()->getType()->isBlockPointerType()) {
4033 BlockCallExprs[dyn_cast<BlockDeclRefExpr>(CE->getCallee())] = CE;
4034 }
4035 }
4036 return;
4037}
4038
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004039Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004040 // Navigate to relevant type information.
Steve Naroff677ab3a2008-10-27 17:20:55 +00004041 const BlockPointerType *CPT = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004042
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004043 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004044 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004045 } else if (const BlockDeclRefExpr *CDRE =
4046 dyn_cast<BlockDeclRefExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004047 CPT = CDRE->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004048 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004049 CPT = MExpr->getType()->getAs<BlockPointerType>();
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004050 }
4051 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4052 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4053 }
4054 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4055 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4056 else if (const ConditionalOperator *CEXPR =
4057 dyn_cast<ConditionalOperator>(BlockExp)) {
4058 Expr *LHSExp = CEXPR->getLHS();
4059 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4060 Expr *RHSExp = CEXPR->getRHS();
4061 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4062 Expr *CONDExp = CEXPR->getCond();
4063 ConditionalOperator *CondExpr =
4064 new (Context) ConditionalOperator(CONDExp,
4065 SourceLocation(), cast<Expr>(LHSStmt),
4066 SourceLocation(), cast<Expr>(RHSStmt),
4067 Exp->getType());
4068 return CondExpr;
Fariborz Jahanian6ab7ed42009-12-18 01:15:21 +00004069 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4070 CPT = IRE->getType()->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004071 } else {
4072 assert(1 && "RewriteBlockClass: Bad type");
4073 }
4074 assert(CPT && "RewriteBlockClass: Bad type");
John McCall9dd450b2009-09-21 23:43:11 +00004075 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004076 assert(FT && "RewriteBlockClass: Bad type");
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004077 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004078 // FTP will be null for closures that don't take arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004079
Steve Naroff350b6652008-10-30 10:07:53 +00004080 RecordDecl *RD = RecordDecl::Create(*Context, TagDecl::TK_struct, TUDecl,
4081 SourceLocation(),
4082 &Context->Idents.get("__block_impl"));
4083 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
Steve Naroff677ab3a2008-10-27 17:20:55 +00004084
Steve Naroff350b6652008-10-30 10:07:53 +00004085 // Generate a funky cast.
4086 llvm::SmallVector<QualType, 8> ArgTypes;
Mike Stump11289f42009-09-09 15:08:12 +00004087
Steve Naroff350b6652008-10-30 10:07:53 +00004088 // Push the block argument type.
4089 ArgTypes.push_back(PtrBlock);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004090 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004091 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff350b6652008-10-30 10:07:53 +00004092 E = FTP->arg_type_end(); I && (I != E); ++I) {
4093 QualType t = *I;
4094 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Steve Naroffa5c0db82008-12-11 21:05:33 +00004095 if (isTopLevelBlockPointerType(t)) {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004096 const BlockPointerType *BPT = t->getAs<BlockPointerType>();
Steve Naroff350b6652008-10-30 10:07:53 +00004097 t = Context->getPointerType(BPT->getPointeeType());
4098 }
4099 ArgTypes.push_back(t);
4100 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004101 }
Steve Naroff350b6652008-10-30 10:07:53 +00004102 // Now do the pointer to function cast.
Mike Stump11289f42009-09-09 15:08:12 +00004103 QualType PtrToFuncCastType = Context->getFunctionType(Exp->getType(),
Steve Naroff350b6652008-10-30 10:07:53 +00004104 &ArgTypes[0], ArgTypes.size(), false/*no variadic*/, 0);
Mike Stump11289f42009-09-09 15:08:12 +00004105
Steve Naroff350b6652008-10-30 10:07:53 +00004106 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
Mike Stump11289f42009-09-09 15:08:12 +00004107
4108 CastExpr *BlkCast = new (Context) CStyleCastExpr(PtrBlock,
Anders Carlssona2615922009-07-31 00:48:10 +00004109 CastExpr::CK_Unknown,
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004110 const_cast<Expr*>(BlockExp),
Ted Kremenek5a201952009-02-07 01:47:29 +00004111 PtrBlock, SourceLocation(),
4112 SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004113 // Don't forget the parens to enforce the proper binding.
Ted Kremenek5a201952009-02-07 01:47:29 +00004114 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4115 BlkCast);
Steve Naroff350b6652008-10-30 10:07:53 +00004116 //PE->dump();
Mike Stump11289f42009-09-09 15:08:12 +00004117
Douglas Gregor91f84212008-12-11 16:49:14 +00004118 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
Mike Stump11289f42009-09-09 15:08:12 +00004119 &Context->Idents.get("FuncPtr"), Context->VoidPtrTy, 0,
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004120 /*BitWidth=*/0, /*Mutable=*/true);
Ted Kremenek5a201952009-02-07 01:47:29 +00004121 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4122 FD->getType());
Mike Stump11289f42009-09-09 15:08:12 +00004123
Anders Carlssona2615922009-07-31 00:48:10 +00004124 CastExpr *FunkCast = new (Context) CStyleCastExpr(PtrToFuncCastType,
4125 CastExpr::CK_Unknown, ME,
Ted Kremenek5a201952009-02-07 01:47:29 +00004126 PtrToFuncCastType,
4127 SourceLocation(),
4128 SourceLocation());
4129 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
Mike Stump11289f42009-09-09 15:08:12 +00004130
Steve Naroff350b6652008-10-30 10:07:53 +00004131 llvm::SmallVector<Expr*, 8> BlkExprs;
4132 // Add the implicit argument.
4133 BlkExprs.push_back(BlkCast);
4134 // Add the user arguments.
Mike Stump11289f42009-09-09 15:08:12 +00004135 for (CallExpr::arg_iterator I = Exp->arg_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004136 E = Exp->arg_end(); I != E; ++I) {
Steve Naroff350b6652008-10-30 10:07:53 +00004137 BlkExprs.push_back(*I);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004138 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004139 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4140 BlkExprs.size(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004141 Exp->getType(), SourceLocation());
Steve Naroff350b6652008-10-30 10:07:53 +00004142 return CE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004143}
4144
4145void RewriteObjC::RewriteBlockCall(CallExpr *Exp) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004146 Stmt *BlockCall = SynthesizeBlockCall(Exp, Exp->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004147 ReplaceStmt(Exp, BlockCall);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004148}
4149
Steve Naroffd9803712009-04-29 16:37:50 +00004150// We need to return the rewritten expression to handle cases where the
4151// BlockDeclRefExpr is embedded in another expression being rewritten.
4152// For example:
4153//
4154// int main() {
4155// __block Foo *f;
4156// __block int i;
Mike Stump11289f42009-09-09 15:08:12 +00004157//
Steve Naroffd9803712009-04-29 16:37:50 +00004158// void (^myblock)() = ^() {
4159// [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
4160// i = 77;
4161// };
4162//}
4163Stmt *RewriteObjC::RewriteBlockDeclRefExpr(BlockDeclRefExpr *BDRE) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004164 // FIXME: Add more elaborate code generation required by the ABI.
Ted Kremenek5a201952009-02-07 01:47:29 +00004165 Expr *DerefExpr = new (Context) UnaryOperator(BDRE, UnaryOperator::Deref,
Steve Narofff26a1d42009-02-02 17:19:26 +00004166 Context->getPointerType(BDRE->getType()),
4167 SourceLocation());
4168 // Need parens to enforce precedence.
Ted Kremenek5a201952009-02-07 01:47:29 +00004169 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), DerefExpr);
Steve Narofff26a1d42009-02-02 17:19:26 +00004170 ReplaceStmt(BDRE, PE);
Steve Naroffd9803712009-04-29 16:37:50 +00004171 return PE;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004172}
4173
Steve Naroffc989a7b2008-11-03 23:29:32 +00004174void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4175 SourceLocation LocStart = CE->getLParenLoc();
4176 SourceLocation LocEnd = CE->getRParenLoc();
Steve Narofff4b992a2008-10-28 20:29:00 +00004177
4178 // Need to avoid trying to rewrite synthesized casts.
4179 if (LocStart.isInvalid())
4180 return;
Steve Naroff3e7ced12008-11-03 11:20:24 +00004181 // Need to avoid trying to rewrite casts contained in macros.
4182 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4183 return;
Mike Stump11289f42009-09-09 15:08:12 +00004184
Steve Naroff677ab3a2008-10-27 17:20:55 +00004185 const char *startBuf = SM->getCharacterData(LocStart);
4186 const char *endBuf = SM->getCharacterData(LocEnd);
Mike Stump11289f42009-09-09 15:08:12 +00004187
Steve Naroff677ab3a2008-10-27 17:20:55 +00004188 // advance the location to startArgList.
4189 const char *argPtr = startBuf;
Mike Stump11289f42009-09-09 15:08:12 +00004190
Steve Naroff677ab3a2008-10-27 17:20:55 +00004191 while (*argPtr++ && (argPtr < endBuf)) {
4192 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004193 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004194 // Replace the '^' with '*'.
4195 LocStart = LocStart.getFileLocWithOffset(argPtr-startBuf);
4196 ReplaceText(LocStart, 1, "*", 1);
4197 break;
4198 }
4199 }
4200 return;
4201}
4202
4203void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4204 SourceLocation DeclLoc = FD->getLocation();
4205 unsigned parenCount = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004206
Steve Naroff677ab3a2008-10-27 17:20:55 +00004207 // We have 1 or more arguments that have closure pointers.
4208 const char *startBuf = SM->getCharacterData(DeclLoc);
4209 const char *startArgList = strchr(startBuf, '(');
Mike Stump11289f42009-09-09 15:08:12 +00004210
Steve Naroff677ab3a2008-10-27 17:20:55 +00004211 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004212
Steve Naroff677ab3a2008-10-27 17:20:55 +00004213 parenCount++;
4214 // advance the location to startArgList.
4215 DeclLoc = DeclLoc.getFileLocWithOffset(startArgList-startBuf);
4216 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
Mike Stump11289f42009-09-09 15:08:12 +00004217
Steve Naroff677ab3a2008-10-27 17:20:55 +00004218 const char *argPtr = startArgList;
Mike Stump11289f42009-09-09 15:08:12 +00004219
Steve Naroff677ab3a2008-10-27 17:20:55 +00004220 while (*argPtr++ && parenCount) {
4221 switch (*argPtr) {
Mike Stump11289f42009-09-09 15:08:12 +00004222 case '^':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004223 // Replace the '^' with '*'.
4224 DeclLoc = DeclLoc.getFileLocWithOffset(argPtr-startArgList);
4225 ReplaceText(DeclLoc, 1, "*", 1);
4226 break;
Mike Stump11289f42009-09-09 15:08:12 +00004227 case '(':
4228 parenCount++;
Steve Naroff677ab3a2008-10-27 17:20:55 +00004229 break;
Mike Stump11289f42009-09-09 15:08:12 +00004230 case ')':
Steve Naroff677ab3a2008-10-27 17:20:55 +00004231 parenCount--;
4232 break;
4233 }
4234 }
4235 return;
4236}
4237
4238bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004239 const FunctionProtoType *FTP;
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004240 const PointerType *PT = QT->getAs<PointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004241 if (PT) {
John McCall9dd450b2009-09-21 23:43:11 +00004242 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004243 } else {
Ted Kremenekc23c7e62009-07-29 21:53:49 +00004244 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004245 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
John McCall9dd450b2009-09-21 23:43:11 +00004246 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
Steve Naroff677ab3a2008-10-27 17:20:55 +00004247 }
4248 if (FTP) {
Mike Stump11289f42009-09-09 15:08:12 +00004249 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
Steve Naroff677ab3a2008-10-27 17:20:55 +00004250 E = FTP->arg_type_end(); I != E; ++I)
Steve Naroffa5c0db82008-12-11 21:05:33 +00004251 if (isTopLevelBlockPointerType(*I))
Steve Naroff677ab3a2008-10-27 17:20:55 +00004252 return true;
4253 }
4254 return false;
4255}
4256
Ted Kremenek5a201952009-02-07 01:47:29 +00004257void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4258 const char *&RParen) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004259 const char *argPtr = strchr(Name, '(');
4260 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
Mike Stump11289f42009-09-09 15:08:12 +00004261
Steve Naroff677ab3a2008-10-27 17:20:55 +00004262 LParen = argPtr; // output the start.
4263 argPtr++; // skip past the left paren.
4264 unsigned parenCount = 1;
Mike Stump11289f42009-09-09 15:08:12 +00004265
Steve Naroff677ab3a2008-10-27 17:20:55 +00004266 while (*argPtr && parenCount) {
4267 switch (*argPtr) {
4268 case '(': parenCount++; break;
4269 case ')': parenCount--; break;
4270 default: break;
4271 }
4272 if (parenCount) argPtr++;
4273 }
4274 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4275 RParen = argPtr; // output the end
4276}
4277
4278void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4279 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4280 RewriteBlockPointerFunctionArgs(FD);
4281 return;
Mike Stump11289f42009-09-09 15:08:12 +00004282 }
Steve Naroff677ab3a2008-10-27 17:20:55 +00004283 // Handle Variables and Typedefs.
4284 SourceLocation DeclLoc = ND->getLocation();
4285 QualType DeclT;
4286 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4287 DeclT = VD->getType();
4288 else if (TypedefDecl *TDD = dyn_cast<TypedefDecl>(ND))
4289 DeclT = TDD->getUnderlyingType();
4290 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4291 DeclT = FD->getType();
Mike Stump11289f42009-09-09 15:08:12 +00004292 else
Steve Naroff677ab3a2008-10-27 17:20:55 +00004293 assert(0 && "RewriteBlockPointerDecl(): Decl type not yet handled");
Mike Stump11289f42009-09-09 15:08:12 +00004294
Steve Naroff677ab3a2008-10-27 17:20:55 +00004295 const char *startBuf = SM->getCharacterData(DeclLoc);
4296 const char *endBuf = startBuf;
4297 // scan backward (from the decl location) for the end of the previous decl.
4298 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4299 startBuf--;
Mike Stump11289f42009-09-09 15:08:12 +00004300
Steve Naroff677ab3a2008-10-27 17:20:55 +00004301 // *startBuf != '^' if we are dealing with a pointer to function that
4302 // may take block argument types (which will be handled below).
4303 if (*startBuf == '^') {
4304 // Replace the '^' with '*', computing a negative offset.
4305 DeclLoc = DeclLoc.getFileLocWithOffset(startBuf-endBuf);
4306 ReplaceText(DeclLoc, 1, "*", 1);
4307 }
4308 if (PointerTypeTakesAnyBlockArguments(DeclT)) {
4309 // Replace the '^' with '*' for arguments.
4310 DeclLoc = ND->getLocation();
4311 startBuf = SM->getCharacterData(DeclLoc);
4312 const char *argListBegin, *argListEnd;
4313 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4314 while (argListBegin < argListEnd) {
4315 if (*argListBegin == '^') {
4316 SourceLocation CaretLoc = DeclLoc.getFileLocWithOffset(argListBegin-startBuf);
4317 ReplaceText(CaretLoc, 1, "*", 1);
4318 }
4319 argListBegin++;
4320 }
4321 }
4322 return;
4323}
4324
Fariborz Jahanian81203462009-12-22 00:48:54 +00004325void RewriteObjC::RewriteByRefVar(NamedDecl *ND) {
4326 return;
4327}
4328
Mike Stump11289f42009-09-09 15:08:12 +00004329void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
Steve Naroff677ab3a2008-10-27 17:20:55 +00004330 // Add initializers for any closure decl refs.
4331 GetBlockDeclRefExprs(Exp->getBody());
4332 if (BlockDeclRefs.size()) {
4333 // Unique all "by copy" declarations.
4334 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4335 if (!BlockDeclRefs[i]->isByRef())
4336 BlockByCopyDecls.insert(BlockDeclRefs[i]->getDecl());
4337 // Unique all "by ref" declarations.
4338 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
4339 if (BlockDeclRefs[i]->isByRef()) {
4340 BlockByRefDecls.insert(BlockDeclRefs[i]->getDecl());
4341 }
4342 // Find any imported blocks...they will need special attention.
4343 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
Fariborz Jahaniane175eeb2009-12-21 23:31:42 +00004344 if (BlockDeclRefs[i]->isByRef() ||
4345 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4346 BlockDeclRefs[i]->getType()->isBlockPointerType()) {
Steve Naroff832d8902008-11-13 17:40:07 +00004347 GetBlockCallExprs(BlockDeclRefs[i]);
Steve Naroff677ab3a2008-10-27 17:20:55 +00004348 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4349 }
4350 }
4351}
4352
Steve Narofff4b992a2008-10-28 20:29:00 +00004353FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(const char *name) {
4354 IdentifierInfo *ID = &Context->Idents.get(name);
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004355 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
Mike Stump11289f42009-09-09 15:08:12 +00004356 return FunctionDecl::Create(*Context, TUDecl,SourceLocation(),
Argyrios Kyrtzidis60ed5602009-08-19 01:27:57 +00004357 ID, FType, 0, FunctionDecl::Extern, false,
Douglas Gregor739ef0c2009-02-25 16:33:18 +00004358 false);
Steve Narofff4b992a2008-10-28 20:29:00 +00004359}
4360
Steve Naroffd8907b72008-10-29 18:15:37 +00004361Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004362 Blocks.push_back(Exp);
4363
4364 CollectBlockDeclRefInfo(Exp);
4365 std::string FuncName;
Mike Stump11289f42009-09-09 15:08:12 +00004366
Steve Narofff4b992a2008-10-28 20:29:00 +00004367 if (CurFunctionDef)
Chris Lattnere4b95692008-11-24 03:33:13 +00004368 FuncName = CurFunctionDef->getNameAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004369 else if (CurMethodDef) {
Chris Lattnere4b95692008-11-24 03:33:13 +00004370 FuncName = CurMethodDef->getSelector().getAsString();
Steve Narofff4b992a2008-10-28 20:29:00 +00004371 // Convert colons to underscores.
4372 std::string::size_type loc = 0;
4373 while ((loc = FuncName.find(":", loc)) != std::string::npos)
4374 FuncName.replace(loc, 1, "_");
Steve Naroffd8907b72008-10-29 18:15:37 +00004375 } else if (GlobalVarDecl)
Chris Lattnerf3d3fae2008-11-24 05:29:24 +00004376 FuncName = std::string(GlobalVarDecl->getNameAsString());
Mike Stump11289f42009-09-09 15:08:12 +00004377
Steve Narofff4b992a2008-10-28 20:29:00 +00004378 std::string BlockNumber = utostr(Blocks.size()-1);
Mike Stump11289f42009-09-09 15:08:12 +00004379
Steve Narofff4b992a2008-10-28 20:29:00 +00004380 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4381 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
Mike Stump11289f42009-09-09 15:08:12 +00004382
Steve Narofff4b992a2008-10-28 20:29:00 +00004383 // Get a pointer to the function type so we can cast appropriately.
4384 QualType FType = Context->getPointerType(QualType(Exp->getFunctionType(),0));
4385
4386 FunctionDecl *FD;
4387 Expr *NewRep;
Mike Stump11289f42009-09-09 15:08:12 +00004388
Steve Narofff4b992a2008-10-28 20:29:00 +00004389 // Simulate a contructor call...
4390 FD = SynthBlockInitFunctionDecl(Tag.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004391 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, FType, SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004392
Steve Narofff4b992a2008-10-28 20:29:00 +00004393 llvm::SmallVector<Expr*, 4> InitExprs;
Mike Stump11289f42009-09-09 15:08:12 +00004394
Steve Naroffe2514232008-10-29 21:23:59 +00004395 // Initialize the block function.
Steve Narofff4b992a2008-10-28 20:29:00 +00004396 FD = SynthBlockInitFunctionDecl(Func.c_str());
Ted Kremenek5a201952009-02-07 01:47:29 +00004397 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, FD->getType(),
4398 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004399 CastExpr *castExpr = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4400 CastExpr::CK_Unknown, Arg,
Ted Kremenek5a201952009-02-07 01:47:29 +00004401 Context->VoidPtrTy, SourceLocation(),
4402 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004403 InitExprs.push_back(castExpr);
4404
Steve Naroff30484702009-12-06 21:14:13 +00004405 // Initialize the block descriptor.
4406 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
Mike Stump11289f42009-09-09 15:08:12 +00004407
Steve Naroff30484702009-12-06 21:14:13 +00004408 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
4409 &Context->Idents.get(DescData.c_str()),
4410 Context->VoidPtrTy, 0,
4411 VarDecl::Static);
4412 UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4413 new (Context) DeclRefExpr(NewVD,
4414 Context->VoidPtrTy, SourceLocation()),
4415 UnaryOperator::AddrOf,
4416 Context->getPointerType(Context->VoidPtrTy),
4417 SourceLocation());
4418 InitExprs.push_back(DescRefExpr);
4419
Steve Narofff4b992a2008-10-28 20:29:00 +00004420 // Add initializers for any closure decl refs.
4421 if (BlockDeclRefs.size()) {
Steve Naroffe2514232008-10-29 21:23:59 +00004422 Expr *Exp;
Steve Narofff4b992a2008-10-28 20:29:00 +00004423 // Output all "by copy" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004424 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004425 E = BlockByCopyDecls.end(); I != E; ++I) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004426 if (isObjCType((*I)->getType())) {
Steve Naroffe2514232008-10-29 21:23:59 +00004427 // FIXME: Conform to ABI ([[obj retain] autorelease]).
Chris Lattner86d7d912008-11-24 03:54:41 +00004428 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004429 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Naroffa5c0db82008-12-11 21:05:33 +00004430 } else if (isTopLevelBlockPointerType((*I)->getType())) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004431 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004432 Arg = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004433 Exp = new (Context) CStyleCastExpr(Context->VoidPtrTy,
4434 CastExpr::CK_Unknown, Arg,
4435 Context->VoidPtrTy,
Anders Carlssona2615922009-07-31 00:48:10 +00004436 SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004437 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004438 } else {
Chris Lattner86d7d912008-11-24 03:54:41 +00004439 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004440 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004441 }
Mike Stump11289f42009-09-09 15:08:12 +00004442 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004443 }
4444 // Output all "by ref" declarations.
Mike Stump11289f42009-09-09 15:08:12 +00004445 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
Steve Narofff4b992a2008-10-28 20:29:00 +00004446 E = BlockByRefDecls.end(); I != E; ++I) {
Chris Lattner86d7d912008-11-24 03:54:41 +00004447 FD = SynthBlockInitFunctionDecl((*I)->getNameAsCString());
Ted Kremenek5a201952009-02-07 01:47:29 +00004448 Exp = new (Context) DeclRefExpr(FD, FD->getType(), SourceLocation());
4449 Exp = new (Context) UnaryOperator(Exp, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004450 Context->getPointerType(Exp->getType()),
Steve Naroffe2514232008-10-29 21:23:59 +00004451 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004452 InitExprs.push_back(Exp);
Steve Narofff4b992a2008-10-28 20:29:00 +00004453 }
4454 }
Steve Naroff30484702009-12-06 21:14:13 +00004455 if (ImportedBlockDecls.size()) { // generate "1<<25" to indicate we have helper functions.
4456 unsigned IntSize =
4457 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4458 BinaryOperator *Exp = new (Context) BinaryOperator(
4459 new (Context) IntegerLiteral(llvm::APInt(IntSize, 1),
4460 Context->IntTy,SourceLocation()),
4461 new (Context) IntegerLiteral(llvm::APInt(IntSize, 25),
4462 Context->IntTy, SourceLocation()),
4463 BinaryOperator::Shl, Context->IntTy, SourceLocation());
4464 InitExprs.push_back(Exp);
4465 }
Ted Kremenekd7b4f402009-02-09 20:51:47 +00004466 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4467 FType, SourceLocation());
Ted Kremenek5a201952009-02-07 01:47:29 +00004468 NewRep = new (Context) UnaryOperator(NewRep, UnaryOperator::AddrOf,
Mike Stump11289f42009-09-09 15:08:12 +00004469 Context->getPointerType(NewRep->getType()),
Steve Narofff4b992a2008-10-28 20:29:00 +00004470 SourceLocation());
Mike Stump11289f42009-09-09 15:08:12 +00004471 NewRep = new (Context) CStyleCastExpr(FType, CastExpr::CK_Unknown, NewRep,
Anders Carlssona2615922009-07-31 00:48:10 +00004472 FType, SourceLocation(),
Ted Kremenek5a201952009-02-07 01:47:29 +00004473 SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004474 BlockDeclRefs.clear();
4475 BlockByRefDecls.clear();
4476 BlockByCopyDecls.clear();
4477 ImportedBlockDecls.clear();
4478 return NewRep;
4479}
4480
4481//===----------------------------------------------------------------------===//
4482// Function Body / Expression rewriting
4483//===----------------------------------------------------------------------===//
4484
Steve Naroff4588d0f2008-12-04 16:24:46 +00004485// This is run as a first "pass" prior to RewriteFunctionBodyOrGlobalInitializer().
4486// The allows the main rewrite loop to associate all ObjCPropertyRefExprs with
4487// their respective BinaryOperator. Without this knowledge, we'd need to rewrite
4488// the ObjCPropertyRefExpr twice (once as a getter, and later as a setter).
4489// Since the rewriter isn't capable of rewriting rewritten code, it's important
4490// we get this right.
4491void RewriteObjC::CollectPropertySetters(Stmt *S) {
4492 // Perform a bottom up traversal of all children.
4493 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4494 CI != E; ++CI)
4495 if (*CI)
4496 CollectPropertySetters(*CI);
4497
4498 if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(S)) {
4499 if (BinOp->isAssignmentOp()) {
4500 if (ObjCPropertyRefExpr *PRE = dyn_cast<ObjCPropertyRefExpr>(BinOp->getLHS()))
4501 PropSetters[PRE] = BinOp;
4502 }
4503 }
4504}
4505
Steve Narofff4b992a2008-10-28 20:29:00 +00004506Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
Mike Stump11289f42009-09-09 15:08:12 +00004507 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004508 isa<DoStmt>(S) || isa<ForStmt>(S))
4509 Stmts.push_back(S);
4510 else if (isa<ObjCForCollectionStmt>(S)) {
4511 Stmts.push_back(S);
Anders Carlsson3caa2b42009-12-22 06:13:42 +00004512 ++BcLabelCount;
4513 ObjCBcLabelNo.push_back(BcLabelCount);
Steve Narofff4b992a2008-10-28 20:29:00 +00004514 }
Mike Stump11289f42009-09-09 15:08:12 +00004515
Steve Narofff4b992a2008-10-28 20:29:00 +00004516 SourceRange OrigStmtRange = S->getSourceRange();
Mike Stump11289f42009-09-09 15:08:12 +00004517
Steve Narofff4b992a2008-10-28 20:29:00 +00004518 // Perform a bottom up rewrite of all children.
4519 for (Stmt::child_iterator CI = S->child_begin(), E = S->child_end();
4520 CI != E; ++CI)
4521 if (*CI) {
4522 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(*CI);
Mike Stump11289f42009-09-09 15:08:12 +00004523 if (newStmt)
Steve Narofff4b992a2008-10-28 20:29:00 +00004524 *CI = newStmt;
4525 }
Mike Stump11289f42009-09-09 15:08:12 +00004526
Steve Narofff4b992a2008-10-28 20:29:00 +00004527 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4528 // Rewrite the block body in place.
4529 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
Mike Stump11289f42009-09-09 15:08:12 +00004530
Steve Narofff4b992a2008-10-28 20:29:00 +00004531 // Now we snarf the rewritten text and stash it away for later use.
Steve Naroffd8907b72008-10-29 18:15:37 +00004532 std::string Str = Rewrite.getRewritenText(BE->getSourceRange());
4533 RewrittenBlockExprs[BE] = Str;
Mike Stump11289f42009-09-09 15:08:12 +00004534
Steve Narofff4b992a2008-10-28 20:29:00 +00004535 Stmt *blockTranscribed = SynthBlockInitExpr(BE);
4536 //blockTranscribed->dump();
Steve Naroffd8907b72008-10-29 18:15:37 +00004537 ReplaceStmt(S, blockTranscribed);
Steve Narofff4b992a2008-10-28 20:29:00 +00004538 return blockTranscribed;
4539 }
4540 // Handle specific things.
4541 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4542 return RewriteAtEncode(AtEncode);
Mike Stump11289f42009-09-09 15:08:12 +00004543
Steve Narofff4b992a2008-10-28 20:29:00 +00004544 if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S))
4545 return RewriteObjCIvarRefExpr(IvarRefExpr, OrigStmtRange.getBegin());
4546
Steve Naroff4588d0f2008-12-04 16:24:46 +00004547 if (ObjCPropertyRefExpr *PropRefExpr = dyn_cast<ObjCPropertyRefExpr>(S)) {
4548 BinaryOperator *BinOp = PropSetters[PropRefExpr];
4549 if (BinOp) {
4550 // Because the rewriter doesn't allow us to rewrite rewritten code,
4551 // we need to rewrite the right hand side prior to rewriting the setter.
Steve Naroff08628db2008-12-09 12:56:34 +00004552 DisableReplaceStmt = true;
4553 // Save the source range. Even if we disable the replacement, the
4554 // rewritten node will have been inserted into the tree. If the synthesized
4555 // node is at the 'end', the rewriter will fail. Consider this:
Mike Stump11289f42009-09-09 15:08:12 +00004556 // self.errorHandler = handler ? handler :
Steve Naroff08628db2008-12-09 12:56:34 +00004557 // ^(NSURL *errorURL, NSError *error) { return (BOOL)1; };
4558 SourceRange SrcRange = BinOp->getSourceRange();
Steve Naroff4588d0f2008-12-04 16:24:46 +00004559 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(BinOp->getRHS());
Steve Naroff08628db2008-12-09 12:56:34 +00004560 DisableReplaceStmt = false;
Steve Naroff22216db2008-12-04 23:50:32 +00004561 //
4562 // Unlike the main iterator, we explicily avoid changing 'BinOp'. If
4563 // we changed the RHS of BinOp, the rewriter would fail (since it needs
4564 // to see the original expression). Consider this example:
4565 //
4566 // Foo *obj1, *obj2;
4567 //
4568 // obj1.i = [obj2 rrrr];
4569 //
4570 // 'BinOp' for the previous expression looks like:
4571 //
4572 // (BinaryOperator 0x231ccf0 'int' '='
4573 // (ObjCPropertyRefExpr 0x231cc70 'int' Kind=PropertyRef Property="i"
4574 // (DeclRefExpr 0x231cc50 'Foo *' Var='obj1' 0x231cbb0))
4575 // (ObjCMessageExpr 0x231ccb0 'int' selector=rrrr
4576 // (DeclRefExpr 0x231cc90 'Foo *' Var='obj2' 0x231cbe0)))
4577 //
4578 // 'newStmt' represents the rewritten message expression. For example:
4579 //
4580 // (CallExpr 0x231d300 'id':'struct objc_object *'
4581 // (ParenExpr 0x231d2e0 'int (*)(id, SEL)'
4582 // (CStyleCastExpr 0x231d2c0 'int (*)(id, SEL)'
4583 // (CStyleCastExpr 0x231d220 'void *'
4584 // (DeclRefExpr 0x231d200 'id (id, SEL, ...)' FunctionDecl='objc_msgSend' 0x231cdc0))))
4585 //
4586 // Note that 'newStmt' is passed to RewritePropertySetter so that it
4587 // can be used as the setter argument. ReplaceStmt() will still 'see'
4588 // the original RHS (since we haven't altered BinOp).
4589 //
Mike Stump11289f42009-09-09 15:08:12 +00004590 // This implies the Rewrite* routines can no longer delete the original
Steve Naroff22216db2008-12-04 23:50:32 +00004591 // node. As a result, we now leak the original AST nodes.
4592 //
Steve Naroff08628db2008-12-09 12:56:34 +00004593 return RewritePropertySetter(BinOp, dyn_cast<Expr>(newStmt), SrcRange);
Steve Naroff4588d0f2008-12-04 16:24:46 +00004594 } else {
4595 return RewritePropertyGetter(PropRefExpr);
Steve Narofff326f402008-12-03 00:56:33 +00004596 }
4597 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004598 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4599 return RewriteAtSelector(AtSelector);
Mike Stump11289f42009-09-09 15:08:12 +00004600
Steve Narofff4b992a2008-10-28 20:29:00 +00004601 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4602 return RewriteObjCStringLiteral(AtString);
Mike Stump11289f42009-09-09 15:08:12 +00004603
Steve Narofff4b992a2008-10-28 20:29:00 +00004604 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
Steve Naroff4588d0f2008-12-04 16:24:46 +00004605#if 0
Steve Narofff4b992a2008-10-28 20:29:00 +00004606 // Before we rewrite it, put the original message expression in a comment.
4607 SourceLocation startLoc = MessExpr->getLocStart();
4608 SourceLocation endLoc = MessExpr->getLocEnd();
Mike Stump11289f42009-09-09 15:08:12 +00004609
Steve Narofff4b992a2008-10-28 20:29:00 +00004610 const char *startBuf = SM->getCharacterData(startLoc);
4611 const char *endBuf = SM->getCharacterData(endLoc);
Mike Stump11289f42009-09-09 15:08:12 +00004612
Steve Narofff4b992a2008-10-28 20:29:00 +00004613 std::string messString;
4614 messString += "// ";
4615 messString.append(startBuf, endBuf-startBuf+1);
4616 messString += "\n";
Mike Stump11289f42009-09-09 15:08:12 +00004617
4618 // FIXME: Missing definition of
Steve Narofff4b992a2008-10-28 20:29:00 +00004619 // InsertText(clang::SourceLocation, char const*, unsigned int).
4620 // InsertText(startLoc, messString.c_str(), messString.size());
4621 // Tried this, but it didn't work either...
4622 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
Steve Naroff4588d0f2008-12-04 16:24:46 +00004623#endif
Steve Narofff4b992a2008-10-28 20:29:00 +00004624 return RewriteMessageExpr(MessExpr);
4625 }
Mike Stump11289f42009-09-09 15:08:12 +00004626
Steve Narofff4b992a2008-10-28 20:29:00 +00004627 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4628 return RewriteObjCTryStmt(StmtTry);
4629
4630 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4631 return RewriteObjCSynchronizedStmt(StmtTry);
4632
4633 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4634 return RewriteObjCThrowStmt(StmtThrow);
Mike Stump11289f42009-09-09 15:08:12 +00004635
Steve Narofff4b992a2008-10-28 20:29:00 +00004636 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4637 return RewriteObjCProtocolExpr(ProtocolExp);
Mike Stump11289f42009-09-09 15:08:12 +00004638
4639 if (ObjCForCollectionStmt *StmtForCollection =
Steve Narofff4b992a2008-10-28 20:29:00 +00004640 dyn_cast<ObjCForCollectionStmt>(S))
Mike Stump11289f42009-09-09 15:08:12 +00004641 return RewriteObjCForCollectionStmt(StmtForCollection,
Steve Narofff4b992a2008-10-28 20:29:00 +00004642 OrigStmtRange.getEnd());
4643 if (BreakStmt *StmtBreakStmt =
4644 dyn_cast<BreakStmt>(S))
4645 return RewriteBreakStmt(StmtBreakStmt);
4646 if (ContinueStmt *StmtContinueStmt =
4647 dyn_cast<ContinueStmt>(S))
4648 return RewriteContinueStmt(StmtContinueStmt);
Mike Stump11289f42009-09-09 15:08:12 +00004649
4650 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
Steve Narofff4b992a2008-10-28 20:29:00 +00004651 // and cast exprs.
4652 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4653 // FIXME: What we're doing here is modifying the type-specifier that
4654 // precedes the first Decl. In the future the DeclGroup should have
Mike Stump11289f42009-09-09 15:08:12 +00004655 // a separate type-specifier that we can rewrite.
Steve Naroffe70a52a2009-12-05 15:55:59 +00004656 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4657 // the context of an ObjCForCollectionStmt. For example:
4658 // NSArray *someArray;
4659 // for (id <FooProtocol> index in someArray) ;
4660 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4661 // and it depends on the original text locations/positions.
Benjamin Krameracc5fa12009-12-05 22:16:51 +00004662 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
Steve Naroffe70a52a2009-12-05 15:55:59 +00004663 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
Mike Stump11289f42009-09-09 15:08:12 +00004664
Steve Narofff4b992a2008-10-28 20:29:00 +00004665 // Blocks rewrite rules.
4666 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4667 DI != DE; ++DI) {
Douglas Gregor6e6ad602009-01-20 01:17:11 +00004668 Decl *SD = *DI;
Steve Narofff4b992a2008-10-28 20:29:00 +00004669 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004670 if (isTopLevelBlockPointerType(ND->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004671 RewriteBlockPointerDecl(ND);
Mike Stump11289f42009-09-09 15:08:12 +00004672 else if (ND->getType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004673 CheckFunctionPointerDecl(ND->getType(), ND);
Fariborz Jahanian81203462009-12-22 00:48:54 +00004674 if (ND->hasAttr<BlocksAttr>())
4675 RewriteByRefVar(ND);
Steve Narofff4b992a2008-10-28 20:29:00 +00004676 }
4677 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(SD)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004678 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004679 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004680 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004681 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4682 }
4683 }
4684 }
Mike Stump11289f42009-09-09 15:08:12 +00004685
Steve Narofff4b992a2008-10-28 20:29:00 +00004686 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4687 RewriteObjCQualifiedInterfaceTypes(CE);
Mike Stump11289f42009-09-09 15:08:12 +00004688
4689 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
Steve Narofff4b992a2008-10-28 20:29:00 +00004690 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4691 assert(!Stmts.empty() && "Statement stack is empty");
Mike Stump11289f42009-09-09 15:08:12 +00004692 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4693 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004694 && "Statement stack mismatch");
4695 Stmts.pop_back();
4696 }
4697 // Handle blocks rewriting.
4698 if (BlockDeclRefExpr *BDRE = dyn_cast<BlockDeclRefExpr>(S)) {
4699 if (BDRE->isByRef())
Steve Naroffd9803712009-04-29 16:37:50 +00004700 return RewriteBlockDeclRefExpr(BDRE);
Steve Narofff4b992a2008-10-28 20:29:00 +00004701 }
4702 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
Steve Naroff350b6652008-10-30 10:07:53 +00004703 if (CE->getCallee()->getType()->isBlockPointerType()) {
Fariborz Jahaniand1a2d572009-12-15 17:30:20 +00004704 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
Steve Naroff350b6652008-10-30 10:07:53 +00004705 ReplaceStmt(S, BlockCall);
4706 return BlockCall;
4707 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004708 }
Steve Naroffc989a7b2008-11-03 23:29:32 +00004709 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004710 RewriteCastExpr(CE);
4711 }
4712#if 0
4713 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
Ted Kremenek5a201952009-02-07 01:47:29 +00004714 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(), ICE->getSubExpr(), SourceLocation());
Steve Narofff4b992a2008-10-28 20:29:00 +00004715 // Get the new text.
4716 std::string SStr;
4717 llvm::raw_string_ostream Buf(SStr);
Eli Friedman0905f142009-05-30 05:19:26 +00004718 Replacement->printPretty(Buf, *Context);
Steve Narofff4b992a2008-10-28 20:29:00 +00004719 const std::string &Str = Buf.str();
4720
4721 printf("CAST = %s\n", &Str[0]);
4722 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4723 delete S;
4724 return Replacement;
4725 }
4726#endif
4727 // Return this stmt unmodified.
4728 return S;
4729}
4730
Steve Naroffe70a52a2009-12-05 15:55:59 +00004731void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4732 for (RecordDecl::field_iterator i = RD->field_begin(),
4733 e = RD->field_end(); i != e; ++i) {
4734 FieldDecl *FD = *i;
4735 if (isTopLevelBlockPointerType(FD->getType()))
4736 RewriteBlockPointerDecl(FD);
4737 if (FD->getType()->isObjCQualifiedIdType() ||
4738 FD->getType()->isObjCQualifiedInterfaceType())
4739 RewriteObjCQualifiedInterfaceTypes(FD);
4740 }
4741}
4742
Steve Narofff4b992a2008-10-28 20:29:00 +00004743/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4744/// main file of the input.
4745void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4746 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
Steve Naroffb1368882008-12-17 00:20:22 +00004747 if (FD->isOverloadedOperator())
4748 return;
Mike Stump11289f42009-09-09 15:08:12 +00004749
Steve Narofff4b992a2008-10-28 20:29:00 +00004750 // Since function prototypes don't have ParmDecl's, we check the function
4751 // prototype. This enables us to rewrite function declarations and
4752 // definitions using the same code.
Douglas Gregordeaad8c2009-02-26 23:50:07 +00004753 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004754
Sebastian Redla7b98a72009-04-26 20:35:05 +00004755 // FIXME: If this should support Obj-C++, support CXXTryStmt
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004756 if (CompoundStmt *Body = FD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004757 CurFunctionDef = FD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004758 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004759 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004760 Body =
4761 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4762 FD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004763 CurrentBody = 0;
4764 if (PropParentMap) {
4765 delete PropParentMap;
4766 PropParentMap = 0;
4767 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004768 // This synthesizes and inserts the block "impl" struct, invoke function,
4769 // and any copy/dispose helper functions.
4770 InsertBlockLiteralsWithinFunction(FD);
4771 CurFunctionDef = 0;
Mike Stump11289f42009-09-09 15:08:12 +00004772 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004773 return;
4774 }
4775 if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
Argyrios Kyrtzidisddcd1322009-06-30 02:35:26 +00004776 if (CompoundStmt *Body = MD->getCompoundBody()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004777 CurMethodDef = MD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004778 CollectPropertySetters(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004779 CurrentBody = Body;
Ted Kremenek73980592009-03-12 18:33:24 +00004780 Body =
4781 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4782 MD->setBody(Body);
Steve Naroff1042ff32008-12-08 16:43:47 +00004783 CurrentBody = 0;
4784 if (PropParentMap) {
4785 delete PropParentMap;
4786 PropParentMap = 0;
4787 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004788 InsertBlockLiteralsWithinMethod(MD);
4789 CurMethodDef = 0;
4790 }
4791 }
4792 if (ObjCImplementationDecl *CI = dyn_cast<ObjCImplementationDecl>(D))
4793 ClassImplementation.push_back(CI);
4794 else if (ObjCCategoryImplDecl *CI = dyn_cast<ObjCCategoryImplDecl>(D))
4795 CategoryImplementation.push_back(CI);
4796 else if (ObjCClassDecl *CD = dyn_cast<ObjCClassDecl>(D))
4797 RewriteForwardClassDecl(CD);
4798 else if (VarDecl *VD = dyn_cast<VarDecl>(D)) {
4799 RewriteObjCQualifiedInterfaceTypes(VD);
Steve Naroffa5c0db82008-12-11 21:05:33 +00004800 if (isTopLevelBlockPointerType(VD->getType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004801 RewriteBlockPointerDecl(VD);
Steve Naroffd8907b72008-10-29 18:15:37 +00004802 else if (VD->getType()->isFunctionPointerType()) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004803 CheckFunctionPointerDecl(VD->getType(), VD);
4804 if (VD->getInit()) {
Steve Naroffc989a7b2008-11-03 23:29:32 +00004805 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004806 RewriteCastExpr(CE);
4807 }
4808 }
Steve Naroffe70a52a2009-12-05 15:55:59 +00004809 } else if (VD->getType()->isRecordType()) {
4810 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4811 if (RD->isDefinition())
4812 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004813 }
Steve Naroffd8907b72008-10-29 18:15:37 +00004814 if (VD->getInit()) {
4815 GlobalVarDecl = VD;
Steve Naroff4588d0f2008-12-04 16:24:46 +00004816 CollectPropertySetters(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004817 CurrentBody = VD->getInit();
Steve Naroffd8907b72008-10-29 18:15:37 +00004818 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
Steve Naroff1042ff32008-12-08 16:43:47 +00004819 CurrentBody = 0;
4820 if (PropParentMap) {
4821 delete PropParentMap;
4822 PropParentMap = 0;
4823 }
Mike Stump11289f42009-09-09 15:08:12 +00004824 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(),
Chris Lattner86d7d912008-11-24 03:54:41 +00004825 VD->getNameAsCString());
Steve Naroffd8907b72008-10-29 18:15:37 +00004826 GlobalVarDecl = 0;
4827
4828 // This is needed for blocks.
Steve Naroffc989a7b2008-11-03 23:29:32 +00004829 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
Steve Naroffd8907b72008-10-29 18:15:37 +00004830 RewriteCastExpr(CE);
4831 }
4832 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004833 return;
4834 }
4835 if (TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
Steve Naroffa5c0db82008-12-11 21:05:33 +00004836 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
Steve Narofff4b992a2008-10-28 20:29:00 +00004837 RewriteBlockPointerDecl(TD);
Mike Stump11289f42009-09-09 15:08:12 +00004838 else if (TD->getUnderlyingType()->isFunctionPointerType())
Steve Narofff4b992a2008-10-28 20:29:00 +00004839 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Steve Naroffe70a52a2009-12-05 15:55:59 +00004840 else if (TD->getUnderlyingType()->isRecordType()) {
4841 RecordDecl *RD = TD->getUnderlyingType()->getAs<RecordType>()->getDecl();
4842 if (RD->isDefinition())
4843 RewriteRecordBody(RD);
4844 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004845 return;
4846 }
4847 if (RecordDecl *RD = dyn_cast<RecordDecl>(D)) {
Steve Naroffe70a52a2009-12-05 15:55:59 +00004848 if (RD->isDefinition())
4849 RewriteRecordBody(RD);
Steve Narofff4b992a2008-10-28 20:29:00 +00004850 return;
4851 }
4852 // Nothing yet.
4853}
4854
Chris Lattnercf169832009-03-28 04:11:33 +00004855void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
Steve Narofff4b992a2008-10-28 20:29:00 +00004856 // Get the top-level buffer that this corresponds to.
Mike Stump11289f42009-09-09 15:08:12 +00004857
Steve Narofff4b992a2008-10-28 20:29:00 +00004858 // Rewrite tabs if we care.
4859 //RewriteTabs();
Mike Stump11289f42009-09-09 15:08:12 +00004860
Steve Narofff4b992a2008-10-28 20:29:00 +00004861 if (Diags.hasErrorOccurred())
4862 return;
Mike Stump11289f42009-09-09 15:08:12 +00004863
Steve Narofff4b992a2008-10-28 20:29:00 +00004864 RewriteInclude();
Mike Stump11289f42009-09-09 15:08:12 +00004865
Steve Naroffd9803712009-04-29 16:37:50 +00004866 // Here's a great place to add any extra declarations that may be needed.
4867 // Write out meta data for each @protocol(<expr>).
Mike Stump11289f42009-09-09 15:08:12 +00004868 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Steve Naroffd9803712009-04-29 16:37:50 +00004869 E = ProtocolExprDecls.end(); I != E; ++I)
4870 RewriteObjCProtocolMetaData(*I, "", "", Preamble);
4871
Mike Stump11289f42009-09-09 15:08:12 +00004872 InsertText(SM->getLocForStartOfFile(MainFileID),
Steve Narofff4b992a2008-10-28 20:29:00 +00004873 Preamble.c_str(), Preamble.size(), false);
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004874 if (ClassImplementation.size() || CategoryImplementation.size())
4875 RewriteImplementations();
Steve Naroffd9803712009-04-29 16:37:50 +00004876
Steve Narofff4b992a2008-10-28 20:29:00 +00004877 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
4878 // we are done.
Mike Stump11289f42009-09-09 15:08:12 +00004879 if (const RewriteBuffer *RewriteBuf =
Steve Narofff4b992a2008-10-28 20:29:00 +00004880 Rewrite.getRewriteBufferFor(MainFileID)) {
4881 //printf("Changed:\n");
4882 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4883 } else {
4884 fprintf(stderr, "No changes\n");
4885 }
Steve Narofff8cfd162008-11-13 20:07:04 +00004886
Steve Naroffd9803712009-04-29 16:37:50 +00004887 if (ClassImplementation.size() || CategoryImplementation.size() ||
4888 ProtocolExprDecls.size()) {
Steve Naroff2a2a41f2008-11-14 14:10:01 +00004889 // Rewrite Objective-c meta data*
4890 std::string ResultStr;
4891 SynthesizeMetaDataIntoBuffer(ResultStr);
4892 // Emit metadata.
4893 *OutFile << ResultStr;
4894 }
Steve Narofff4b992a2008-10-28 20:29:00 +00004895 OutFile->flush();
4896}
4897