blob: a113fec39ab026f02d3e2e36ea78aa0f87704fe7 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000022#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000031
32using namespace clang;
33using llvm::utostr;
34
35namespace {
36 class RewriteModernObjC : public ASTConsumer {
37 protected:
38
39 enum {
40 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
41 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
45 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
46 helpers */
47 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
48 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
60 static const int OBJC_ABI_VERSION = 7;
61
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
105 FunctionDecl *SuperContructorFunctionDecl;
106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
120 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
John McCallf4b88a42012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000135
136 // Block related declarations.
137 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
139 SmallVector<ValueDecl *, 8> BlockByRefDecls;
140 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
141 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
142 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
143 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
144
145 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000146 llvm::DenseMap<ObjCInterfaceDecl *,
147 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
148
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000149 // This maps an original source AST to it's rewritten form. This allows
150 // us to avoid rewriting the same node twice (which is very uncommon).
151 // This is needed to support some of the exotic property rewriting.
152 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
153
154 // Needed for header files being rewritten
155 bool IsHeader;
156 bool SilenceRewriteMacroWarning;
157 bool objc_impl_method;
158
159 bool DisableReplaceStmt;
160 class DisableReplaceStmtScope {
161 RewriteModernObjC &R;
162 bool SavedValue;
163
164 public:
165 DisableReplaceStmtScope(RewriteModernObjC &R)
166 : R(R), SavedValue(R.DisableReplaceStmt) {
167 R.DisableReplaceStmt = true;
168 }
169 ~DisableReplaceStmtScope() {
170 R.DisableReplaceStmt = SavedValue;
171 }
172 };
173 void InitializeCommon(ASTContext &context);
174
175 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000176 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000177 // Top Level Driver code.
178 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
179 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
180 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
181 if (!Class->isThisDeclarationADefinition()) {
182 RewriteForwardClassDecl(D);
183 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000184 } else {
185 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000186 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000187 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000188 }
189 }
190
191 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
192 if (!Proto->isThisDeclarationADefinition()) {
193 RewriteForwardProtocolDecl(D);
194 break;
195 }
196 }
197
198 HandleTopLevelSingleDecl(*I);
199 }
200 return true;
201 }
202 void HandleTopLevelSingleDecl(Decl *D);
203 void HandleDeclInMainFile(Decl *D);
204 RewriteModernObjC(std::string inFile, raw_ostream *OS,
205 DiagnosticsEngine &D, const LangOptions &LOpts,
206 bool silenceMacroWarn);
207
208 ~RewriteModernObjC() {}
209
210 virtual void HandleTranslationUnit(ASTContext &C);
211
212 void ReplaceStmt(Stmt *Old, Stmt *New) {
213 Stmt *ReplacingStmt = ReplacedNodes[Old];
214
215 if (ReplacingStmt)
216 return; // We can't rewrite the same node twice.
217
218 if (DisableReplaceStmt)
219 return;
220
221 // If replacement succeeded or warning disabled return with no warning.
222 if (!Rewrite.ReplaceStmt(Old, New)) {
223 ReplacedNodes[Old] = New;
224 return;
225 }
226 if (SilenceRewriteMacroWarning)
227 return;
228 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
229 << Old->getSourceRange();
230 }
231
232 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
233 if (DisableReplaceStmt)
234 return;
235
236 // Measure the old text.
237 int Size = Rewrite.getRangeSize(SrcRange);
238 if (Size == -1) {
239 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
240 << Old->getSourceRange();
241 return;
242 }
243 // Get the new text.
244 std::string SStr;
245 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000246 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000247 const std::string &Str = S.str();
248
249 // If replacement succeeded or warning disabled return with no warning.
250 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
251 ReplacedNodes[Old] = New;
252 return;
253 }
254 if (SilenceRewriteMacroWarning)
255 return;
256 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
257 << Old->getSourceRange();
258 }
259
260 void InsertText(SourceLocation Loc, StringRef Str,
261 bool InsertAfter = true) {
262 // If insertion succeeded or warning disabled return with no warning.
263 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
264 SilenceRewriteMacroWarning)
265 return;
266
267 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
268 }
269
270 void ReplaceText(SourceLocation Start, unsigned OrigLength,
271 StringRef Str) {
272 // If removal succeeded or warning disabled return with no warning.
273 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
274 SilenceRewriteMacroWarning)
275 return;
276
277 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
278 }
279
280 // Syntactic Rewriting.
281 void RewriteRecordBody(RecordDecl *RD);
282 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000283 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000284 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
285 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000286 void RewriteForwardClassDecl(DeclGroupRef D);
287 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
288 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
289 const std::string &typedefString);
290 void RewriteImplementations();
291 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
292 ObjCImplementationDecl *IMD,
293 ObjCCategoryImplDecl *CID);
294 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
295 void RewriteImplementationDecl(Decl *Dcl);
296 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
297 ObjCMethodDecl *MDecl, std::string &ResultStr);
298 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
299 const FunctionType *&FPRetType);
300 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
301 ValueDecl *VD, bool def=false);
302 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
303 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
304 void RewriteForwardProtocolDecl(DeclGroupRef D);
305 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
306 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
307 void RewriteProperty(ObjCPropertyDecl *prop);
308 void RewriteFunctionDecl(FunctionDecl *FD);
309 void RewriteBlockPointerType(std::string& Str, QualType Type);
310 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000311 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000312 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
313 void RewriteTypeOfDecl(VarDecl *VD);
314 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000315
316 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000317
318 // Expression Rewriting.
319 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
320 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
321 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
322 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
323 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
324 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
325 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000326 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000327 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000328 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000329 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000330 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000331 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000332 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000333 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
334 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
335 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
336 SourceLocation OrigEnd);
337 Stmt *RewriteBreakStmt(BreakStmt *S);
338 Stmt *RewriteContinueStmt(ContinueStmt *S);
339 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000340 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000341 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342
343 // Block rewriting.
344 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
345
346 // Block specific rewrite rules.
347 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000348 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000349 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000350 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
351 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
352
353 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
354 std::string &Result);
355
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000356 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000357 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000358 bool &IsNamedDefinition);
359 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
360 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000361
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000362 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
363
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000364 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
365 std::string &Result);
366
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000367 virtual void Initialize(ASTContext &context);
368
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000369 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000370 // rewriting routines on the new ASTs.
371 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
372 Expr **args, unsigned nargs,
373 SourceLocation StartLoc=SourceLocation(),
374 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000375
376 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
377 QualType msgSendType,
378 QualType returnType,
379 SmallVectorImpl<QualType> &ArgTypes,
380 SmallVectorImpl<Expr*> &MsgExprs,
381 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000382
383 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
384 SourceLocation StartLoc=SourceLocation(),
385 SourceLocation EndLoc=SourceLocation());
386
387 void SynthCountByEnumWithState(std::string &buf);
388 void SynthMsgSendFunctionDecl();
389 void SynthMsgSendSuperFunctionDecl();
390 void SynthMsgSendStretFunctionDecl();
391 void SynthMsgSendFpretFunctionDecl();
392 void SynthMsgSendSuperStretFunctionDecl();
393 void SynthGetClassFunctionDecl();
394 void SynthGetMetaClassFunctionDecl();
395 void SynthGetSuperClassFunctionDecl();
396 void SynthSelGetUidFunctionDecl();
397 void SynthSuperContructorFunctionDecl();
398
399 // Rewriting metadata
400 template<typename MethodIterator>
401 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
402 MethodIterator MethodEnd,
403 bool IsInstanceMethod,
404 StringRef prefix,
405 StringRef ClassName,
406 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000407 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
408 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000409 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000410 const ObjCList<ObjCProtocolDecl> &Prots,
411 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000412 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000413 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000414 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000415
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000416 void RewriteMetaDataIntoBuffer(std::string &Result);
417 void WriteImageInfo(std::string &Result);
418 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000419 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000420 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000421
422 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000423 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000424 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000425 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000426
427
428 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
429 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
430 StringRef funcName, std::string Tag);
431 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
432 StringRef funcName, std::string Tag);
433 std::string SynthesizeBlockImpl(BlockExpr *CE,
434 std::string Tag, std::string Desc);
435 std::string SynthesizeBlockDescriptor(std::string DescTag,
436 std::string ImplTag,
437 int i, StringRef funcName,
438 unsigned hasCopy);
439 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
440 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
441 StringRef FunName);
442 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
443 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000444 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445
446 // Misc. helper routines.
447 QualType getProtocolType();
448 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000449 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
450 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
451 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
452
453 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
454 void CollectBlockDeclRefInfo(BlockExpr *Exp);
455 void GetBlockDeclRefExprs(Stmt *S);
456 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000457 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000458 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
459
460 // We avoid calling Type::isBlockPointerType(), since it operates on the
461 // canonical type. We only care if the top-level type is a closure pointer.
462 bool isTopLevelBlockPointerType(QualType T) {
463 return isa<BlockPointerType>(T);
464 }
465
466 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
467 /// to a function pointer type and upon success, returns true; false
468 /// otherwise.
469 bool convertBlockPointerToFunctionPointer(QualType &T) {
470 if (isTopLevelBlockPointerType(T)) {
471 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
472 T = Context->getPointerType(BPT->getPointeeType());
473 return true;
474 }
475 return false;
476 }
477
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000478 bool convertObjCTypeToCStyleType(QualType &T);
479
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480 bool needToScanForQualifiers(QualType T);
481 QualType getSuperStructType();
482 QualType getConstantStringStructType();
483 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
484 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
485
486 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000487 if (T->isObjCQualifiedIdType()) {
488 bool isConst = T.isConstQualified();
489 T = isConst ? Context->getObjCIdType().withConst()
490 : Context->getObjCIdType();
491 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000492 else if (T->isObjCQualifiedClassType())
493 T = Context->getObjCClassType();
494 else if (T->isObjCObjectPointerType() &&
495 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
496 if (const ObjCObjectPointerType * OBJPT =
497 T->getAsObjCInterfacePointerType()) {
498 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
499 T = QualType(IFaceT, 0);
500 T = Context->getPointerType(T);
501 }
502 }
503 }
504
505 // FIXME: This predicate seems like it would be useful to add to ASTContext.
506 bool isObjCType(QualType T) {
507 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
508 return false;
509
510 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
511
512 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
513 OCT == Context->getCanonicalType(Context->getObjCClassType()))
514 return true;
515
516 if (const PointerType *PT = OCT->getAs<PointerType>()) {
517 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
518 PT->getPointeeType()->isObjCQualifiedIdType())
519 return true;
520 }
521 return false;
522 }
523 bool PointerTypeTakesAnyBlockArguments(QualType QT);
524 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
525 void GetExtentOfArgList(const char *Name, const char *&LParen,
526 const char *&RParen);
527
528 void QuoteDoublequotes(std::string &From, std::string &To) {
529 for (unsigned i = 0; i < From.length(); i++) {
530 if (From[i] == '"')
531 To += "\\\"";
532 else
533 To += From[i];
534 }
535 }
536
537 QualType getSimpleFunctionType(QualType result,
538 const QualType *args,
539 unsigned numArgs,
540 bool variadic = false) {
541 if (result == Context->getObjCInstanceType())
542 result = Context->getObjCIdType();
543 FunctionProtoType::ExtProtoInfo fpi;
544 fpi.Variadic = variadic;
545 return Context->getFunctionType(result, args, numArgs, fpi);
546 }
547
548 // Helper function: create a CStyleCastExpr with trivial type source info.
549 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
550 CastKind Kind, Expr *E) {
551 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
552 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
553 SourceLocation(), SourceLocation());
554 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000555
556 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
557 IdentifierInfo* II = &Context->Idents.get("load");
558 Selector LoadSel = Context->Selectors.getSelector(0, &II);
559 return OD->getClassMethod(LoadSel) != 0;
560 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000561 };
562
563}
564
565void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
566 NamedDecl *D) {
567 if (const FunctionProtoType *fproto
568 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
569 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
570 E = fproto->arg_type_end(); I && (I != E); ++I)
571 if (isTopLevelBlockPointerType(*I)) {
572 // All the args are checked/rewritten. Don't call twice!
573 RewriteBlockPointerDecl(D);
574 break;
575 }
576 }
577}
578
579void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
580 const PointerType *PT = funcType->getAs<PointerType>();
581 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
582 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
583}
584
585static bool IsHeaderFile(const std::string &Filename) {
586 std::string::size_type DotPos = Filename.rfind('.');
587
588 if (DotPos == std::string::npos) {
589 // no file extension
590 return false;
591 }
592
593 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
594 // C header: .h
595 // C++ header: .hh or .H;
596 return Ext == "h" || Ext == "hh" || Ext == "H";
597}
598
599RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
600 DiagnosticsEngine &D, const LangOptions &LOpts,
601 bool silenceMacroWarn)
602 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
603 SilenceRewriteMacroWarning(silenceMacroWarn) {
604 IsHeader = IsHeaderFile(inFile);
605 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
606 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000607 // FIXME. This should be an error. But if block is not called, it is OK. And it
608 // may break including some headers.
609 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
610 "rewriting block literal declared in global scope is not implemented");
611
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000612 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
613 DiagnosticsEngine::Warning,
614 "rewriter doesn't support user-specified control flow semantics "
615 "for @try/@finally (code may not execute properly)");
616}
617
618ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
619 raw_ostream* OS,
620 DiagnosticsEngine &Diags,
621 const LangOptions &LOpts,
622 bool SilenceRewriteMacroWarning) {
623 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
624}
625
626void RewriteModernObjC::InitializeCommon(ASTContext &context) {
627 Context = &context;
628 SM = &Context->getSourceManager();
629 TUDecl = Context->getTranslationUnitDecl();
630 MsgSendFunctionDecl = 0;
631 MsgSendSuperFunctionDecl = 0;
632 MsgSendStretFunctionDecl = 0;
633 MsgSendSuperStretFunctionDecl = 0;
634 MsgSendFpretFunctionDecl = 0;
635 GetClassFunctionDecl = 0;
636 GetMetaClassFunctionDecl = 0;
637 GetSuperClassFunctionDecl = 0;
638 SelGetUidFunctionDecl = 0;
639 CFStringFunctionDecl = 0;
640 ConstantStringClassReference = 0;
641 NSStringRecord = 0;
642 CurMethodDef = 0;
643 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000644 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000645 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000646 SuperStructDecl = 0;
647 ProtocolTypeDecl = 0;
648 ConstantStringDecl = 0;
649 BcLabelCount = 0;
650 SuperContructorFunctionDecl = 0;
651 NumObjCStringLiterals = 0;
652 PropParentMap = 0;
653 CurrentBody = 0;
654 DisableReplaceStmt = false;
655 objc_impl_method = false;
656
657 // Get the ID and start/end of the main file.
658 MainFileID = SM->getMainFileID();
659 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
660 MainFileStart = MainBuf->getBufferStart();
661 MainFileEnd = MainBuf->getBufferEnd();
662
David Blaikie4e4d0842012-03-11 07:00:24 +0000663 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000664}
665
666//===----------------------------------------------------------------------===//
667// Top Level Driver Code
668//===----------------------------------------------------------------------===//
669
670void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
671 if (Diags.hasErrorOccurred())
672 return;
673
674 // Two cases: either the decl could be in the main file, or it could be in a
675 // #included file. If the former, rewrite it now. If the later, check to see
676 // if we rewrote the #include/#import.
677 SourceLocation Loc = D->getLocation();
678 Loc = SM->getExpansionLoc(Loc);
679
680 // If this is for a builtin, ignore it.
681 if (Loc.isInvalid()) return;
682
683 // Look for built-in declarations that we need to refer during the rewrite.
684 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
685 RewriteFunctionDecl(FD);
686 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
687 // declared in <Foundation/NSString.h>
688 if (FVD->getName() == "_NSConstantStringClassReference") {
689 ConstantStringClassReference = FVD;
690 return;
691 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000692 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
693 RewriteCategoryDecl(CD);
694 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
695 if (PD->isThisDeclarationADefinition())
696 RewriteProtocolDecl(PD);
697 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000698 // FIXME. This will not work in all situations and leaving it out
699 // is harmless.
700 // RewriteLinkageSpec(LSD);
701
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000702 // Recurse into linkage specifications
703 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
704 DIEnd = LSD->decls_end();
705 DI != DIEnd; ) {
706 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
707 if (!IFace->isThisDeclarationADefinition()) {
708 SmallVector<Decl *, 8> DG;
709 SourceLocation StartLoc = IFace->getLocStart();
710 do {
711 if (isa<ObjCInterfaceDecl>(*DI) &&
712 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
713 StartLoc == (*DI)->getLocStart())
714 DG.push_back(*DI);
715 else
716 break;
717
718 ++DI;
719 } while (DI != DIEnd);
720 RewriteForwardClassDecl(DG);
721 continue;
722 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000723 else {
724 // Keep track of all interface declarations seen.
725 ObjCInterfacesSeen.push_back(IFace);
726 ++DI;
727 continue;
728 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000729 }
730
731 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
732 if (!Proto->isThisDeclarationADefinition()) {
733 SmallVector<Decl *, 8> DG;
734 SourceLocation StartLoc = Proto->getLocStart();
735 do {
736 if (isa<ObjCProtocolDecl>(*DI) &&
737 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
738 StartLoc == (*DI)->getLocStart())
739 DG.push_back(*DI);
740 else
741 break;
742
743 ++DI;
744 } while (DI != DIEnd);
745 RewriteForwardProtocolDecl(DG);
746 continue;
747 }
748 }
749
750 HandleTopLevelSingleDecl(*DI);
751 ++DI;
752 }
753 }
754 // If we have a decl in the main file, see if we should rewrite it.
755 if (SM->isFromMainFile(Loc))
756 return HandleDeclInMainFile(D);
757}
758
759//===----------------------------------------------------------------------===//
760// Syntactic (non-AST) Rewriting Code
761//===----------------------------------------------------------------------===//
762
763void RewriteModernObjC::RewriteInclude() {
764 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
765 StringRef MainBuf = SM->getBufferData(MainFileID);
766 const char *MainBufStart = MainBuf.begin();
767 const char *MainBufEnd = MainBuf.end();
768 size_t ImportLen = strlen("import");
769
770 // Loop over the whole file, looking for includes.
771 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
772 if (*BufPtr == '#') {
773 if (++BufPtr == MainBufEnd)
774 return;
775 while (*BufPtr == ' ' || *BufPtr == '\t')
776 if (++BufPtr == MainBufEnd)
777 return;
778 if (!strncmp(BufPtr, "import", ImportLen)) {
779 // replace import with include
780 SourceLocation ImportLoc =
781 LocStart.getLocWithOffset(BufPtr-MainBufStart);
782 ReplaceText(ImportLoc, ImportLen, "include");
783 BufPtr += ImportLen;
784 }
785 }
786 }
787}
788
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000789static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
790 ObjCIvarDecl *IvarDecl, std::string &Result) {
791 Result += "OBJC_IVAR_$_";
792 Result += IDecl->getName();
793 Result += "$";
794 Result += IvarDecl->getName();
795}
796
797std::string
798RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
799 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
800
801 // Build name of symbol holding ivar offset.
802 std::string IvarOffsetName;
803 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
804
805
806 std::string S = "(*(";
807 QualType IvarT = D->getType();
808
809 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
810 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
811 RD = RD->getDefinition();
812 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
813 // decltype(((Foo_IMPL*)0)->bar) *
814 ObjCContainerDecl *CDecl =
815 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
816 // ivar in class extensions requires special treatment.
817 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
818 CDecl = CatDecl->getClassInterface();
819 std::string RecName = CDecl->getName();
820 RecName += "_IMPL";
821 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
822 SourceLocation(), SourceLocation(),
823 &Context->Idents.get(RecName.c_str()));
824 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
825 unsigned UnsignedIntSize =
826 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
827 Expr *Zero = IntegerLiteral::Create(*Context,
828 llvm::APInt(UnsignedIntSize, 0),
829 Context->UnsignedIntTy, SourceLocation());
830 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
831 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
832 Zero);
833 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
834 SourceLocation(),
835 &Context->Idents.get(D->getNameAsString()),
836 IvarT, 0,
837 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000838 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000839 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
840 FD->getType(), VK_LValue,
841 OK_Ordinary);
842 IvarT = Context->getDecltypeType(ME, ME->getType());
843 }
844 }
845 convertObjCTypeToCStyleType(IvarT);
846 QualType castT = Context->getPointerType(IvarT);
847 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
848 S += TypeString;
849 S += ")";
850
851 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
852 S += "((char *)self + ";
853 S += IvarOffsetName;
854 S += "))";
855 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000856 return S;
857}
858
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000859/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
860/// been found in the class implementation. In this case, it must be synthesized.
861static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
862 ObjCPropertyDecl *PD,
863 bool getter) {
864 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
865 : !IMP->getInstanceMethod(PD->getSetterName());
866
867}
868
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000869void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
870 ObjCImplementationDecl *IMD,
871 ObjCCategoryImplDecl *CID) {
872 static bool objcGetPropertyDefined = false;
873 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000874 SourceLocation startGetterSetterLoc;
875
876 if (PID->getLocStart().isValid()) {
877 SourceLocation startLoc = PID->getLocStart();
878 InsertText(startLoc, "// ");
879 const char *startBuf = SM->getCharacterData(startLoc);
880 assert((*startBuf == '@') && "bogus @synthesize location");
881 const char *semiBuf = strchr(startBuf, ';');
882 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
883 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
884 }
885 else
886 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000887
888 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
889 return; // FIXME: is this correct?
890
891 // Generate the 'getter' function.
892 ObjCPropertyDecl *PD = PID->getPropertyDecl();
893 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
894
895 if (!OID)
896 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000897 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000898 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000899 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
900 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000901 ObjCPropertyDecl::OBJC_PR_copy));
902 std::string Getr;
903 if (GenGetProperty && !objcGetPropertyDefined) {
904 objcGetPropertyDefined = true;
905 // FIXME. Is this attribute correct in all cases?
906 Getr = "\nextern \"C\" __declspec(dllimport) "
907 "id objc_getProperty(id, SEL, long, bool);\n";
908 }
909 RewriteObjCMethodDecl(OID->getContainingInterface(),
910 PD->getGetterMethodDecl(), Getr);
911 Getr += "{ ";
912 // Synthesize an explicit cast to gain access to the ivar.
913 // See objc-act.c:objc_synthesize_new_getter() for details.
914 if (GenGetProperty) {
915 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
916 Getr += "typedef ";
917 const FunctionType *FPRetType = 0;
918 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
919 FPRetType);
920 Getr += " _TYPE";
921 if (FPRetType) {
922 Getr += ")"; // close the precedence "scope" for "*".
923
924 // Now, emit the argument types (if any).
925 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
926 Getr += "(";
927 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
928 if (i) Getr += ", ";
929 std::string ParamStr = FT->getArgType(i).getAsString(
930 Context->getPrintingPolicy());
931 Getr += ParamStr;
932 }
933 if (FT->isVariadic()) {
934 if (FT->getNumArgs()) Getr += ", ";
935 Getr += "...";
936 }
937 Getr += ")";
938 } else
939 Getr += "()";
940 }
941 Getr += ";\n";
942 Getr += "return (_TYPE)";
943 Getr += "objc_getProperty(self, _cmd, ";
944 RewriteIvarOffsetComputation(OID, Getr);
945 Getr += ", 1)";
946 }
947 else
948 Getr += "return " + getIvarAccessString(OID);
949 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000950 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000951 }
952
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000953 if (PD->isReadOnly() ||
954 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000955 return;
956
957 // Generate the 'setter' function.
958 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000959 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000960 ObjCPropertyDecl::OBJC_PR_copy);
961 if (GenSetProperty && !objcSetPropertyDefined) {
962 objcSetPropertyDefined = true;
963 // FIXME. Is this attribute correct in all cases?
964 Setr = "\nextern \"C\" __declspec(dllimport) "
965 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
966 }
967
968 RewriteObjCMethodDecl(OID->getContainingInterface(),
969 PD->getSetterMethodDecl(), Setr);
970 Setr += "{ ";
971 // Synthesize an explicit cast to initialize the ivar.
972 // See objc-act.c:objc_synthesize_new_setter() for details.
973 if (GenSetProperty) {
974 Setr += "objc_setProperty (self, _cmd, ";
975 RewriteIvarOffsetComputation(OID, Setr);
976 Setr += ", (id)";
977 Setr += PD->getName();
978 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000979 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000980 Setr += "0, ";
981 else
982 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +0000983 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000984 Setr += "1)";
985 else
986 Setr += "0)";
987 }
988 else {
989 Setr += getIvarAccessString(OID) + " = ";
990 Setr += PD->getName();
991 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000992 Setr += "; }\n";
993 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000994}
995
996static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
997 std::string &typedefString) {
998 typedefString += "#ifndef _REWRITER_typedef_";
999 typedefString += ForwardDecl->getNameAsString();
1000 typedefString += "\n";
1001 typedefString += "#define _REWRITER_typedef_";
1002 typedefString += ForwardDecl->getNameAsString();
1003 typedefString += "\n";
1004 typedefString += "typedef struct objc_object ";
1005 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001006 // typedef struct { } _objc_exc_Classname;
1007 typedefString += ";\ntypedef struct {} _objc_exc_";
1008 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001009 typedefString += ";\n#endif\n";
1010}
1011
1012void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1013 const std::string &typedefString) {
1014 SourceLocation startLoc = ClassDecl->getLocStart();
1015 const char *startBuf = SM->getCharacterData(startLoc);
1016 const char *semiPtr = strchr(startBuf, ';');
1017 // Replace the @class with typedefs corresponding to the classes.
1018 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1019}
1020
1021void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1022 std::string typedefString;
1023 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1024 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1025 if (I == D.begin()) {
1026 // Translate to typedef's that forward reference structs with the same name
1027 // as the class. As a convenience, we include the original declaration
1028 // as a comment.
1029 typedefString += "// @class ";
1030 typedefString += ForwardDecl->getNameAsString();
1031 typedefString += ";\n";
1032 }
1033 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1034 }
1035 DeclGroupRef::iterator I = D.begin();
1036 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1037}
1038
1039void RewriteModernObjC::RewriteForwardClassDecl(
1040 const llvm::SmallVector<Decl*, 8> &D) {
1041 std::string typedefString;
1042 for (unsigned i = 0; i < D.size(); i++) {
1043 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1044 if (i == 0) {
1045 typedefString += "// @class ";
1046 typedefString += ForwardDecl->getNameAsString();
1047 typedefString += ";\n";
1048 }
1049 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1050 }
1051 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1052}
1053
1054void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1055 // When method is a synthesized one, such as a getter/setter there is
1056 // nothing to rewrite.
1057 if (Method->isImplicit())
1058 return;
1059 SourceLocation LocStart = Method->getLocStart();
1060 SourceLocation LocEnd = Method->getLocEnd();
1061
1062 if (SM->getExpansionLineNumber(LocEnd) >
1063 SM->getExpansionLineNumber(LocStart)) {
1064 InsertText(LocStart, "#if 0\n");
1065 ReplaceText(LocEnd, 1, ";\n#endif\n");
1066 } else {
1067 InsertText(LocStart, "// ");
1068 }
1069}
1070
1071void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1072 SourceLocation Loc = prop->getAtLoc();
1073
1074 ReplaceText(Loc, 0, "// ");
1075 // FIXME: handle properties that are declared across multiple lines.
1076}
1077
1078void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1079 SourceLocation LocStart = CatDecl->getLocStart();
1080
1081 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001082 if (CatDecl->getIvarRBraceLoc().isValid()) {
1083 ReplaceText(LocStart, 1, "/** ");
1084 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1085 }
1086 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001087 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001088 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001089
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001090 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1091 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001092 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001093
1094 for (ObjCCategoryDecl::instmeth_iterator
1095 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1096 I != E; ++I)
1097 RewriteMethodDeclaration(*I);
1098 for (ObjCCategoryDecl::classmeth_iterator
1099 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1100 I != E; ++I)
1101 RewriteMethodDeclaration(*I);
1102
1103 // Lastly, comment out the @end.
1104 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1105 strlen("@end"), "/* @end */");
1106}
1107
1108void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1109 SourceLocation LocStart = PDecl->getLocStart();
1110 assert(PDecl->isThisDeclarationADefinition());
1111
1112 // FIXME: handle protocol headers that are declared across multiple lines.
1113 ReplaceText(LocStart, 0, "// ");
1114
1115 for (ObjCProtocolDecl::instmeth_iterator
1116 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1117 I != E; ++I)
1118 RewriteMethodDeclaration(*I);
1119 for (ObjCProtocolDecl::classmeth_iterator
1120 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1121 I != E; ++I)
1122 RewriteMethodDeclaration(*I);
1123
1124 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1125 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001126 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001127
1128 // Lastly, comment out the @end.
1129 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1130 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1131
1132 // Must comment out @optional/@required
1133 const char *startBuf = SM->getCharacterData(LocStart);
1134 const char *endBuf = SM->getCharacterData(LocEnd);
1135 for (const char *p = startBuf; p < endBuf; p++) {
1136 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1137 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1138 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1139
1140 }
1141 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1142 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1143 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1144
1145 }
1146 }
1147}
1148
1149void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1150 SourceLocation LocStart = (*D.begin())->getLocStart();
1151 if (LocStart.isInvalid())
1152 llvm_unreachable("Invalid SourceLocation");
1153 // FIXME: handle forward protocol that are declared across multiple lines.
1154 ReplaceText(LocStart, 0, "// ");
1155}
1156
1157void
1158RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1159 SourceLocation LocStart = DG[0]->getLocStart();
1160 if (LocStart.isInvalid())
1161 llvm_unreachable("Invalid SourceLocation");
1162 // FIXME: handle forward protocol that are declared across multiple lines.
1163 ReplaceText(LocStart, 0, "// ");
1164}
1165
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001166void
1167RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1168 SourceLocation LocStart = LSD->getExternLoc();
1169 if (LocStart.isInvalid())
1170 llvm_unreachable("Invalid extern SourceLocation");
1171
1172 ReplaceText(LocStart, 0, "// ");
1173 if (!LSD->hasBraces())
1174 return;
1175 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1176 SourceLocation LocRBrace = LSD->getRBraceLoc();
1177 if (LocRBrace.isInvalid())
1178 llvm_unreachable("Invalid rbrace SourceLocation");
1179 ReplaceText(LocRBrace, 0, "// ");
1180}
1181
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001182void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1183 const FunctionType *&FPRetType) {
1184 if (T->isObjCQualifiedIdType())
1185 ResultStr += "id";
1186 else if (T->isFunctionPointerType() ||
1187 T->isBlockPointerType()) {
1188 // needs special handling, since pointer-to-functions have special
1189 // syntax (where a decaration models use).
1190 QualType retType = T;
1191 QualType PointeeTy;
1192 if (const PointerType* PT = retType->getAs<PointerType>())
1193 PointeeTy = PT->getPointeeType();
1194 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1195 PointeeTy = BPT->getPointeeType();
1196 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1197 ResultStr += FPRetType->getResultType().getAsString(
1198 Context->getPrintingPolicy());
1199 ResultStr += "(*";
1200 }
1201 } else
1202 ResultStr += T.getAsString(Context->getPrintingPolicy());
1203}
1204
1205void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1206 ObjCMethodDecl *OMD,
1207 std::string &ResultStr) {
1208 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1209 const FunctionType *FPRetType = 0;
1210 ResultStr += "\nstatic ";
1211 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1212 ResultStr += " ";
1213
1214 // Unique method name
1215 std::string NameStr;
1216
1217 if (OMD->isInstanceMethod())
1218 NameStr += "_I_";
1219 else
1220 NameStr += "_C_";
1221
1222 NameStr += IDecl->getNameAsString();
1223 NameStr += "_";
1224
1225 if (ObjCCategoryImplDecl *CID =
1226 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1227 NameStr += CID->getNameAsString();
1228 NameStr += "_";
1229 }
1230 // Append selector names, replacing ':' with '_'
1231 {
1232 std::string selString = OMD->getSelector().getAsString();
1233 int len = selString.size();
1234 for (int i = 0; i < len; i++)
1235 if (selString[i] == ':')
1236 selString[i] = '_';
1237 NameStr += selString;
1238 }
1239 // Remember this name for metadata emission
1240 MethodInternalNames[OMD] = NameStr;
1241 ResultStr += NameStr;
1242
1243 // Rewrite arguments
1244 ResultStr += "(";
1245
1246 // invisible arguments
1247 if (OMD->isInstanceMethod()) {
1248 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1249 selfTy = Context->getPointerType(selfTy);
1250 if (!LangOpts.MicrosoftExt) {
1251 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1252 ResultStr += "struct ";
1253 }
1254 // When rewriting for Microsoft, explicitly omit the structure name.
1255 ResultStr += IDecl->getNameAsString();
1256 ResultStr += " *";
1257 }
1258 else
1259 ResultStr += Context->getObjCClassType().getAsString(
1260 Context->getPrintingPolicy());
1261
1262 ResultStr += " self, ";
1263 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1264 ResultStr += " _cmd";
1265
1266 // Method arguments.
1267 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1268 E = OMD->param_end(); PI != E; ++PI) {
1269 ParmVarDecl *PDecl = *PI;
1270 ResultStr += ", ";
1271 if (PDecl->getType()->isObjCQualifiedIdType()) {
1272 ResultStr += "id ";
1273 ResultStr += PDecl->getNameAsString();
1274 } else {
1275 std::string Name = PDecl->getNameAsString();
1276 QualType QT = PDecl->getType();
1277 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001278 (void)convertBlockPointerToFunctionPointer(QT);
1279 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001280 ResultStr += Name;
1281 }
1282 }
1283 if (OMD->isVariadic())
1284 ResultStr += ", ...";
1285 ResultStr += ") ";
1286
1287 if (FPRetType) {
1288 ResultStr += ")"; // close the precedence "scope" for "*".
1289
1290 // Now, emit the argument types (if any).
1291 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1292 ResultStr += "(";
1293 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1294 if (i) ResultStr += ", ";
1295 std::string ParamStr = FT->getArgType(i).getAsString(
1296 Context->getPrintingPolicy());
1297 ResultStr += ParamStr;
1298 }
1299 if (FT->isVariadic()) {
1300 if (FT->getNumArgs()) ResultStr += ", ";
1301 ResultStr += "...";
1302 }
1303 ResultStr += ")";
1304 } else {
1305 ResultStr += "()";
1306 }
1307 }
1308}
1309void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1310 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1311 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1312
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001313 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001314 if (IMD->getIvarRBraceLoc().isValid()) {
1315 ReplaceText(IMD->getLocStart(), 1, "/** ");
1316 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001317 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001318 else {
1319 InsertText(IMD->getLocStart(), "// ");
1320 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001321 }
1322 else
1323 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001324
1325 for (ObjCCategoryImplDecl::instmeth_iterator
1326 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1327 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1328 I != E; ++I) {
1329 std::string ResultStr;
1330 ObjCMethodDecl *OMD = *I;
1331 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1332 SourceLocation LocStart = OMD->getLocStart();
1333 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1334
1335 const char *startBuf = SM->getCharacterData(LocStart);
1336 const char *endBuf = SM->getCharacterData(LocEnd);
1337 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1338 }
1339
1340 for (ObjCCategoryImplDecl::classmeth_iterator
1341 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1342 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1343 I != E; ++I) {
1344 std::string ResultStr;
1345 ObjCMethodDecl *OMD = *I;
1346 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1347 SourceLocation LocStart = OMD->getLocStart();
1348 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1349
1350 const char *startBuf = SM->getCharacterData(LocStart);
1351 const char *endBuf = SM->getCharacterData(LocEnd);
1352 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1353 }
1354 for (ObjCCategoryImplDecl::propimpl_iterator
1355 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1356 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1357 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001358 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001359 }
1360
1361 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1362}
1363
1364void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001365 // Do not synthesize more than once.
1366 if (ObjCSynthesizedStructs.count(ClassDecl))
1367 return;
1368 // Make sure super class's are written before current class is written.
1369 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1370 while (SuperClass) {
1371 RewriteInterfaceDecl(SuperClass);
1372 SuperClass = SuperClass->getSuperClass();
1373 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001374 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001375 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001376 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001377 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001378 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1379
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001380 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001381 // Mark this typedef as having been written into its c++ equivalent.
1382 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001383
1384 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001385 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001386 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001387 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001388 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001389 I != E; ++I)
1390 RewriteMethodDeclaration(*I);
1391 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001392 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001393 I != E; ++I)
1394 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001395
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001396 // Lastly, comment out the @end.
1397 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1398 "/* @end */");
1399 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001400}
1401
1402Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1403 SourceRange OldRange = PseudoOp->getSourceRange();
1404
1405 // We just magically know some things about the structure of this
1406 // expression.
1407 ObjCMessageExpr *OldMsg =
1408 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1409 PseudoOp->getNumSemanticExprs() - 1));
1410
1411 // Because the rewriter doesn't allow us to rewrite rewritten code,
1412 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001413 Expr *Base;
1414 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001415 {
1416 DisableReplaceStmtScope S(*this);
1417
1418 // Rebuild the base expression if we have one.
1419 Base = 0;
1420 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1421 Base = OldMsg->getInstanceReceiver();
1422 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1423 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1424 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001425
1426 unsigned numArgs = OldMsg->getNumArgs();
1427 for (unsigned i = 0; i < numArgs; i++) {
1428 Expr *Arg = OldMsg->getArg(i);
1429 if (isa<OpaqueValueExpr>(Arg))
1430 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1431 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1432 Args.push_back(Arg);
1433 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001434 }
1435
1436 // TODO: avoid this copy.
1437 SmallVector<SourceLocation, 1> SelLocs;
1438 OldMsg->getSelectorLocs(SelLocs);
1439
1440 ObjCMessageExpr *NewMsg = 0;
1441 switch (OldMsg->getReceiverKind()) {
1442 case ObjCMessageExpr::Class:
1443 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1444 OldMsg->getValueKind(),
1445 OldMsg->getLeftLoc(),
1446 OldMsg->getClassReceiverTypeInfo(),
1447 OldMsg->getSelector(),
1448 SelLocs,
1449 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001450 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001451 OldMsg->getRightLoc(),
1452 OldMsg->isImplicit());
1453 break;
1454
1455 case ObjCMessageExpr::Instance:
1456 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1457 OldMsg->getValueKind(),
1458 OldMsg->getLeftLoc(),
1459 Base,
1460 OldMsg->getSelector(),
1461 SelLocs,
1462 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001463 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001464 OldMsg->getRightLoc(),
1465 OldMsg->isImplicit());
1466 break;
1467
1468 case ObjCMessageExpr::SuperClass:
1469 case ObjCMessageExpr::SuperInstance:
1470 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1471 OldMsg->getValueKind(),
1472 OldMsg->getLeftLoc(),
1473 OldMsg->getSuperLoc(),
1474 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1475 OldMsg->getSuperType(),
1476 OldMsg->getSelector(),
1477 SelLocs,
1478 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001479 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001480 OldMsg->getRightLoc(),
1481 OldMsg->isImplicit());
1482 break;
1483 }
1484
1485 Stmt *Replacement = SynthMessageExpr(NewMsg);
1486 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1487 return Replacement;
1488}
1489
1490Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1491 SourceRange OldRange = PseudoOp->getSourceRange();
1492
1493 // We just magically know some things about the structure of this
1494 // expression.
1495 ObjCMessageExpr *OldMsg =
1496 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1497
1498 // Because the rewriter doesn't allow us to rewrite rewritten code,
1499 // we need to suppress rewriting the sub-statements.
1500 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001501 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001502 {
1503 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001504 // Rebuild the base expression if we have one.
1505 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1506 Base = OldMsg->getInstanceReceiver();
1507 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1508 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1509 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001510 unsigned numArgs = OldMsg->getNumArgs();
1511 for (unsigned i = 0; i < numArgs; i++) {
1512 Expr *Arg = OldMsg->getArg(i);
1513 if (isa<OpaqueValueExpr>(Arg))
1514 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1515 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1516 Args.push_back(Arg);
1517 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001518 }
1519
1520 // Intentionally empty.
1521 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001522
1523 ObjCMessageExpr *NewMsg = 0;
1524 switch (OldMsg->getReceiverKind()) {
1525 case ObjCMessageExpr::Class:
1526 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1527 OldMsg->getValueKind(),
1528 OldMsg->getLeftLoc(),
1529 OldMsg->getClassReceiverTypeInfo(),
1530 OldMsg->getSelector(),
1531 SelLocs,
1532 OldMsg->getMethodDecl(),
1533 Args,
1534 OldMsg->getRightLoc(),
1535 OldMsg->isImplicit());
1536 break;
1537
1538 case ObjCMessageExpr::Instance:
1539 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1540 OldMsg->getValueKind(),
1541 OldMsg->getLeftLoc(),
1542 Base,
1543 OldMsg->getSelector(),
1544 SelLocs,
1545 OldMsg->getMethodDecl(),
1546 Args,
1547 OldMsg->getRightLoc(),
1548 OldMsg->isImplicit());
1549 break;
1550
1551 case ObjCMessageExpr::SuperClass:
1552 case ObjCMessageExpr::SuperInstance:
1553 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1554 OldMsg->getValueKind(),
1555 OldMsg->getLeftLoc(),
1556 OldMsg->getSuperLoc(),
1557 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1558 OldMsg->getSuperType(),
1559 OldMsg->getSelector(),
1560 SelLocs,
1561 OldMsg->getMethodDecl(),
1562 Args,
1563 OldMsg->getRightLoc(),
1564 OldMsg->isImplicit());
1565 break;
1566 }
1567
1568 Stmt *Replacement = SynthMessageExpr(NewMsg);
1569 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1570 return Replacement;
1571}
1572
1573/// SynthCountByEnumWithState - To print:
1574/// ((unsigned int (*)
1575/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1576/// (void *)objc_msgSend)((id)l_collection,
1577/// sel_registerName(
1578/// "countByEnumeratingWithState:objects:count:"),
1579/// &enumState,
1580/// (id *)__rw_items, (unsigned int)16)
1581///
1582void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1583 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1584 "id *, unsigned int))(void *)objc_msgSend)";
1585 buf += "\n\t\t";
1586 buf += "((id)l_collection,\n\t\t";
1587 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1588 buf += "\n\t\t";
1589 buf += "&enumState, "
1590 "(id *)__rw_items, (unsigned int)16)";
1591}
1592
1593/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1594/// statement to exit to its outer synthesized loop.
1595///
1596Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1597 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1598 return S;
1599 // replace break with goto __break_label
1600 std::string buf;
1601
1602 SourceLocation startLoc = S->getLocStart();
1603 buf = "goto __break_label_";
1604 buf += utostr(ObjCBcLabelNo.back());
1605 ReplaceText(startLoc, strlen("break"), buf);
1606
1607 return 0;
1608}
1609
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001610void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1611 SourceLocation Loc,
1612 std::string &LineString) {
1613 if (Loc.isFileID()) {
1614 LineString += "\n#line ";
1615 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1616 LineString += utostr(PLoc.getLine());
1617 LineString += " \"";
1618 LineString += Lexer::Stringify(PLoc.getFilename());
1619 LineString += "\"\n";
1620 }
1621}
1622
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001623/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1624/// statement to continue with its inner synthesized loop.
1625///
1626Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1627 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1628 return S;
1629 // replace continue with goto __continue_label
1630 std::string buf;
1631
1632 SourceLocation startLoc = S->getLocStart();
1633 buf = "goto __continue_label_";
1634 buf += utostr(ObjCBcLabelNo.back());
1635 ReplaceText(startLoc, strlen("continue"), buf);
1636
1637 return 0;
1638}
1639
1640/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1641/// It rewrites:
1642/// for ( type elem in collection) { stmts; }
1643
1644/// Into:
1645/// {
1646/// type elem;
1647/// struct __objcFastEnumerationState enumState = { 0 };
1648/// id __rw_items[16];
1649/// id l_collection = (id)collection;
1650/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1651/// objects:__rw_items count:16];
1652/// if (limit) {
1653/// unsigned long startMutations = *enumState.mutationsPtr;
1654/// do {
1655/// unsigned long counter = 0;
1656/// do {
1657/// if (startMutations != *enumState.mutationsPtr)
1658/// objc_enumerationMutation(l_collection);
1659/// elem = (type)enumState.itemsPtr[counter++];
1660/// stmts;
1661/// __continue_label: ;
1662/// } while (counter < limit);
1663/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1664/// objects:__rw_items count:16]);
1665/// elem = nil;
1666/// __break_label: ;
1667/// }
1668/// else
1669/// elem = nil;
1670/// }
1671///
1672Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1673 SourceLocation OrigEnd) {
1674 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1675 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1676 "ObjCForCollectionStmt Statement stack mismatch");
1677 assert(!ObjCBcLabelNo.empty() &&
1678 "ObjCForCollectionStmt - Label No stack empty");
1679
1680 SourceLocation startLoc = S->getLocStart();
1681 const char *startBuf = SM->getCharacterData(startLoc);
1682 StringRef elementName;
1683 std::string elementTypeAsString;
1684 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001685 // line directive first.
1686 SourceLocation ForEachLoc = S->getForLoc();
1687 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1688 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001689 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1690 // type elem;
1691 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1692 QualType ElementType = cast<ValueDecl>(D)->getType();
1693 if (ElementType->isObjCQualifiedIdType() ||
1694 ElementType->isObjCQualifiedInterfaceType())
1695 // Simply use 'id' for all qualified types.
1696 elementTypeAsString = "id";
1697 else
1698 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1699 buf += elementTypeAsString;
1700 buf += " ";
1701 elementName = D->getName();
1702 buf += elementName;
1703 buf += ";\n\t";
1704 }
1705 else {
1706 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1707 elementName = DR->getDecl()->getName();
1708 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1709 if (VD->getType()->isObjCQualifiedIdType() ||
1710 VD->getType()->isObjCQualifiedInterfaceType())
1711 // Simply use 'id' for all qualified types.
1712 elementTypeAsString = "id";
1713 else
1714 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1715 }
1716
1717 // struct __objcFastEnumerationState enumState = { 0 };
1718 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1719 // id __rw_items[16];
1720 buf += "id __rw_items[16];\n\t";
1721 // id l_collection = (id)
1722 buf += "id l_collection = (id)";
1723 // Find start location of 'collection' the hard way!
1724 const char *startCollectionBuf = startBuf;
1725 startCollectionBuf += 3; // skip 'for'
1726 startCollectionBuf = strchr(startCollectionBuf, '(');
1727 startCollectionBuf++; // skip '('
1728 // find 'in' and skip it.
1729 while (*startCollectionBuf != ' ' ||
1730 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1731 (*(startCollectionBuf+3) != ' ' &&
1732 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1733 startCollectionBuf++;
1734 startCollectionBuf += 3;
1735
1736 // Replace: "for (type element in" with string constructed thus far.
1737 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1738 // Replace ')' in for '(' type elem in collection ')' with ';'
1739 SourceLocation rightParenLoc = S->getRParenLoc();
1740 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1741 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1742 buf = ";\n\t";
1743
1744 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1745 // objects:__rw_items count:16];
1746 // which is synthesized into:
1747 // unsigned int limit =
1748 // ((unsigned int (*)
1749 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1750 // (void *)objc_msgSend)((id)l_collection,
1751 // sel_registerName(
1752 // "countByEnumeratingWithState:objects:count:"),
1753 // (struct __objcFastEnumerationState *)&state,
1754 // (id *)__rw_items, (unsigned int)16);
1755 buf += "unsigned long limit =\n\t\t";
1756 SynthCountByEnumWithState(buf);
1757 buf += ";\n\t";
1758 /// if (limit) {
1759 /// unsigned long startMutations = *enumState.mutationsPtr;
1760 /// do {
1761 /// unsigned long counter = 0;
1762 /// do {
1763 /// if (startMutations != *enumState.mutationsPtr)
1764 /// objc_enumerationMutation(l_collection);
1765 /// elem = (type)enumState.itemsPtr[counter++];
1766 buf += "if (limit) {\n\t";
1767 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1768 buf += "do {\n\t\t";
1769 buf += "unsigned long counter = 0;\n\t\t";
1770 buf += "do {\n\t\t\t";
1771 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1772 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1773 buf += elementName;
1774 buf += " = (";
1775 buf += elementTypeAsString;
1776 buf += ")enumState.itemsPtr[counter++];";
1777 // Replace ')' in for '(' type elem in collection ')' with all of these.
1778 ReplaceText(lparenLoc, 1, buf);
1779
1780 /// __continue_label: ;
1781 /// } while (counter < limit);
1782 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1783 /// objects:__rw_items count:16]);
1784 /// elem = nil;
1785 /// __break_label: ;
1786 /// }
1787 /// else
1788 /// elem = nil;
1789 /// }
1790 ///
1791 buf = ";\n\t";
1792 buf += "__continue_label_";
1793 buf += utostr(ObjCBcLabelNo.back());
1794 buf += ": ;";
1795 buf += "\n\t\t";
1796 buf += "} while (counter < limit);\n\t";
1797 buf += "} while (limit = ";
1798 SynthCountByEnumWithState(buf);
1799 buf += ");\n\t";
1800 buf += elementName;
1801 buf += " = ((";
1802 buf += elementTypeAsString;
1803 buf += ")0);\n\t";
1804 buf += "__break_label_";
1805 buf += utostr(ObjCBcLabelNo.back());
1806 buf += ": ;\n\t";
1807 buf += "}\n\t";
1808 buf += "else\n\t\t";
1809 buf += elementName;
1810 buf += " = ((";
1811 buf += elementTypeAsString;
1812 buf += ")0);\n\t";
1813 buf += "}\n";
1814
1815 // Insert all these *after* the statement body.
1816 // FIXME: If this should support Obj-C++, support CXXTryStmt
1817 if (isa<CompoundStmt>(S->getBody())) {
1818 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1819 InsertText(endBodyLoc, buf);
1820 } else {
1821 /* Need to treat single statements specially. For example:
1822 *
1823 * for (A *a in b) if (stuff()) break;
1824 * for (A *a in b) xxxyy;
1825 *
1826 * The following code simply scans ahead to the semi to find the actual end.
1827 */
1828 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1829 const char *semiBuf = strchr(stmtBuf, ';');
1830 assert(semiBuf && "Can't find ';'");
1831 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1832 InsertText(endBodyLoc, buf);
1833 }
1834 Stmts.pop_back();
1835 ObjCBcLabelNo.pop_back();
1836 return 0;
1837}
1838
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001839static void Write_RethrowObject(std::string &buf) {
1840 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1841 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1842 buf += "\tid rethrow;\n";
1843 buf += "\t} _fin_force_rethow(_rethrow);";
1844}
1845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001846/// RewriteObjCSynchronizedStmt -
1847/// This routine rewrites @synchronized(expr) stmt;
1848/// into:
1849/// objc_sync_enter(expr);
1850/// @try stmt @finally { objc_sync_exit(expr); }
1851///
1852Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1853 // Get the start location and compute the semi location.
1854 SourceLocation startLoc = S->getLocStart();
1855 const char *startBuf = SM->getCharacterData(startLoc);
1856
1857 assert((*startBuf == '@') && "bogus @synchronized location");
1858
1859 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001860 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1861 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1862 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001864 const char *lparenBuf = startBuf;
1865 while (*lparenBuf != '(') lparenBuf++;
1866 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001867
1868 buf = "; objc_sync_enter(_sync_obj);\n";
1869 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1870 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1871 buf += "\n\tid sync_exit;";
1872 buf += "\n\t} _sync_exit(_sync_obj);\n";
1873
1874 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1875 // the sync expression is typically a message expression that's already
1876 // been rewritten! (which implies the SourceLocation's are invalid).
1877 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1878 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1879 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1880 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1881
1882 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1883 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1884 assert (*LBraceLocBuf == '{');
1885 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001886
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001887 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001888 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1889 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001890
1891 buf = "} catch (id e) {_rethrow = e;}\n";
1892 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001893 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001894 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001895
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001896 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001897
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001898 return 0;
1899}
1900
1901void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1902{
1903 // Perform a bottom up traversal of all children.
1904 for (Stmt::child_range CI = S->children(); CI; ++CI)
1905 if (*CI)
1906 WarnAboutReturnGotoStmts(*CI);
1907
1908 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1909 Diags.Report(Context->getFullLoc(S->getLocStart()),
1910 TryFinallyContainsReturnDiag);
1911 }
1912 return;
1913}
1914
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001915Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1916 SourceLocation startLoc = S->getAtLoc();
1917 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001918 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1919 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001920
1921 return 0;
1922}
1923
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001924Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001925 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001926 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001927 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001928 SourceLocation TryLocation = S->getAtTryLoc();
1929 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001930
1931 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001932 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001933 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001934 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001935 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001936 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001937 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001938 // Get the start location and compute the semi location.
1939 SourceLocation startLoc = S->getLocStart();
1940 const char *startBuf = SM->getCharacterData(startLoc);
1941
1942 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001943 if (finalStmt)
1944 ReplaceText(startLoc, 1, buf);
1945 else
1946 // @try -> try
1947 ReplaceText(startLoc, 1, "");
1948
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001949 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1950 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001951 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001952
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001953 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001954 bool AtRemoved = false;
1955 if (catchDecl) {
1956 QualType t = catchDecl->getType();
1957 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1958 // Should be a pointer to a class.
1959 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1960 if (IDecl) {
1961 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001962 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1963
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001964 startBuf = SM->getCharacterData(startLoc);
1965 assert((*startBuf == '@') && "bogus @catch location");
1966 SourceLocation rParenLoc = Catch->getRParenLoc();
1967 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1968
1969 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001970 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001971 Result += " *_"; Result += catchDecl->getNameAsString();
1972 Result += ")";
1973 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1974 // Foo *e = (Foo *)_e;
1975 Result.clear();
1976 Result = "{ ";
1977 Result += IDecl->getNameAsString();
1978 Result += " *"; Result += catchDecl->getNameAsString();
1979 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1980 Result += "_"; Result += catchDecl->getNameAsString();
1981
1982 Result += "; ";
1983 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1984 ReplaceText(lBraceLoc, 1, Result);
1985 AtRemoved = true;
1986 }
1987 }
1988 }
1989 if (!AtRemoved)
1990 // @catch -> catch
1991 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001992
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001993 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001994 if (finalStmt) {
1995 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001996 SourceLocation FinallyLoc = finalStmt->getLocStart();
1997
1998 if (noCatch) {
1999 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2000 buf += "catch (id e) {_rethrow = e;}\n";
2001 }
2002 else {
2003 buf += "}\n";
2004 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2005 buf += "catch (id e) {_rethrow = e;}\n";
2006 }
2007
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002008 SourceLocation startFinalLoc = finalStmt->getLocStart();
2009 ReplaceText(startFinalLoc, 8, buf);
2010 Stmt *body = finalStmt->getFinallyBody();
2011 SourceLocation startFinalBodyLoc = body->getLocStart();
2012 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002013 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002014 ReplaceText(startFinalBodyLoc, 1, buf);
2015
2016 SourceLocation endFinalBodyLoc = body->getLocEnd();
2017 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002018 // Now check for any return/continue/go statements within the @try.
2019 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002020 }
2021
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002022 return 0;
2023}
2024
2025// This can't be done with ReplaceStmt(S, ThrowExpr), since
2026// the throw expression is typically a message expression that's already
2027// been rewritten! (which implies the SourceLocation's are invalid).
2028Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2029 // Get the start location and compute the semi location.
2030 SourceLocation startLoc = S->getLocStart();
2031 const char *startBuf = SM->getCharacterData(startLoc);
2032
2033 assert((*startBuf == '@') && "bogus @throw location");
2034
2035 std::string buf;
2036 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2037 if (S->getThrowExpr())
2038 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002039 else
2040 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002041
2042 // handle "@ throw" correctly.
2043 const char *wBuf = strchr(startBuf, 'w');
2044 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2045 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2046
2047 const char *semiBuf = strchr(startBuf, ';');
2048 assert((*semiBuf == ';') && "@throw: can't find ';'");
2049 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002050 if (S->getThrowExpr())
2051 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002052 return 0;
2053}
2054
2055Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2056 // Create a new string expression.
2057 QualType StrType = Context->getPointerType(Context->CharTy);
2058 std::string StrEncoding;
2059 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2060 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2061 StringLiteral::Ascii, false,
2062 StrType, SourceLocation());
2063 ReplaceStmt(Exp, Replacement);
2064
2065 // Replace this subexpr in the parent.
2066 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2067 return Replacement;
2068}
2069
2070Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2071 if (!SelGetUidFunctionDecl)
2072 SynthSelGetUidFunctionDecl();
2073 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2074 // Create a call to sel_registerName("selName").
2075 SmallVector<Expr*, 8> SelExprs;
2076 QualType argType = Context->getPointerType(Context->CharTy);
2077 SelExprs.push_back(StringLiteral::Create(*Context,
2078 Exp->getSelector().getAsString(),
2079 StringLiteral::Ascii, false,
2080 argType, SourceLocation()));
2081 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2082 &SelExprs[0], SelExprs.size());
2083 ReplaceStmt(Exp, SelExp);
2084 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2085 return SelExp;
2086}
2087
2088CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2089 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2090 SourceLocation EndLoc) {
2091 // Get the type, we will need to reference it in a couple spots.
2092 QualType msgSendType = FD->getType();
2093
2094 // Create a reference to the objc_msgSend() declaration.
2095 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002096 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002097
2098 // Now, we cast the reference to a pointer to the objc_msgSend type.
2099 QualType pToFunc = Context->getPointerType(msgSendType);
2100 ImplicitCastExpr *ICE =
2101 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2102 DRE, 0, VK_RValue);
2103
2104 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2105
2106 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002107 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002108 FT->getCallResultType(*Context),
2109 VK_RValue, EndLoc);
2110 return Exp;
2111}
2112
2113static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2114 const char *&startRef, const char *&endRef) {
2115 while (startBuf < endBuf) {
2116 if (*startBuf == '<')
2117 startRef = startBuf; // mark the start.
2118 if (*startBuf == '>') {
2119 if (startRef && *startRef == '<') {
2120 endRef = startBuf; // mark the end.
2121 return true;
2122 }
2123 return false;
2124 }
2125 startBuf++;
2126 }
2127 return false;
2128}
2129
2130static void scanToNextArgument(const char *&argRef) {
2131 int angle = 0;
2132 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2133 if (*argRef == '<')
2134 angle++;
2135 else if (*argRef == '>')
2136 angle--;
2137 argRef++;
2138 }
2139 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2140}
2141
2142bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2143 if (T->isObjCQualifiedIdType())
2144 return true;
2145 if (const PointerType *PT = T->getAs<PointerType>()) {
2146 if (PT->getPointeeType()->isObjCQualifiedIdType())
2147 return true;
2148 }
2149 if (T->isObjCObjectPointerType()) {
2150 T = T->getPointeeType();
2151 return T->isObjCQualifiedInterfaceType();
2152 }
2153 if (T->isArrayType()) {
2154 QualType ElemTy = Context->getBaseElementType(T);
2155 return needToScanForQualifiers(ElemTy);
2156 }
2157 return false;
2158}
2159
2160void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2161 QualType Type = E->getType();
2162 if (needToScanForQualifiers(Type)) {
2163 SourceLocation Loc, EndLoc;
2164
2165 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2166 Loc = ECE->getLParenLoc();
2167 EndLoc = ECE->getRParenLoc();
2168 } else {
2169 Loc = E->getLocStart();
2170 EndLoc = E->getLocEnd();
2171 }
2172 // This will defend against trying to rewrite synthesized expressions.
2173 if (Loc.isInvalid() || EndLoc.isInvalid())
2174 return;
2175
2176 const char *startBuf = SM->getCharacterData(Loc);
2177 const char *endBuf = SM->getCharacterData(EndLoc);
2178 const char *startRef = 0, *endRef = 0;
2179 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2180 // Get the locations of the startRef, endRef.
2181 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2182 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2183 // Comment out the protocol references.
2184 InsertText(LessLoc, "/*");
2185 InsertText(GreaterLoc, "*/");
2186 }
2187 }
2188}
2189
2190void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2191 SourceLocation Loc;
2192 QualType Type;
2193 const FunctionProtoType *proto = 0;
2194 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2195 Loc = VD->getLocation();
2196 Type = VD->getType();
2197 }
2198 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2199 Loc = FD->getLocation();
2200 // Check for ObjC 'id' and class types that have been adorned with protocol
2201 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2202 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2203 assert(funcType && "missing function type");
2204 proto = dyn_cast<FunctionProtoType>(funcType);
2205 if (!proto)
2206 return;
2207 Type = proto->getResultType();
2208 }
2209 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2210 Loc = FD->getLocation();
2211 Type = FD->getType();
2212 }
2213 else
2214 return;
2215
2216 if (needToScanForQualifiers(Type)) {
2217 // Since types are unique, we need to scan the buffer.
2218
2219 const char *endBuf = SM->getCharacterData(Loc);
2220 const char *startBuf = endBuf;
2221 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2222 startBuf--; // scan backward (from the decl location) for return type.
2223 const char *startRef = 0, *endRef = 0;
2224 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2225 // Get the locations of the startRef, endRef.
2226 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2227 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2228 // Comment out the protocol references.
2229 InsertText(LessLoc, "/*");
2230 InsertText(GreaterLoc, "*/");
2231 }
2232 }
2233 if (!proto)
2234 return; // most likely, was a variable
2235 // Now check arguments.
2236 const char *startBuf = SM->getCharacterData(Loc);
2237 const char *startFuncBuf = startBuf;
2238 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2239 if (needToScanForQualifiers(proto->getArgType(i))) {
2240 // Since types are unique, we need to scan the buffer.
2241
2242 const char *endBuf = startBuf;
2243 // scan forward (from the decl location) for argument types.
2244 scanToNextArgument(endBuf);
2245 const char *startRef = 0, *endRef = 0;
2246 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2247 // Get the locations of the startRef, endRef.
2248 SourceLocation LessLoc =
2249 Loc.getLocWithOffset(startRef-startFuncBuf);
2250 SourceLocation GreaterLoc =
2251 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2252 // Comment out the protocol references.
2253 InsertText(LessLoc, "/*");
2254 InsertText(GreaterLoc, "*/");
2255 }
2256 startBuf = ++endBuf;
2257 }
2258 else {
2259 // If the function name is derived from a macro expansion, then the
2260 // argument buffer will not follow the name. Need to speak with Chris.
2261 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2262 startBuf++; // scan forward (from the decl location) for argument types.
2263 startBuf++;
2264 }
2265 }
2266}
2267
2268void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2269 QualType QT = ND->getType();
2270 const Type* TypePtr = QT->getAs<Type>();
2271 if (!isa<TypeOfExprType>(TypePtr))
2272 return;
2273 while (isa<TypeOfExprType>(TypePtr)) {
2274 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2275 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2276 TypePtr = QT->getAs<Type>();
2277 }
2278 // FIXME. This will not work for multiple declarators; as in:
2279 // __typeof__(a) b,c,d;
2280 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2281 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2282 const char *startBuf = SM->getCharacterData(DeclLoc);
2283 if (ND->getInit()) {
2284 std::string Name(ND->getNameAsString());
2285 TypeAsString += " " + Name + " = ";
2286 Expr *E = ND->getInit();
2287 SourceLocation startLoc;
2288 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2289 startLoc = ECE->getLParenLoc();
2290 else
2291 startLoc = E->getLocStart();
2292 startLoc = SM->getExpansionLoc(startLoc);
2293 const char *endBuf = SM->getCharacterData(startLoc);
2294 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2295 }
2296 else {
2297 SourceLocation X = ND->getLocEnd();
2298 X = SM->getExpansionLoc(X);
2299 const char *endBuf = SM->getCharacterData(X);
2300 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2301 }
2302}
2303
2304// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2305void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2306 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2307 SmallVector<QualType, 16> ArgTys;
2308 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2309 QualType getFuncType =
2310 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2311 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002312 SourceLocation(),
2313 SourceLocation(),
2314 SelGetUidIdent, getFuncType, 0,
2315 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002316}
2317
2318void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2319 // declared in <objc/objc.h>
2320 if (FD->getIdentifier() &&
2321 FD->getName() == "sel_registerName") {
2322 SelGetUidFunctionDecl = FD;
2323 return;
2324 }
2325 RewriteObjCQualifiedInterfaceTypes(FD);
2326}
2327
2328void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2329 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2330 const char *argPtr = TypeString.c_str();
2331 if (!strchr(argPtr, '^')) {
2332 Str += TypeString;
2333 return;
2334 }
2335 while (*argPtr) {
2336 Str += (*argPtr == '^' ? '*' : *argPtr);
2337 argPtr++;
2338 }
2339}
2340
2341// FIXME. Consolidate this routine with RewriteBlockPointerType.
2342void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2343 ValueDecl *VD) {
2344 QualType Type = VD->getType();
2345 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2346 const char *argPtr = TypeString.c_str();
2347 int paren = 0;
2348 while (*argPtr) {
2349 switch (*argPtr) {
2350 case '(':
2351 Str += *argPtr;
2352 paren++;
2353 break;
2354 case ')':
2355 Str += *argPtr;
2356 paren--;
2357 break;
2358 case '^':
2359 Str += '*';
2360 if (paren == 1)
2361 Str += VD->getNameAsString();
2362 break;
2363 default:
2364 Str += *argPtr;
2365 break;
2366 }
2367 argPtr++;
2368 }
2369}
2370
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002371void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2372 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2373 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2374 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2375 if (!proto)
2376 return;
2377 QualType Type = proto->getResultType();
2378 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2379 FdStr += " ";
2380 FdStr += FD->getName();
2381 FdStr += "(";
2382 unsigned numArgs = proto->getNumArgs();
2383 for (unsigned i = 0; i < numArgs; i++) {
2384 QualType ArgType = proto->getArgType(i);
2385 RewriteBlockPointerType(FdStr, ArgType);
2386 if (i+1 < numArgs)
2387 FdStr += ", ";
2388 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002389 if (FD->isVariadic()) {
2390 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2391 }
2392 else
2393 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002394 InsertText(FunLocStart, FdStr);
2395}
2396
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002397// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002398void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2399 if (SuperContructorFunctionDecl)
2400 return;
2401 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2402 SmallVector<QualType, 16> ArgTys;
2403 QualType argT = Context->getObjCIdType();
2404 assert(!argT.isNull() && "Can't find 'id' type");
2405 ArgTys.push_back(argT);
2406 ArgTys.push_back(argT);
2407 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2408 &ArgTys[0], ArgTys.size());
2409 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002410 SourceLocation(),
2411 SourceLocation(),
2412 msgSendIdent, msgSendType,
2413 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002414}
2415
2416// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2417void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2418 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2419 SmallVector<QualType, 16> ArgTys;
2420 QualType argT = Context->getObjCIdType();
2421 assert(!argT.isNull() && "Can't find 'id' type");
2422 ArgTys.push_back(argT);
2423 argT = Context->getObjCSelType();
2424 assert(!argT.isNull() && "Can't find 'SEL' type");
2425 ArgTys.push_back(argT);
2426 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2427 &ArgTys[0], ArgTys.size(),
2428 true /*isVariadic*/);
2429 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002430 SourceLocation(),
2431 SourceLocation(),
2432 msgSendIdent, msgSendType, 0,
2433 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002434}
2435
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002436// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002437void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2438 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002439 SmallVector<QualType, 2> ArgTys;
2440 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002441 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002442 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002443 true /*isVariadic*/);
2444 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002445 SourceLocation(),
2446 SourceLocation(),
2447 msgSendIdent, msgSendType, 0,
2448 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002449}
2450
2451// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2452void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2453 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2454 SmallVector<QualType, 16> ArgTys;
2455 QualType argT = Context->getObjCIdType();
2456 assert(!argT.isNull() && "Can't find 'id' type");
2457 ArgTys.push_back(argT);
2458 argT = Context->getObjCSelType();
2459 assert(!argT.isNull() && "Can't find 'SEL' type");
2460 ArgTys.push_back(argT);
2461 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2462 &ArgTys[0], ArgTys.size(),
2463 true /*isVariadic*/);
2464 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002465 SourceLocation(),
2466 SourceLocation(),
2467 msgSendIdent, msgSendType, 0,
2468 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002469}
2470
2471// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002472// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002473void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2474 IdentifierInfo *msgSendIdent =
2475 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002476 SmallVector<QualType, 2> ArgTys;
2477 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002478 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002479 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002480 true /*isVariadic*/);
2481 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2482 SourceLocation(),
2483 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002484 msgSendIdent,
2485 msgSendType, 0,
2486 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002487}
2488
2489// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2490void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2491 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2492 SmallVector<QualType, 16> ArgTys;
2493 QualType argT = Context->getObjCIdType();
2494 assert(!argT.isNull() && "Can't find 'id' type");
2495 ArgTys.push_back(argT);
2496 argT = Context->getObjCSelType();
2497 assert(!argT.isNull() && "Can't find 'SEL' type");
2498 ArgTys.push_back(argT);
2499 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2500 &ArgTys[0], ArgTys.size(),
2501 true /*isVariadic*/);
2502 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002503 SourceLocation(),
2504 SourceLocation(),
2505 msgSendIdent, msgSendType, 0,
2506 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002507}
2508
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002509// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002510void RewriteModernObjC::SynthGetClassFunctionDecl() {
2511 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2512 SmallVector<QualType, 16> ArgTys;
2513 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002514 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002515 &ArgTys[0], ArgTys.size());
2516 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002517 SourceLocation(),
2518 SourceLocation(),
2519 getClassIdent, getClassType, 0,
2520 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002521}
2522
2523// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2524void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2525 IdentifierInfo *getSuperClassIdent =
2526 &Context->Idents.get("class_getSuperclass");
2527 SmallVector<QualType, 16> ArgTys;
2528 ArgTys.push_back(Context->getObjCClassType());
2529 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2530 &ArgTys[0], ArgTys.size());
2531 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2532 SourceLocation(),
2533 SourceLocation(),
2534 getSuperClassIdent,
2535 getClassType, 0,
Chad Rosiere3b29882013-01-04 22:40:33 +00002536 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002537}
2538
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002539// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002540void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2541 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2542 SmallVector<QualType, 16> ArgTys;
2543 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002544 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002545 &ArgTys[0], ArgTys.size());
2546 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002547 SourceLocation(),
2548 SourceLocation(),
2549 getClassIdent, getClassType,
2550 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002551}
2552
2553Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2554 QualType strType = getConstantStringStructType();
2555
2556 std::string S = "__NSConstantStringImpl_";
2557
2558 std::string tmpName = InFileName;
2559 unsigned i;
2560 for (i=0; i < tmpName.length(); i++) {
2561 char c = tmpName.at(i);
2562 // replace any non alphanumeric characters with '_'.
2563 if (!isalpha(c) && (c < '0' || c > '9'))
2564 tmpName[i] = '_';
2565 }
2566 S += tmpName;
2567 S += "_";
2568 S += utostr(NumObjCStringLiterals++);
2569
2570 Preamble += "static __NSConstantStringImpl " + S;
2571 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2572 Preamble += "0x000007c8,"; // utf8_str
2573 // The pretty printer for StringLiteral handles escape characters properly.
2574 std::string prettyBufS;
2575 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002576 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002577 Preamble += prettyBuf.str();
2578 Preamble += ",";
2579 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2580
2581 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2582 SourceLocation(), &Context->Idents.get(S),
2583 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002584 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002585 SourceLocation());
2586 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2587 Context->getPointerType(DRE->getType()),
2588 VK_RValue, OK_Ordinary,
2589 SourceLocation());
2590 // cast to NSConstantString *
2591 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2592 CK_CPointerToObjCPointerCast, Unop);
2593 ReplaceStmt(Exp, cast);
2594 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2595 return cast;
2596}
2597
Fariborz Jahanian55947042012-03-27 20:17:30 +00002598Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2599 unsigned IntSize =
2600 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2601
2602 Expr *FlagExp = IntegerLiteral::Create(*Context,
2603 llvm::APInt(IntSize, Exp->getValue()),
2604 Context->IntTy, Exp->getLocation());
2605 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2606 CK_BitCast, FlagExp);
2607 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2608 cast);
2609 ReplaceStmt(Exp, PE);
2610 return PE;
2611}
2612
Patrick Beardeb382ec2012-04-19 00:25:12 +00002613Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002614 // synthesize declaration of helper functions needed in this routine.
2615 if (!SelGetUidFunctionDecl)
2616 SynthSelGetUidFunctionDecl();
2617 // use objc_msgSend() for all.
2618 if (!MsgSendFunctionDecl)
2619 SynthMsgSendFunctionDecl();
2620 if (!GetClassFunctionDecl)
2621 SynthGetClassFunctionDecl();
2622
2623 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2624 SourceLocation StartLoc = Exp->getLocStart();
2625 SourceLocation EndLoc = Exp->getLocEnd();
2626
2627 // Synthesize a call to objc_msgSend().
2628 SmallVector<Expr*, 4> MsgExprs;
2629 SmallVector<Expr*, 4> ClsExprs;
2630 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002631
Patrick Beardeb382ec2012-04-19 00:25:12 +00002632 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2633 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2634 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002635
Patrick Beardeb382ec2012-04-19 00:25:12 +00002636 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002637 ClsExprs.push_back(StringLiteral::Create(*Context,
2638 clsName->getName(),
2639 StringLiteral::Ascii, false,
2640 argType, SourceLocation()));
2641 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2642 &ClsExprs[0],
2643 ClsExprs.size(),
2644 StartLoc, EndLoc);
2645 MsgExprs.push_back(Cls);
2646
Patrick Beardeb382ec2012-04-19 00:25:12 +00002647 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002648 // it will be the 2nd argument.
2649 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002650 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002651 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002652 StringLiteral::Ascii, false,
2653 argType, SourceLocation()));
2654 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2655 &SelExprs[0], SelExprs.size(),
2656 StartLoc, EndLoc);
2657 MsgExprs.push_back(SelExp);
2658
Patrick Beardeb382ec2012-04-19 00:25:12 +00002659 // User provided sub-expression is the 3rd, and last, argument.
2660 Expr *subExpr = Exp->getSubExpr();
2661 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002662 QualType type = ICE->getType();
2663 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2664 CastKind CK = CK_BitCast;
2665 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2666 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002667 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002668 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002669 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002670
2671 SmallVector<QualType, 4> ArgTypes;
2672 ArgTypes.push_back(Context->getObjCIdType());
2673 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002674 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2675 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002676 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002677
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002678 QualType returnType = Exp->getType();
2679 // Get the type, we will need to reference it in a couple spots.
2680 QualType msgSendType = MsgSendFlavor->getType();
2681
2682 // Create a reference to the objc_msgSend() declaration.
2683 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2684 VK_LValue, SourceLocation());
2685
2686 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002687 Context->getPointerType(Context->VoidTy),
2688 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002689
2690 // Now do the "normal" pointer to function cast.
2691 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002692 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2693 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002694 castType = Context->getPointerType(castType);
2695 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2696 cast);
2697
2698 // Don't forget the parens to enforce the proper binding.
2699 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2700
2701 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002702 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002703 FT->getResultType(), VK_RValue,
2704 EndLoc);
2705 ReplaceStmt(Exp, CE);
2706 return CE;
2707}
2708
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002709Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2710 // synthesize declaration of helper functions needed in this routine.
2711 if (!SelGetUidFunctionDecl)
2712 SynthSelGetUidFunctionDecl();
2713 // use objc_msgSend() for all.
2714 if (!MsgSendFunctionDecl)
2715 SynthMsgSendFunctionDecl();
2716 if (!GetClassFunctionDecl)
2717 SynthGetClassFunctionDecl();
2718
2719 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2720 SourceLocation StartLoc = Exp->getLocStart();
2721 SourceLocation EndLoc = Exp->getLocEnd();
2722
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002723 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002724 QualType IntQT = Context->IntTy;
2725 QualType NSArrayFType =
2726 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002727 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002728 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2729 DeclRefExpr *NSArrayDRE =
2730 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2731 SourceLocation());
2732
2733 SmallVector<Expr*, 16> InitExprs;
2734 unsigned NumElements = Exp->getNumElements();
2735 unsigned UnsignedIntSize =
2736 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2737 Expr *count = IntegerLiteral::Create(*Context,
2738 llvm::APInt(UnsignedIntSize, NumElements),
2739 Context->UnsignedIntTy, SourceLocation());
2740 InitExprs.push_back(count);
2741 for (unsigned i = 0; i < NumElements; i++)
2742 InitExprs.push_back(Exp->getElement(i));
2743 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002744 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002745 NSArrayFType, VK_LValue, SourceLocation());
2746
2747 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2748 SourceLocation(),
2749 &Context->Idents.get("arr"),
2750 Context->getPointerType(Context->VoidPtrTy), 0,
2751 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002752 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002753 MemberExpr *ArrayLiteralME =
2754 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2755 SourceLocation(),
2756 ARRFD->getType(), VK_LValue,
2757 OK_Ordinary);
2758 QualType ConstIdT = Context->getObjCIdType().withConst();
2759 CStyleCastExpr * ArrayLiteralObjects =
2760 NoTypeInfoCStyleCastExpr(Context,
2761 Context->getPointerType(ConstIdT),
2762 CK_BitCast,
2763 ArrayLiteralME);
2764
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002765 // Synthesize a call to objc_msgSend().
2766 SmallVector<Expr*, 32> MsgExprs;
2767 SmallVector<Expr*, 4> ClsExprs;
2768 QualType argType = Context->getPointerType(Context->CharTy);
2769 QualType expType = Exp->getType();
2770
2771 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2772 ObjCInterfaceDecl *Class =
2773 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2774
2775 IdentifierInfo *clsName = Class->getIdentifier();
2776 ClsExprs.push_back(StringLiteral::Create(*Context,
2777 clsName->getName(),
2778 StringLiteral::Ascii, false,
2779 argType, SourceLocation()));
2780 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2781 &ClsExprs[0],
2782 ClsExprs.size(),
2783 StartLoc, EndLoc);
2784 MsgExprs.push_back(Cls);
2785
2786 // Create a call to sel_registerName("arrayWithObjects:count:").
2787 // it will be the 2nd argument.
2788 SmallVector<Expr*, 4> SelExprs;
2789 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2790 SelExprs.push_back(StringLiteral::Create(*Context,
2791 ArrayMethod->getSelector().getAsString(),
2792 StringLiteral::Ascii, false,
2793 argType, SourceLocation()));
2794 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2795 &SelExprs[0], SelExprs.size(),
2796 StartLoc, EndLoc);
2797 MsgExprs.push_back(SelExp);
2798
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002799 // (const id [])objects
2800 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002801
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002802 // (NSUInteger)cnt
2803 Expr *cnt = IntegerLiteral::Create(*Context,
2804 llvm::APInt(UnsignedIntSize, NumElements),
2805 Context->UnsignedIntTy, SourceLocation());
2806 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002807
2808
2809 SmallVector<QualType, 4> ArgTypes;
2810 ArgTypes.push_back(Context->getObjCIdType());
2811 ArgTypes.push_back(Context->getObjCSelType());
2812 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2813 E = ArrayMethod->param_end(); PI != E; ++PI)
2814 ArgTypes.push_back((*PI)->getType());
2815
2816 QualType returnType = Exp->getType();
2817 // Get the type, we will need to reference it in a couple spots.
2818 QualType msgSendType = MsgSendFlavor->getType();
2819
2820 // Create a reference to the objc_msgSend() declaration.
2821 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2822 VK_LValue, SourceLocation());
2823
2824 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2825 Context->getPointerType(Context->VoidTy),
2826 CK_BitCast, DRE);
2827
2828 // Now do the "normal" pointer to function cast.
2829 QualType castType =
2830 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2831 ArrayMethod->isVariadic());
2832 castType = Context->getPointerType(castType);
2833 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2834 cast);
2835
2836 // Don't forget the parens to enforce the proper binding.
2837 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2838
2839 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002840 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002841 FT->getResultType(), VK_RValue,
2842 EndLoc);
2843 ReplaceStmt(Exp, CE);
2844 return CE;
2845}
2846
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002847Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2848 // synthesize declaration of helper functions needed in this routine.
2849 if (!SelGetUidFunctionDecl)
2850 SynthSelGetUidFunctionDecl();
2851 // use objc_msgSend() for all.
2852 if (!MsgSendFunctionDecl)
2853 SynthMsgSendFunctionDecl();
2854 if (!GetClassFunctionDecl)
2855 SynthGetClassFunctionDecl();
2856
2857 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2858 SourceLocation StartLoc = Exp->getLocStart();
2859 SourceLocation EndLoc = Exp->getLocEnd();
2860
2861 // Build the expression: __NSContainer_literal(int, ...).arr
2862 QualType IntQT = Context->IntTy;
2863 QualType NSDictFType =
2864 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2865 std::string NSDictFName("__NSContainer_literal");
2866 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2867 DeclRefExpr *NSDictDRE =
2868 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2869 SourceLocation());
2870
2871 SmallVector<Expr*, 16> KeyExprs;
2872 SmallVector<Expr*, 16> ValueExprs;
2873
2874 unsigned NumElements = Exp->getNumElements();
2875 unsigned UnsignedIntSize =
2876 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2877 Expr *count = IntegerLiteral::Create(*Context,
2878 llvm::APInt(UnsignedIntSize, NumElements),
2879 Context->UnsignedIntTy, SourceLocation());
2880 KeyExprs.push_back(count);
2881 ValueExprs.push_back(count);
2882 for (unsigned i = 0; i < NumElements; i++) {
2883 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2884 KeyExprs.push_back(Element.Key);
2885 ValueExprs.push_back(Element.Value);
2886 }
2887
2888 // (const id [])objects
2889 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002890 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002891 NSDictFType, VK_LValue, SourceLocation());
2892
2893 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2894 SourceLocation(),
2895 &Context->Idents.get("arr"),
2896 Context->getPointerType(Context->VoidPtrTy), 0,
2897 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002898 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002899 MemberExpr *DictLiteralValueME =
2900 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2901 SourceLocation(),
2902 ARRFD->getType(), VK_LValue,
2903 OK_Ordinary);
2904 QualType ConstIdT = Context->getObjCIdType().withConst();
2905 CStyleCastExpr * DictValueObjects =
2906 NoTypeInfoCStyleCastExpr(Context,
2907 Context->getPointerType(ConstIdT),
2908 CK_BitCast,
2909 DictLiteralValueME);
2910 // (const id <NSCopying> [])keys
2911 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002912 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002913 NSDictFType, VK_LValue, SourceLocation());
2914
2915 MemberExpr *DictLiteralKeyME =
2916 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2917 SourceLocation(),
2918 ARRFD->getType(), VK_LValue,
2919 OK_Ordinary);
2920
2921 CStyleCastExpr * DictKeyObjects =
2922 NoTypeInfoCStyleCastExpr(Context,
2923 Context->getPointerType(ConstIdT),
2924 CK_BitCast,
2925 DictLiteralKeyME);
2926
2927
2928
2929 // Synthesize a call to objc_msgSend().
2930 SmallVector<Expr*, 32> MsgExprs;
2931 SmallVector<Expr*, 4> ClsExprs;
2932 QualType argType = Context->getPointerType(Context->CharTy);
2933 QualType expType = Exp->getType();
2934
2935 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2936 ObjCInterfaceDecl *Class =
2937 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2938
2939 IdentifierInfo *clsName = Class->getIdentifier();
2940 ClsExprs.push_back(StringLiteral::Create(*Context,
2941 clsName->getName(),
2942 StringLiteral::Ascii, false,
2943 argType, SourceLocation()));
2944 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2945 &ClsExprs[0],
2946 ClsExprs.size(),
2947 StartLoc, EndLoc);
2948 MsgExprs.push_back(Cls);
2949
2950 // Create a call to sel_registerName("arrayWithObjects:count:").
2951 // it will be the 2nd argument.
2952 SmallVector<Expr*, 4> SelExprs;
2953 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2954 SelExprs.push_back(StringLiteral::Create(*Context,
2955 DictMethod->getSelector().getAsString(),
2956 StringLiteral::Ascii, false,
2957 argType, SourceLocation()));
2958 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2959 &SelExprs[0], SelExprs.size(),
2960 StartLoc, EndLoc);
2961 MsgExprs.push_back(SelExp);
2962
2963 // (const id [])objects
2964 MsgExprs.push_back(DictValueObjects);
2965
2966 // (const id <NSCopying> [])keys
2967 MsgExprs.push_back(DictKeyObjects);
2968
2969 // (NSUInteger)cnt
2970 Expr *cnt = IntegerLiteral::Create(*Context,
2971 llvm::APInt(UnsignedIntSize, NumElements),
2972 Context->UnsignedIntTy, SourceLocation());
2973 MsgExprs.push_back(cnt);
2974
2975
2976 SmallVector<QualType, 8> ArgTypes;
2977 ArgTypes.push_back(Context->getObjCIdType());
2978 ArgTypes.push_back(Context->getObjCSelType());
2979 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2980 E = DictMethod->param_end(); PI != E; ++PI) {
2981 QualType T = (*PI)->getType();
2982 if (const PointerType* PT = T->getAs<PointerType>()) {
2983 QualType PointeeTy = PT->getPointeeType();
2984 convertToUnqualifiedObjCType(PointeeTy);
2985 T = Context->getPointerType(PointeeTy);
2986 }
2987 ArgTypes.push_back(T);
2988 }
2989
2990 QualType returnType = Exp->getType();
2991 // Get the type, we will need to reference it in a couple spots.
2992 QualType msgSendType = MsgSendFlavor->getType();
2993
2994 // Create a reference to the objc_msgSend() declaration.
2995 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2996 VK_LValue, SourceLocation());
2997
2998 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2999 Context->getPointerType(Context->VoidTy),
3000 CK_BitCast, DRE);
3001
3002 // Now do the "normal" pointer to function cast.
3003 QualType castType =
3004 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3005 DictMethod->isVariadic());
3006 castType = Context->getPointerType(castType);
3007 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3008 cast);
3009
3010 // Don't forget the parens to enforce the proper binding.
3011 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3012
3013 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003014 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003015 FT->getResultType(), VK_RValue,
3016 EndLoc);
3017 ReplaceStmt(Exp, CE);
3018 return CE;
3019}
3020
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003021// struct __rw_objc_super {
3022// struct objc_object *object; struct objc_object *superClass;
3023// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003024QualType RewriteModernObjC::getSuperStructType() {
3025 if (!SuperStructDecl) {
3026 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3027 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003028 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003029 QualType FieldTypes[2];
3030
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003031 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003032 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003033 // struct objc_object *superClass;
3034 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003035
3036 // Create fields
3037 for (unsigned i = 0; i < 2; ++i) {
3038 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3039 SourceLocation(),
3040 SourceLocation(), 0,
3041 FieldTypes[i], 0,
3042 /*BitWidth=*/0,
3043 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003044 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003045 }
3046
3047 SuperStructDecl->completeDefinition();
3048 }
3049 return Context->getTagDeclType(SuperStructDecl);
3050}
3051
3052QualType RewriteModernObjC::getConstantStringStructType() {
3053 if (!ConstantStringDecl) {
3054 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3055 SourceLocation(), SourceLocation(),
3056 &Context->Idents.get("__NSConstantStringImpl"));
3057 QualType FieldTypes[4];
3058
3059 // struct objc_object *receiver;
3060 FieldTypes[0] = Context->getObjCIdType();
3061 // int flags;
3062 FieldTypes[1] = Context->IntTy;
3063 // char *str;
3064 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3065 // long length;
3066 FieldTypes[3] = Context->LongTy;
3067
3068 // Create fields
3069 for (unsigned i = 0; i < 4; ++i) {
3070 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3071 ConstantStringDecl,
3072 SourceLocation(),
3073 SourceLocation(), 0,
3074 FieldTypes[i], 0,
3075 /*BitWidth=*/0,
3076 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003077 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003078 }
3079
3080 ConstantStringDecl->completeDefinition();
3081 }
3082 return Context->getTagDeclType(ConstantStringDecl);
3083}
3084
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003085/// getFunctionSourceLocation - returns start location of a function
3086/// definition. Complication arises when function has declared as
3087/// extern "C" or extern "C" {...}
3088static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3089 FunctionDecl *FD) {
3090 if (FD->isExternC() && !FD->isMain()) {
3091 const DeclContext *DC = FD->getDeclContext();
3092 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3093 // if it is extern "C" {...}, return function decl's own location.
3094 if (!LSD->getRBraceLoc().isValid())
3095 return LSD->getExternLoc();
3096 }
3097 if (FD->getStorageClassAsWritten() != SC_None)
3098 R.RewriteBlockLiteralFunctionDecl(FD);
3099 return FD->getTypeSpecStartLoc();
3100}
3101
Fariborz Jahanian96205962012-11-06 17:30:23 +00003102void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3103
3104 SourceLocation Location = D->getLocation();
3105
3106 if (Location.isFileID()) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003107 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003108 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3109 LineString += utostr(PLoc.getLine());
3110 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003111 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003112 if (isa<ObjCMethodDecl>(D))
3113 LineString += "\"";
3114 else LineString += "\"\n";
3115
3116 Location = D->getLocStart();
3117 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3118 if (FD->isExternC() && !FD->isMain()) {
3119 const DeclContext *DC = FD->getDeclContext();
3120 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3121 // if it is extern "C" {...}, return function decl's own location.
3122 if (!LSD->getRBraceLoc().isValid())
3123 Location = LSD->getExternLoc();
3124 }
3125 }
3126 InsertText(Location, LineString);
3127 }
3128}
3129
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003130/// SynthMsgSendStretCallExpr - This routine translates message expression
3131/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3132/// nil check on receiver must be performed before calling objc_msgSend_stret.
3133/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3134/// msgSendType - function type of objc_msgSend_stret(...)
3135/// returnType - Result type of the method being synthesized.
3136/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3137/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3138/// starting with receiver.
3139/// Method - Method being rewritten.
3140Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3141 QualType msgSendType,
3142 QualType returnType,
3143 SmallVectorImpl<QualType> &ArgTypes,
3144 SmallVectorImpl<Expr*> &MsgExprs,
3145 ObjCMethodDecl *Method) {
3146 // Now do the "normal" pointer to function cast.
3147 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3148 Method ? Method->isVariadic() : false);
3149 castType = Context->getPointerType(castType);
3150
3151 // build type for containing the objc_msgSend_stret object.
3152 static unsigned stretCount=0;
3153 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003154 std::string str =
3155 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3156 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003157 str += " {\n\t";
3158 str += name;
3159 str += "(id receiver, SEL sel";
3160 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003161 std::string ArgName = "arg"; ArgName += utostr(i);
3162 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3163 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003164 }
3165 // could be vararg.
3166 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003167 std::string ArgName = "arg"; ArgName += utostr(i);
3168 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3169 Context->getPrintingPolicy());
3170 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003171 }
3172
3173 str += ") {\n";
3174 str += "\t if (receiver == 0)\n";
3175 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3176 str += "\t else\n";
3177 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3178 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3179 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3180 str += ", arg"; str += utostr(i);
3181 }
3182 // could be vararg.
3183 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3184 str += ", arg"; str += utostr(i);
3185 }
3186
3187 str += ");\n";
3188 str += "\t}\n";
3189 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3190 str += " s;\n";
3191 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003192 SourceLocation FunLocStart;
3193 if (CurFunctionDef)
3194 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3195 else {
3196 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3197 FunLocStart = CurMethodDef->getLocStart();
3198 }
3199
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003200 InsertText(FunLocStart, str);
3201 ++stretCount;
3202
3203 // AST for __Stretn(receiver, args).s;
3204 IdentifierInfo *ID = &Context->Idents.get(name);
3205 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003206 SourceLocation(), ID, castType, 0,
3207 SC_Extern, SC_None, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003208 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3209 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003210 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003211 castType, VK_LValue, SourceLocation());
3212
3213 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3214 SourceLocation(),
3215 &Context->Idents.get("s"),
3216 returnType, 0,
3217 /*BitWidth=*/0, /*Mutable=*/true,
3218 ICIS_NoInit);
3219 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3220 FieldD->getType(), VK_LValue,
3221 OK_Ordinary);
3222
3223 return ME;
3224}
3225
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003226Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3227 SourceLocation StartLoc,
3228 SourceLocation EndLoc) {
3229 if (!SelGetUidFunctionDecl)
3230 SynthSelGetUidFunctionDecl();
3231 if (!MsgSendFunctionDecl)
3232 SynthMsgSendFunctionDecl();
3233 if (!MsgSendSuperFunctionDecl)
3234 SynthMsgSendSuperFunctionDecl();
3235 if (!MsgSendStretFunctionDecl)
3236 SynthMsgSendStretFunctionDecl();
3237 if (!MsgSendSuperStretFunctionDecl)
3238 SynthMsgSendSuperStretFunctionDecl();
3239 if (!MsgSendFpretFunctionDecl)
3240 SynthMsgSendFpretFunctionDecl();
3241 if (!GetClassFunctionDecl)
3242 SynthGetClassFunctionDecl();
3243 if (!GetSuperClassFunctionDecl)
3244 SynthGetSuperClassFunctionDecl();
3245 if (!GetMetaClassFunctionDecl)
3246 SynthGetMetaClassFunctionDecl();
3247
3248 // default to objc_msgSend().
3249 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3250 // May need to use objc_msgSend_stret() as well.
3251 FunctionDecl *MsgSendStretFlavor = 0;
3252 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3253 QualType resultType = mDecl->getResultType();
3254 if (resultType->isRecordType())
3255 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3256 else if (resultType->isRealFloatingType())
3257 MsgSendFlavor = MsgSendFpretFunctionDecl;
3258 }
3259
3260 // Synthesize a call to objc_msgSend().
3261 SmallVector<Expr*, 8> MsgExprs;
3262 switch (Exp->getReceiverKind()) {
3263 case ObjCMessageExpr::SuperClass: {
3264 MsgSendFlavor = MsgSendSuperFunctionDecl;
3265 if (MsgSendStretFlavor)
3266 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3267 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3268
3269 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3270
3271 SmallVector<Expr*, 4> InitExprs;
3272
3273 // set the receiver to self, the first argument to all methods.
3274 InitExprs.push_back(
3275 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3276 CK_BitCast,
3277 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003278 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003279 Context->getObjCIdType(),
3280 VK_RValue,
3281 SourceLocation()))
3282 ); // set the 'receiver'.
3283
3284 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3285 SmallVector<Expr*, 8> ClsExprs;
3286 QualType argType = Context->getPointerType(Context->CharTy);
3287 ClsExprs.push_back(StringLiteral::Create(*Context,
3288 ClassDecl->getIdentifier()->getName(),
3289 StringLiteral::Ascii, false,
3290 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003291 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003292 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3293 &ClsExprs[0],
3294 ClsExprs.size(),
3295 StartLoc,
3296 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003297 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003298 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003299 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3300 &ClsExprs[0], ClsExprs.size(),
3301 StartLoc, EndLoc);
3302
3303 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3304 // To turn off a warning, type-cast to 'id'
3305 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3306 NoTypeInfoCStyleCastExpr(Context,
3307 Context->getObjCIdType(),
3308 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003309 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003310 QualType superType = getSuperStructType();
3311 Expr *SuperRep;
3312
3313 if (LangOpts.MicrosoftExt) {
3314 SynthSuperContructorFunctionDecl();
3315 // Simulate a contructor call...
3316 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003317 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003318 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003319 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003320 superType, VK_LValue,
3321 SourceLocation());
3322 // The code for super is a little tricky to prevent collision with
3323 // the structure definition in the header. The rewriter has it's own
3324 // internal definition (__rw_objc_super) that is uses. This is why
3325 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003326 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003327 //
3328 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3329 Context->getPointerType(SuperRep->getType()),
3330 VK_RValue, OK_Ordinary,
3331 SourceLocation());
3332 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3333 Context->getPointerType(superType),
3334 CK_BitCast, SuperRep);
3335 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003336 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003337 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003338 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003339 SourceLocation());
3340 TypeSourceInfo *superTInfo
3341 = Context->getTrivialTypeSourceInfo(superType);
3342 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3343 superType, VK_LValue,
3344 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003345 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003346 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3347 Context->getPointerType(SuperRep->getType()),
3348 VK_RValue, OK_Ordinary,
3349 SourceLocation());
3350 }
3351 MsgExprs.push_back(SuperRep);
3352 break;
3353 }
3354
3355 case ObjCMessageExpr::Class: {
3356 SmallVector<Expr*, 8> ClsExprs;
3357 QualType argType = Context->getPointerType(Context->CharTy);
3358 ObjCInterfaceDecl *Class
3359 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3360 IdentifierInfo *clsName = Class->getIdentifier();
3361 ClsExprs.push_back(StringLiteral::Create(*Context,
3362 clsName->getName(),
3363 StringLiteral::Ascii, false,
3364 argType, SourceLocation()));
3365 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3366 &ClsExprs[0],
3367 ClsExprs.size(),
3368 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003369 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3370 Context->getObjCIdType(),
3371 CK_BitCast, Cls);
3372 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003373 break;
3374 }
3375
3376 case ObjCMessageExpr::SuperInstance:{
3377 MsgSendFlavor = MsgSendSuperFunctionDecl;
3378 if (MsgSendStretFlavor)
3379 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3380 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3381 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3382 SmallVector<Expr*, 4> InitExprs;
3383
3384 InitExprs.push_back(
3385 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3386 CK_BitCast,
3387 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003388 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003389 Context->getObjCIdType(),
3390 VK_RValue, SourceLocation()))
3391 ); // set the 'receiver'.
3392
3393 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3394 SmallVector<Expr*, 8> ClsExprs;
3395 QualType argType = Context->getPointerType(Context->CharTy);
3396 ClsExprs.push_back(StringLiteral::Create(*Context,
3397 ClassDecl->getIdentifier()->getName(),
3398 StringLiteral::Ascii, false, argType,
3399 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003400 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003401 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3402 &ClsExprs[0],
3403 ClsExprs.size(),
3404 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003405 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003406 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003407 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3408 &ClsExprs[0], ClsExprs.size(),
3409 StartLoc, EndLoc);
3410
3411 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3412 // To turn off a warning, type-cast to 'id'
3413 InitExprs.push_back(
3414 // set 'super class', using class_getSuperclass().
3415 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3416 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003417 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003418 QualType superType = getSuperStructType();
3419 Expr *SuperRep;
3420
3421 if (LangOpts.MicrosoftExt) {
3422 SynthSuperContructorFunctionDecl();
3423 // Simulate a contructor call...
3424 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003425 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003426 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003427 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003428 superType, VK_LValue, SourceLocation());
3429 // The code for super is a little tricky to prevent collision with
3430 // the structure definition in the header. The rewriter has it's own
3431 // internal definition (__rw_objc_super) that is uses. This is why
3432 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003433 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003434 //
3435 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3436 Context->getPointerType(SuperRep->getType()),
3437 VK_RValue, OK_Ordinary,
3438 SourceLocation());
3439 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3440 Context->getPointerType(superType),
3441 CK_BitCast, SuperRep);
3442 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003443 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003444 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003445 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003446 SourceLocation());
3447 TypeSourceInfo *superTInfo
3448 = Context->getTrivialTypeSourceInfo(superType);
3449 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3450 superType, VK_RValue, ILE,
3451 false);
3452 }
3453 MsgExprs.push_back(SuperRep);
3454 break;
3455 }
3456
3457 case ObjCMessageExpr::Instance: {
3458 // Remove all type-casts because it may contain objc-style types; e.g.
3459 // Foo<Proto> *.
3460 Expr *recExpr = Exp->getInstanceReceiver();
3461 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3462 recExpr = CE->getSubExpr();
3463 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3464 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3465 ? CK_BlockPointerToObjCPointerCast
3466 : CK_CPointerToObjCPointerCast;
3467
3468 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3469 CK, recExpr);
3470 MsgExprs.push_back(recExpr);
3471 break;
3472 }
3473 }
3474
3475 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3476 SmallVector<Expr*, 8> SelExprs;
3477 QualType argType = Context->getPointerType(Context->CharTy);
3478 SelExprs.push_back(StringLiteral::Create(*Context,
3479 Exp->getSelector().getAsString(),
3480 StringLiteral::Ascii, false,
3481 argType, SourceLocation()));
3482 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3483 &SelExprs[0], SelExprs.size(),
3484 StartLoc,
3485 EndLoc);
3486 MsgExprs.push_back(SelExp);
3487
3488 // Now push any user supplied arguments.
3489 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3490 Expr *userExpr = Exp->getArg(i);
3491 // Make all implicit casts explicit...ICE comes in handy:-)
3492 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3493 // Reuse the ICE type, it is exactly what the doctor ordered.
3494 QualType type = ICE->getType();
3495 if (needToScanForQualifiers(type))
3496 type = Context->getObjCIdType();
3497 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3498 (void)convertBlockPointerToFunctionPointer(type);
3499 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3500 CastKind CK;
3501 if (SubExpr->getType()->isIntegralType(*Context) &&
3502 type->isBooleanType()) {
3503 CK = CK_IntegralToBoolean;
3504 } else if (type->isObjCObjectPointerType()) {
3505 if (SubExpr->getType()->isBlockPointerType()) {
3506 CK = CK_BlockPointerToObjCPointerCast;
3507 } else if (SubExpr->getType()->isPointerType()) {
3508 CK = CK_CPointerToObjCPointerCast;
3509 } else {
3510 CK = CK_BitCast;
3511 }
3512 } else {
3513 CK = CK_BitCast;
3514 }
3515
3516 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3517 }
3518 // Make id<P...> cast into an 'id' cast.
3519 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3520 if (CE->getType()->isObjCQualifiedIdType()) {
3521 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3522 userExpr = CE->getSubExpr();
3523 CastKind CK;
3524 if (userExpr->getType()->isIntegralType(*Context)) {
3525 CK = CK_IntegralToPointer;
3526 } else if (userExpr->getType()->isBlockPointerType()) {
3527 CK = CK_BlockPointerToObjCPointerCast;
3528 } else if (userExpr->getType()->isPointerType()) {
3529 CK = CK_CPointerToObjCPointerCast;
3530 } else {
3531 CK = CK_BitCast;
3532 }
3533 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3534 CK, userExpr);
3535 }
3536 }
3537 MsgExprs.push_back(userExpr);
3538 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3539 // out the argument in the original expression (since we aren't deleting
3540 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3541 //Exp->setArg(i, 0);
3542 }
3543 // Generate the funky cast.
3544 CastExpr *cast;
3545 SmallVector<QualType, 8> ArgTypes;
3546 QualType returnType;
3547
3548 // Push 'id' and 'SEL', the 2 implicit arguments.
3549 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3550 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3551 else
3552 ArgTypes.push_back(Context->getObjCIdType());
3553 ArgTypes.push_back(Context->getObjCSelType());
3554 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3555 // Push any user argument types.
3556 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3557 E = OMD->param_end(); PI != E; ++PI) {
3558 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3559 ? Context->getObjCIdType()
3560 : (*PI)->getType();
3561 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3562 (void)convertBlockPointerToFunctionPointer(t);
3563 ArgTypes.push_back(t);
3564 }
3565 returnType = Exp->getType();
3566 convertToUnqualifiedObjCType(returnType);
3567 (void)convertBlockPointerToFunctionPointer(returnType);
3568 } else {
3569 returnType = Context->getObjCIdType();
3570 }
3571 // Get the type, we will need to reference it in a couple spots.
3572 QualType msgSendType = MsgSendFlavor->getType();
3573
3574 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003575 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003576 VK_LValue, SourceLocation());
3577
3578 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3579 // If we don't do this cast, we get the following bizarre warning/note:
3580 // xx.m:13: warning: function called through a non-compatible type
3581 // xx.m:13: note: if this code is reached, the program will abort
3582 cast = NoTypeInfoCStyleCastExpr(Context,
3583 Context->getPointerType(Context->VoidTy),
3584 CK_BitCast, DRE);
3585
3586 // Now do the "normal" pointer to function cast.
3587 QualType castType =
3588 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3589 // If we don't have a method decl, force a variadic cast.
3590 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3591 castType = Context->getPointerType(castType);
3592 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3593 cast);
3594
3595 // Don't forget the parens to enforce the proper binding.
3596 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3597
3598 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003599 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3600 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003601 Stmt *ReplacingStmt = CE;
3602 if (MsgSendStretFlavor) {
3603 // We have the method which returns a struct/union. Must also generate
3604 // call to objc_msgSend_stret and hang both varieties on a conditional
3605 // expression which dictate which one to envoke depending on size of
3606 // method's return type.
3607
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003608 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3609 msgSendType, returnType,
3610 ArgTypes, MsgExprs,
3611 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003612
3613 // Build sizeof(returnType)
3614 UnaryExprOrTypeTraitExpr *sizeofExpr =
3615 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3616 Context->getTrivialTypeSourceInfo(returnType),
3617 Context->getSizeType(), SourceLocation(),
3618 SourceLocation());
3619 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3620 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3621 // For X86 it is more complicated and some kind of target specific routine
3622 // is needed to decide what to do.
3623 unsigned IntSize =
3624 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3625 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3626 llvm::APInt(IntSize, 8),
3627 Context->IntTy,
3628 SourceLocation());
3629 BinaryOperator *lessThanExpr =
3630 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003631 VK_RValue, OK_Ordinary, SourceLocation(),
3632 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003633 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3634 ConditionalOperator *CondExpr =
3635 new (Context) ConditionalOperator(lessThanExpr,
3636 SourceLocation(), CE,
3637 SourceLocation(), STCE,
3638 returnType, VK_RValue, OK_Ordinary);
3639 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3640 CondExpr);
3641 }
3642 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3643 return ReplacingStmt;
3644}
3645
3646Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3647 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3648 Exp->getLocEnd());
3649
3650 // Now do the actual rewrite.
3651 ReplaceStmt(Exp, ReplacingStmt);
3652
3653 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3654 return ReplacingStmt;
3655}
3656
3657// typedef struct objc_object Protocol;
3658QualType RewriteModernObjC::getProtocolType() {
3659 if (!ProtocolTypeDecl) {
3660 TypeSourceInfo *TInfo
3661 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3662 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3663 SourceLocation(), SourceLocation(),
3664 &Context->Idents.get("Protocol"),
3665 TInfo);
3666 }
3667 return Context->getTypeDeclType(ProtocolTypeDecl);
3668}
3669
3670/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3671/// a synthesized/forward data reference (to the protocol's metadata).
3672/// The forward references (and metadata) are generated in
3673/// RewriteModernObjC::HandleTranslationUnit().
3674Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003675 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3676 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003677 IdentifierInfo *ID = &Context->Idents.get(Name);
3678 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3679 SourceLocation(), ID, getProtocolType(), 0,
3680 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003681 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3682 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003683 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3684 Context->getPointerType(DRE->getType()),
3685 VK_RValue, OK_Ordinary, SourceLocation());
3686 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3687 CK_BitCast,
3688 DerefExpr);
3689 ReplaceStmt(Exp, castExpr);
3690 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3691 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3692 return castExpr;
3693
3694}
3695
3696bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3697 const char *endBuf) {
3698 while (startBuf < endBuf) {
3699 if (*startBuf == '#') {
3700 // Skip whitespace.
3701 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3702 ;
3703 if (!strncmp(startBuf, "if", strlen("if")) ||
3704 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3705 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3706 !strncmp(startBuf, "define", strlen("define")) ||
3707 !strncmp(startBuf, "undef", strlen("undef")) ||
3708 !strncmp(startBuf, "else", strlen("else")) ||
3709 !strncmp(startBuf, "elif", strlen("elif")) ||
3710 !strncmp(startBuf, "endif", strlen("endif")) ||
3711 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3712 !strncmp(startBuf, "include", strlen("include")) ||
3713 !strncmp(startBuf, "import", strlen("import")) ||
3714 !strncmp(startBuf, "include_next", strlen("include_next")))
3715 return true;
3716 }
3717 startBuf++;
3718 }
3719 return false;
3720}
3721
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003722/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3723/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003724bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003725 TagDecl *Tag,
3726 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003727 if (!IDecl)
3728 return false;
3729 SourceLocation TagLocation;
3730 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3731 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003732 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003733 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003734 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003735 TagLocation = RD->getLocation();
3736 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003737 IDecl->getLocation(), TagLocation);
3738 }
3739 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3740 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3741 return false;
3742 IsNamedDefinition = true;
3743 TagLocation = ED->getLocation();
3744 return Context->getSourceManager().isBeforeInTranslationUnit(
3745 IDecl->getLocation(), TagLocation);
3746
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003747 }
3748 return false;
3749}
3750
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003751/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003752/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003753bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3754 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003755 if (isa<TypedefType>(Type)) {
3756 Result += "\t";
3757 return false;
3758 }
3759
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003760 if (Type->isArrayType()) {
3761 QualType ElemTy = Context->getBaseElementType(Type);
3762 return RewriteObjCFieldDeclType(ElemTy, Result);
3763 }
3764 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003765 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3766 if (RD->isCompleteDefinition()) {
3767 if (RD->isStruct())
3768 Result += "\n\tstruct ";
3769 else if (RD->isUnion())
3770 Result += "\n\tunion ";
3771 else
3772 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003773
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003774 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003775 if (GlobalDefinedTags.count(RD)) {
3776 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003777 Result += " ";
3778 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003779 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003780 Result += " {\n";
3781 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003782 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003783 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003784 RewriteObjCFieldDecl(FD, Result);
3785 }
3786 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003787 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003788 }
3789 }
3790 else if (Type->isEnumeralType()) {
3791 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3792 if (ED->isCompleteDefinition()) {
3793 Result += "\n\tenum ";
3794 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003795 if (GlobalDefinedTags.count(ED)) {
3796 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003797 Result += " ";
3798 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003799 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003800
3801 Result += " {\n";
3802 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3803 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3804 Result += "\t"; Result += EC->getName(); Result += " = ";
3805 llvm::APSInt Val = EC->getInitVal();
3806 Result += Val.toString(10);
3807 Result += ",\n";
3808 }
3809 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003810 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003811 }
3812 }
3813
3814 Result += "\t";
3815 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003816 return false;
3817}
3818
3819
3820/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3821/// It handles elaborated types, as well as enum types in the process.
3822void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3823 std::string &Result) {
3824 QualType Type = fieldDecl->getType();
3825 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003826
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003827 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3828 if (!EleboratedType)
3829 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003830 Result += Name;
3831 if (fieldDecl->isBitField()) {
3832 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3833 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003834 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003835 const ArrayType *AT = Context->getAsArrayType(Type);
3836 do {
3837 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003838 Result += "[";
3839 llvm::APInt Dim = CAT->getSize();
3840 Result += utostr(Dim.getZExtValue());
3841 Result += "]";
3842 }
Eli Friedman6febf122012-12-13 01:43:21 +00003843 AT = Context->getAsArrayType(AT->getElementType());
3844 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003845 }
3846
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003847 Result += ";\n";
3848}
3849
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003850/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3851/// named aggregate types into the input buffer.
3852void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3853 std::string &Result) {
3854 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003855 if (isa<TypedefType>(Type))
3856 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003857 if (Type->isArrayType())
3858 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003859 ObjCContainerDecl *IDecl =
3860 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003861
3862 TagDecl *TD = 0;
3863 if (Type->isRecordType()) {
3864 TD = Type->getAs<RecordType>()->getDecl();
3865 }
3866 else if (Type->isEnumeralType()) {
3867 TD = Type->getAs<EnumType>()->getDecl();
3868 }
3869
3870 if (TD) {
3871 if (GlobalDefinedTags.count(TD))
3872 return;
3873
3874 bool IsNamedDefinition = false;
3875 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3876 RewriteObjCFieldDeclType(Type, Result);
3877 Result += ";";
3878 }
3879 if (IsNamedDefinition)
3880 GlobalDefinedTags.insert(TD);
3881 }
3882
3883}
3884
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003885/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3886/// an objective-c class with ivars.
3887void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3888 std::string &Result) {
3889 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3890 assert(CDecl->getName() != "" &&
3891 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003892 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003893 SmallVector<ObjCIvarDecl *, 8> IVars;
3894 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003895 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003896 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003897
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003898 SourceLocation LocStart = CDecl->getLocStart();
3899 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003900
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003901 const char *startBuf = SM->getCharacterData(LocStart);
3902 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003903
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003904 // If no ivars and no root or if its root, directly or indirectly,
3905 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003906 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003907 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3908 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3909 ReplaceText(LocStart, endBuf-startBuf, Result);
3910 return;
3911 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003912
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003913 // Insert named struct/union definitions inside class to
3914 // outer scope. This follows semantics of locally defined
3915 // struct/unions in objective-c classes.
3916 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3917 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3918
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003919 Result += "\nstruct ";
3920 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003921 Result += "_IMPL {\n";
3922
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003923 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003924 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3925 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3926 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003927 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003928
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003929 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3930 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003931
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003932 Result += "};\n";
3933 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3934 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003935 // Mark this struct as having been generated.
3936 if (!ObjCSynthesizedStructs.insert(CDecl))
3937 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003938}
3939
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003940/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3941/// have been referenced in an ivar access expression.
3942void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3943 std::string &Result) {
3944 // write out ivar offset symbols which have been referenced in an ivar
3945 // access expression.
3946 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3947 if (Ivars.empty())
3948 return;
3949 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3950 e = Ivars.end(); i != e; i++) {
3951 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003952 Result += "\n";
3953 if (LangOpts.MicrosoftExt)
3954 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003955 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003956 if (LangOpts.MicrosoftExt &&
3957 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003958 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3959 Result += "__declspec(dllimport) ";
3960
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003961 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003962 WriteInternalIvarName(CDecl, IvarDecl, Result);
3963 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003964 }
3965}
3966
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003967//===----------------------------------------------------------------------===//
3968// Meta Data Emission
3969//===----------------------------------------------------------------------===//
3970
3971
3972/// RewriteImplementations - This routine rewrites all method implementations
3973/// and emits meta-data.
3974
3975void RewriteModernObjC::RewriteImplementations() {
3976 int ClsDefCount = ClassImplementation.size();
3977 int CatDefCount = CategoryImplementation.size();
3978
3979 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003980 for (int i = 0; i < ClsDefCount; i++) {
3981 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3982 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3983 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003984 assert(false &&
3985 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003986 RewriteImplementationDecl(OIMP);
3987 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003988
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003989 for (int i = 0; i < CatDefCount; i++) {
3990 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3991 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3992 if (CDecl->isImplicitInterfaceDecl())
3993 assert(false &&
3994 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003995 RewriteImplementationDecl(CIMP);
3996 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003997}
3998
3999void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4000 const std::string &Name,
4001 ValueDecl *VD, bool def) {
4002 assert(BlockByRefDeclNo.count(VD) &&
4003 "RewriteByRefString: ByRef decl missing");
4004 if (def)
4005 ResultStr += "struct ";
4006 ResultStr += "__Block_byref_" + Name +
4007 "_" + utostr(BlockByRefDeclNo[VD]) ;
4008}
4009
4010static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4011 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4012 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4013 return false;
4014}
4015
4016std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4017 StringRef funcName,
4018 std::string Tag) {
4019 const FunctionType *AFT = CE->getFunctionType();
4020 QualType RT = AFT->getResultType();
4021 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004022 SourceLocation BlockLoc = CE->getExprLoc();
4023 std::string S;
4024 ConvertSourceLocationToLineDirective(BlockLoc, S);
4025
4026 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4027 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004028
4029 BlockDecl *BD = CE->getBlockDecl();
4030
4031 if (isa<FunctionNoProtoType>(AFT)) {
4032 // No user-supplied arguments. Still need to pass in a pointer to the
4033 // block (to reference imported block decl refs).
4034 S += "(" + StructRef + " *__cself)";
4035 } else if (BD->param_empty()) {
4036 S += "(" + StructRef + " *__cself)";
4037 } else {
4038 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4039 assert(FT && "SynthesizeBlockFunc: No function proto");
4040 S += '(';
4041 // first add the implicit argument.
4042 S += StructRef + " *__cself, ";
4043 std::string ParamStr;
4044 for (BlockDecl::param_iterator AI = BD->param_begin(),
4045 E = BD->param_end(); AI != E; ++AI) {
4046 if (AI != BD->param_begin()) S += ", ";
4047 ParamStr = (*AI)->getNameAsString();
4048 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004049 (void)convertBlockPointerToFunctionPointer(QT);
4050 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004051 S += ParamStr;
4052 }
4053 if (FT->isVariadic()) {
4054 if (!BD->param_empty()) S += ", ";
4055 S += "...";
4056 }
4057 S += ')';
4058 }
4059 S += " {\n";
4060
4061 // Create local declarations to avoid rewriting all closure decl ref exprs.
4062 // First, emit a declaration for all "by ref" decls.
4063 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4064 E = BlockByRefDecls.end(); I != E; ++I) {
4065 S += " ";
4066 std::string Name = (*I)->getNameAsString();
4067 std::string TypeString;
4068 RewriteByRefString(TypeString, Name, (*I));
4069 TypeString += " *";
4070 Name = TypeString + Name;
4071 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4072 }
4073 // Next, emit a declaration for all "by copy" declarations.
4074 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4075 E = BlockByCopyDecls.end(); I != E; ++I) {
4076 S += " ";
4077 // Handle nested closure invocation. For example:
4078 //
4079 // void (^myImportedClosure)(void);
4080 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4081 //
4082 // void (^anotherClosure)(void);
4083 // anotherClosure = ^(void) {
4084 // myImportedClosure(); // import and invoke the closure
4085 // };
4086 //
4087 if (isTopLevelBlockPointerType((*I)->getType())) {
4088 RewriteBlockPointerTypeVariable(S, (*I));
4089 S += " = (";
4090 RewriteBlockPointerType(S, (*I)->getType());
4091 S += ")";
4092 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4093 }
4094 else {
4095 std::string Name = (*I)->getNameAsString();
4096 QualType QT = (*I)->getType();
4097 if (HasLocalVariableExternalStorage(*I))
4098 QT = Context->getPointerType(QT);
4099 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4100 S += Name + " = __cself->" +
4101 (*I)->getNameAsString() + "; // bound by copy\n";
4102 }
4103 }
4104 std::string RewrittenStr = RewrittenBlockExprs[CE];
4105 const char *cstr = RewrittenStr.c_str();
4106 while (*cstr++ != '{') ;
4107 S += cstr;
4108 S += "\n";
4109 return S;
4110}
4111
4112std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4113 StringRef funcName,
4114 std::string Tag) {
4115 std::string StructRef = "struct " + Tag;
4116 std::string S = "static void __";
4117
4118 S += funcName;
4119 S += "_block_copy_" + utostr(i);
4120 S += "(" + StructRef;
4121 S += "*dst, " + StructRef;
4122 S += "*src) {";
4123 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4124 E = ImportedBlockDecls.end(); I != E; ++I) {
4125 ValueDecl *VD = (*I);
4126 S += "_Block_object_assign((void*)&dst->";
4127 S += (*I)->getNameAsString();
4128 S += ", (void*)src->";
4129 S += (*I)->getNameAsString();
4130 if (BlockByRefDeclsPtrSet.count((*I)))
4131 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4132 else if (VD->getType()->isBlockPointerType())
4133 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4134 else
4135 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4136 }
4137 S += "}\n";
4138
4139 S += "\nstatic void __";
4140 S += funcName;
4141 S += "_block_dispose_" + utostr(i);
4142 S += "(" + StructRef;
4143 S += "*src) {";
4144 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4145 E = ImportedBlockDecls.end(); I != E; ++I) {
4146 ValueDecl *VD = (*I);
4147 S += "_Block_object_dispose((void*)src->";
4148 S += (*I)->getNameAsString();
4149 if (BlockByRefDeclsPtrSet.count((*I)))
4150 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4151 else if (VD->getType()->isBlockPointerType())
4152 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4153 else
4154 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4155 }
4156 S += "}\n";
4157 return S;
4158}
4159
4160std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4161 std::string Desc) {
4162 std::string S = "\nstruct " + Tag;
4163 std::string Constructor = " " + Tag;
4164
4165 S += " {\n struct __block_impl impl;\n";
4166 S += " struct " + Desc;
4167 S += "* Desc;\n";
4168
4169 Constructor += "(void *fp, "; // Invoke function pointer.
4170 Constructor += "struct " + Desc; // Descriptor pointer.
4171 Constructor += " *desc";
4172
4173 if (BlockDeclRefs.size()) {
4174 // Output all "by copy" declarations.
4175 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4176 E = BlockByCopyDecls.end(); I != E; ++I) {
4177 S += " ";
4178 std::string FieldName = (*I)->getNameAsString();
4179 std::string ArgName = "_" + FieldName;
4180 // Handle nested closure invocation. For example:
4181 //
4182 // void (^myImportedBlock)(void);
4183 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4184 //
4185 // void (^anotherBlock)(void);
4186 // anotherBlock = ^(void) {
4187 // myImportedBlock(); // import and invoke the closure
4188 // };
4189 //
4190 if (isTopLevelBlockPointerType((*I)->getType())) {
4191 S += "struct __block_impl *";
4192 Constructor += ", void *" + ArgName;
4193 } else {
4194 QualType QT = (*I)->getType();
4195 if (HasLocalVariableExternalStorage(*I))
4196 QT = Context->getPointerType(QT);
4197 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4198 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4199 Constructor += ", " + ArgName;
4200 }
4201 S += FieldName + ";\n";
4202 }
4203 // Output all "by ref" declarations.
4204 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4205 E = BlockByRefDecls.end(); I != E; ++I) {
4206 S += " ";
4207 std::string FieldName = (*I)->getNameAsString();
4208 std::string ArgName = "_" + FieldName;
4209 {
4210 std::string TypeString;
4211 RewriteByRefString(TypeString, FieldName, (*I));
4212 TypeString += " *";
4213 FieldName = TypeString + FieldName;
4214 ArgName = TypeString + ArgName;
4215 Constructor += ", " + ArgName;
4216 }
4217 S += FieldName + "; // by ref\n";
4218 }
4219 // Finish writing the constructor.
4220 Constructor += ", int flags=0)";
4221 // Initialize all "by copy" arguments.
4222 bool firsTime = true;
4223 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4224 E = BlockByCopyDecls.end(); I != E; ++I) {
4225 std::string Name = (*I)->getNameAsString();
4226 if (firsTime) {
4227 Constructor += " : ";
4228 firsTime = false;
4229 }
4230 else
4231 Constructor += ", ";
4232 if (isTopLevelBlockPointerType((*I)->getType()))
4233 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4234 else
4235 Constructor += Name + "(_" + Name + ")";
4236 }
4237 // Initialize all "by ref" arguments.
4238 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4239 E = BlockByRefDecls.end(); I != E; ++I) {
4240 std::string Name = (*I)->getNameAsString();
4241 if (firsTime) {
4242 Constructor += " : ";
4243 firsTime = false;
4244 }
4245 else
4246 Constructor += ", ";
4247 Constructor += Name + "(_" + Name + "->__forwarding)";
4248 }
4249
4250 Constructor += " {\n";
4251 if (GlobalVarDecl)
4252 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4253 else
4254 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4255 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4256
4257 Constructor += " Desc = desc;\n";
4258 } else {
4259 // Finish writing the constructor.
4260 Constructor += ", int flags=0) {\n";
4261 if (GlobalVarDecl)
4262 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4263 else
4264 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4265 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4266 Constructor += " Desc = desc;\n";
4267 }
4268 Constructor += " ";
4269 Constructor += "}\n";
4270 S += Constructor;
4271 S += "};\n";
4272 return S;
4273}
4274
4275std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4276 std::string ImplTag, int i,
4277 StringRef FunName,
4278 unsigned hasCopy) {
4279 std::string S = "\nstatic struct " + DescTag;
4280
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004281 S += " {\n size_t reserved;\n";
4282 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004283 if (hasCopy) {
4284 S += " void (*copy)(struct ";
4285 S += ImplTag; S += "*, struct ";
4286 S += ImplTag; S += "*);\n";
4287
4288 S += " void (*dispose)(struct ";
4289 S += ImplTag; S += "*);\n";
4290 }
4291 S += "} ";
4292
4293 S += DescTag + "_DATA = { 0, sizeof(struct ";
4294 S += ImplTag + ")";
4295 if (hasCopy) {
4296 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4297 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4298 }
4299 S += "};\n";
4300 return S;
4301}
4302
4303void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4304 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004305 bool RewriteSC = (GlobalVarDecl &&
4306 !Blocks.empty() &&
4307 GlobalVarDecl->getStorageClass() == SC_Static &&
4308 GlobalVarDecl->getType().getCVRQualifiers());
4309 if (RewriteSC) {
4310 std::string SC(" void __");
4311 SC += GlobalVarDecl->getNameAsString();
4312 SC += "() {}";
4313 InsertText(FunLocStart, SC);
4314 }
4315
4316 // Insert closures that were part of the function.
4317 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4318 CollectBlockDeclRefInfo(Blocks[i]);
4319 // Need to copy-in the inner copied-in variables not actually used in this
4320 // block.
4321 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004322 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004323 ValueDecl *VD = Exp->getDecl();
4324 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004325 if (!VD->hasAttr<BlocksAttr>()) {
4326 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4327 BlockByCopyDeclsPtrSet.insert(VD);
4328 BlockByCopyDecls.push_back(VD);
4329 }
4330 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004331 }
John McCallf4b88a42012-03-10 09:33:50 +00004332
4333 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004334 BlockByRefDeclsPtrSet.insert(VD);
4335 BlockByRefDecls.push_back(VD);
4336 }
John McCallf4b88a42012-03-10 09:33:50 +00004337
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004338 // imported objects in the inner blocks not used in the outer
4339 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004340 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004341 VD->getType()->isBlockPointerType())
4342 ImportedBlockDecls.insert(VD);
4343 }
4344
4345 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4346 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4347
4348 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4349
4350 InsertText(FunLocStart, CI);
4351
4352 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4353
4354 InsertText(FunLocStart, CF);
4355
4356 if (ImportedBlockDecls.size()) {
4357 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4358 InsertText(FunLocStart, HF);
4359 }
4360 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4361 ImportedBlockDecls.size() > 0);
4362 InsertText(FunLocStart, BD);
4363
4364 BlockDeclRefs.clear();
4365 BlockByRefDecls.clear();
4366 BlockByRefDeclsPtrSet.clear();
4367 BlockByCopyDecls.clear();
4368 BlockByCopyDeclsPtrSet.clear();
4369 ImportedBlockDecls.clear();
4370 }
4371 if (RewriteSC) {
4372 // Must insert any 'const/volatile/static here. Since it has been
4373 // removed as result of rewriting of block literals.
4374 std::string SC;
4375 if (GlobalVarDecl->getStorageClass() == SC_Static)
4376 SC = "static ";
4377 if (GlobalVarDecl->getType().isConstQualified())
4378 SC += "const ";
4379 if (GlobalVarDecl->getType().isVolatileQualified())
4380 SC += "volatile ";
4381 if (GlobalVarDecl->getType().isRestrictQualified())
4382 SC += "restrict ";
4383 InsertText(FunLocStart, SC);
4384 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004385 if (GlobalConstructionExp) {
4386 // extra fancy dance for global literal expression.
4387
4388 // Always the latest block expression on the block stack.
4389 std::string Tag = "__";
4390 Tag += FunName;
4391 Tag += "_block_impl_";
4392 Tag += utostr(Blocks.size()-1);
4393 std::string globalBuf = "static ";
4394 globalBuf += Tag; globalBuf += " ";
4395 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004396
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004397 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004398 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004399 PrintingPolicy(LangOpts));
4400 globalBuf += constructorExprBuf.str();
4401 globalBuf += ";\n";
4402 InsertText(FunLocStart, globalBuf);
4403 GlobalConstructionExp = 0;
4404 }
4405
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004406 Blocks.clear();
4407 InnerDeclRefsCount.clear();
4408 InnerDeclRefs.clear();
4409 RewrittenBlockExprs.clear();
4410}
4411
4412void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004413 SourceLocation FunLocStart =
4414 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4415 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004416 StringRef FuncName = FD->getName();
4417
4418 SynthesizeBlockLiterals(FunLocStart, FuncName);
4419}
4420
4421static void BuildUniqueMethodName(std::string &Name,
4422 ObjCMethodDecl *MD) {
4423 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4424 Name = IFace->getName();
4425 Name += "__" + MD->getSelector().getAsString();
4426 // Convert colons to underscores.
4427 std::string::size_type loc = 0;
4428 while ((loc = Name.find(":", loc)) != std::string::npos)
4429 Name.replace(loc, 1, "_");
4430}
4431
4432void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4433 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4434 //SourceLocation FunLocStart = MD->getLocStart();
4435 SourceLocation FunLocStart = MD->getLocStart();
4436 std::string FuncName;
4437 BuildUniqueMethodName(FuncName, MD);
4438 SynthesizeBlockLiterals(FunLocStart, FuncName);
4439}
4440
4441void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4442 for (Stmt::child_range CI = S->children(); CI; ++CI)
4443 if (*CI) {
4444 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4445 GetBlockDeclRefExprs(CBE->getBody());
4446 else
4447 GetBlockDeclRefExprs(*CI);
4448 }
4449 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004450 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4451 if (DRE->refersToEnclosingLocal()) {
4452 // FIXME: Handle enums.
4453 if (!isa<FunctionDecl>(DRE->getDecl()))
4454 BlockDeclRefs.push_back(DRE);
4455 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4456 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004457 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004458 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004459
4460 return;
4461}
4462
4463void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004464 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004465 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4466 for (Stmt::child_range CI = S->children(); CI; ++CI)
4467 if (*CI) {
4468 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4469 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4470 GetInnerBlockDeclRefExprs(CBE->getBody(),
4471 InnerBlockDeclRefs,
4472 InnerContexts);
4473 }
4474 else
4475 GetInnerBlockDeclRefExprs(*CI,
4476 InnerBlockDeclRefs,
4477 InnerContexts);
4478
4479 }
4480 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004481 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4482 if (DRE->refersToEnclosingLocal()) {
4483 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4484 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4485 InnerBlockDeclRefs.push_back(DRE);
4486 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4487 if (Var->isFunctionOrMethodVarDecl())
4488 ImportedLocalExternalDecls.insert(Var);
4489 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004490 }
4491
4492 return;
4493}
4494
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004495/// convertObjCTypeToCStyleType - This routine converts such objc types
4496/// as qualified objects, and blocks to their closest c/c++ types that
4497/// it can. It returns true if input type was modified.
4498bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4499 QualType oldT = T;
4500 convertBlockPointerToFunctionPointer(T);
4501 if (T->isFunctionPointerType()) {
4502 QualType PointeeTy;
4503 if (const PointerType* PT = T->getAs<PointerType>()) {
4504 PointeeTy = PT->getPointeeType();
4505 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4506 T = convertFunctionTypeOfBlocks(FT);
4507 T = Context->getPointerType(T);
4508 }
4509 }
4510 }
4511
4512 convertToUnqualifiedObjCType(T);
4513 return T != oldT;
4514}
4515
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004516/// convertFunctionTypeOfBlocks - This routine converts a function type
4517/// whose result type may be a block pointer or whose argument type(s)
4518/// might be block pointers to an equivalent function type replacing
4519/// all block pointers to function pointers.
4520QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4521 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4522 // FTP will be null for closures that don't take arguments.
4523 // Generate a funky cast.
4524 SmallVector<QualType, 8> ArgTypes;
4525 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004526 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004527
4528 if (FTP) {
4529 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4530 E = FTP->arg_type_end(); I && (I != E); ++I) {
4531 QualType t = *I;
4532 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004533 if (convertObjCTypeToCStyleType(t))
4534 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004535 ArgTypes.push_back(t);
4536 }
4537 }
4538 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004539 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004540 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4541 else FuncType = QualType(FT, 0);
4542 return FuncType;
4543}
4544
4545Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4546 // Navigate to relevant type information.
4547 const BlockPointerType *CPT = 0;
4548
4549 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4550 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004551 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4552 CPT = MExpr->getType()->getAs<BlockPointerType>();
4553 }
4554 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4555 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4556 }
4557 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4558 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4559 else if (const ConditionalOperator *CEXPR =
4560 dyn_cast<ConditionalOperator>(BlockExp)) {
4561 Expr *LHSExp = CEXPR->getLHS();
4562 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4563 Expr *RHSExp = CEXPR->getRHS();
4564 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4565 Expr *CONDExp = CEXPR->getCond();
4566 ConditionalOperator *CondExpr =
4567 new (Context) ConditionalOperator(CONDExp,
4568 SourceLocation(), cast<Expr>(LHSStmt),
4569 SourceLocation(), cast<Expr>(RHSStmt),
4570 Exp->getType(), VK_RValue, OK_Ordinary);
4571 return CondExpr;
4572 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4573 CPT = IRE->getType()->getAs<BlockPointerType>();
4574 } else if (const PseudoObjectExpr *POE
4575 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4576 CPT = POE->getType()->castAs<BlockPointerType>();
4577 } else {
4578 assert(1 && "RewriteBlockClass: Bad type");
4579 }
4580 assert(CPT && "RewriteBlockClass: Bad type");
4581 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4582 assert(FT && "RewriteBlockClass: Bad type");
4583 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4584 // FTP will be null for closures that don't take arguments.
4585
4586 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4587 SourceLocation(), SourceLocation(),
4588 &Context->Idents.get("__block_impl"));
4589 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4590
4591 // Generate a funky cast.
4592 SmallVector<QualType, 8> ArgTypes;
4593
4594 // Push the block argument type.
4595 ArgTypes.push_back(PtrBlock);
4596 if (FTP) {
4597 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4598 E = FTP->arg_type_end(); I && (I != E); ++I) {
4599 QualType t = *I;
4600 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4601 if (!convertBlockPointerToFunctionPointer(t))
4602 convertToUnqualifiedObjCType(t);
4603 ArgTypes.push_back(t);
4604 }
4605 }
4606 // Now do the pointer to function cast.
4607 QualType PtrToFuncCastType
4608 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4609
4610 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4611
4612 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4613 CK_BitCast,
4614 const_cast<Expr*>(BlockExp));
4615 // Don't forget the parens to enforce the proper binding.
4616 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4617 BlkCast);
4618 //PE->dump();
4619
4620 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4621 SourceLocation(),
4622 &Context->Idents.get("FuncPtr"),
4623 Context->VoidPtrTy, 0,
4624 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004625 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004626 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4627 FD->getType(), VK_LValue,
4628 OK_Ordinary);
4629
4630
4631 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4632 CK_BitCast, ME);
4633 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4634
4635 SmallVector<Expr*, 8> BlkExprs;
4636 // Add the implicit argument.
4637 BlkExprs.push_back(BlkCast);
4638 // Add the user arguments.
4639 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4640 E = Exp->arg_end(); I != E; ++I) {
4641 BlkExprs.push_back(*I);
4642 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004643 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004644 Exp->getType(), VK_RValue,
4645 SourceLocation());
4646 return CE;
4647}
4648
4649// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004650// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004651// For example:
4652//
4653// int main() {
4654// __block Foo *f;
4655// __block int i;
4656//
4657// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004658// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004659// i = 77;
4660// };
4661//}
John McCallf4b88a42012-03-10 09:33:50 +00004662Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004663 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4664 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004665 ValueDecl *VD = DeclRefExp->getDecl();
4666 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004667
4668 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4669 SourceLocation(),
4670 &Context->Idents.get("__forwarding"),
4671 Context->VoidPtrTy, 0,
4672 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004673 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004674 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4675 FD, SourceLocation(),
4676 FD->getType(), VK_LValue,
4677 OK_Ordinary);
4678
4679 StringRef Name = VD->getName();
4680 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4681 &Context->Idents.get(Name),
4682 Context->VoidPtrTy, 0,
4683 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004684 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004685 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4686 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4687
4688
4689
4690 // Need parens to enforce precedence.
4691 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4692 DeclRefExp->getExprLoc(),
4693 ME);
4694 ReplaceStmt(DeclRefExp, PE);
4695 return PE;
4696}
4697
4698// Rewrites the imported local variable V with external storage
4699// (static, extern, etc.) as *V
4700//
4701Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4702 ValueDecl *VD = DRE->getDecl();
4703 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4704 if (!ImportedLocalExternalDecls.count(Var))
4705 return DRE;
4706 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4707 VK_LValue, OK_Ordinary,
4708 DRE->getLocation());
4709 // Need parens to enforce precedence.
4710 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4711 Exp);
4712 ReplaceStmt(DRE, PE);
4713 return PE;
4714}
4715
4716void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4717 SourceLocation LocStart = CE->getLParenLoc();
4718 SourceLocation LocEnd = CE->getRParenLoc();
4719
4720 // Need to avoid trying to rewrite synthesized casts.
4721 if (LocStart.isInvalid())
4722 return;
4723 // Need to avoid trying to rewrite casts contained in macros.
4724 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4725 return;
4726
4727 const char *startBuf = SM->getCharacterData(LocStart);
4728 const char *endBuf = SM->getCharacterData(LocEnd);
4729 QualType QT = CE->getType();
4730 const Type* TypePtr = QT->getAs<Type>();
4731 if (isa<TypeOfExprType>(TypePtr)) {
4732 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4733 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4734 std::string TypeAsString = "(";
4735 RewriteBlockPointerType(TypeAsString, QT);
4736 TypeAsString += ")";
4737 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4738 return;
4739 }
4740 // advance the location to startArgList.
4741 const char *argPtr = startBuf;
4742
4743 while (*argPtr++ && (argPtr < endBuf)) {
4744 switch (*argPtr) {
4745 case '^':
4746 // Replace the '^' with '*'.
4747 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4748 ReplaceText(LocStart, 1, "*");
4749 break;
4750 }
4751 }
4752 return;
4753}
4754
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004755void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4756 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004757 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4758 CastKind != CK_AnyPointerToBlockPointerCast)
4759 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004760
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004761 QualType QT = IC->getType();
4762 (void)convertBlockPointerToFunctionPointer(QT);
4763 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4764 std::string Str = "(";
4765 Str += TypeString;
4766 Str += ")";
4767 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4768
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004769 return;
4770}
4771
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004772void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4773 SourceLocation DeclLoc = FD->getLocation();
4774 unsigned parenCount = 0;
4775
4776 // We have 1 or more arguments that have closure pointers.
4777 const char *startBuf = SM->getCharacterData(DeclLoc);
4778 const char *startArgList = strchr(startBuf, '(');
4779
4780 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4781
4782 parenCount++;
4783 // advance the location to startArgList.
4784 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4785 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4786
4787 const char *argPtr = startArgList;
4788
4789 while (*argPtr++ && parenCount) {
4790 switch (*argPtr) {
4791 case '^':
4792 // Replace the '^' with '*'.
4793 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4794 ReplaceText(DeclLoc, 1, "*");
4795 break;
4796 case '(':
4797 parenCount++;
4798 break;
4799 case ')':
4800 parenCount--;
4801 break;
4802 }
4803 }
4804 return;
4805}
4806
4807bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4808 const FunctionProtoType *FTP;
4809 const PointerType *PT = QT->getAs<PointerType>();
4810 if (PT) {
4811 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4812 } else {
4813 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4814 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4815 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4816 }
4817 if (FTP) {
4818 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4819 E = FTP->arg_type_end(); I != E; ++I)
4820 if (isTopLevelBlockPointerType(*I))
4821 return true;
4822 }
4823 return false;
4824}
4825
4826bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4827 const FunctionProtoType *FTP;
4828 const PointerType *PT = QT->getAs<PointerType>();
4829 if (PT) {
4830 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4831 } else {
4832 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4833 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4834 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4835 }
4836 if (FTP) {
4837 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4838 E = FTP->arg_type_end(); I != E; ++I) {
4839 if ((*I)->isObjCQualifiedIdType())
4840 return true;
4841 if ((*I)->isObjCObjectPointerType() &&
4842 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4843 return true;
4844 }
4845
4846 }
4847 return false;
4848}
4849
4850void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4851 const char *&RParen) {
4852 const char *argPtr = strchr(Name, '(');
4853 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4854
4855 LParen = argPtr; // output the start.
4856 argPtr++; // skip past the left paren.
4857 unsigned parenCount = 1;
4858
4859 while (*argPtr && parenCount) {
4860 switch (*argPtr) {
4861 case '(': parenCount++; break;
4862 case ')': parenCount--; break;
4863 default: break;
4864 }
4865 if (parenCount) argPtr++;
4866 }
4867 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4868 RParen = argPtr; // output the end
4869}
4870
4871void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4872 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4873 RewriteBlockPointerFunctionArgs(FD);
4874 return;
4875 }
4876 // Handle Variables and Typedefs.
4877 SourceLocation DeclLoc = ND->getLocation();
4878 QualType DeclT;
4879 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4880 DeclT = VD->getType();
4881 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4882 DeclT = TDD->getUnderlyingType();
4883 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4884 DeclT = FD->getType();
4885 else
4886 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4887
4888 const char *startBuf = SM->getCharacterData(DeclLoc);
4889 const char *endBuf = startBuf;
4890 // scan backward (from the decl location) for the end of the previous decl.
4891 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4892 startBuf--;
4893 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4894 std::string buf;
4895 unsigned OrigLength=0;
4896 // *startBuf != '^' if we are dealing with a pointer to function that
4897 // may take block argument types (which will be handled below).
4898 if (*startBuf == '^') {
4899 // Replace the '^' with '*', computing a negative offset.
4900 buf = '*';
4901 startBuf++;
4902 OrigLength++;
4903 }
4904 while (*startBuf != ')') {
4905 buf += *startBuf;
4906 startBuf++;
4907 OrigLength++;
4908 }
4909 buf += ')';
4910 OrigLength++;
4911
4912 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4913 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4914 // Replace the '^' with '*' for arguments.
4915 // Replace id<P> with id/*<>*/
4916 DeclLoc = ND->getLocation();
4917 startBuf = SM->getCharacterData(DeclLoc);
4918 const char *argListBegin, *argListEnd;
4919 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4920 while (argListBegin < argListEnd) {
4921 if (*argListBegin == '^')
4922 buf += '*';
4923 else if (*argListBegin == '<') {
4924 buf += "/*";
4925 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00004926 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004927 while (*argListBegin != '>') {
4928 buf += *argListBegin++;
4929 OrigLength++;
4930 }
4931 buf += *argListBegin;
4932 buf += "*/";
4933 }
4934 else
4935 buf += *argListBegin;
4936 argListBegin++;
4937 OrigLength++;
4938 }
4939 buf += ')';
4940 OrigLength++;
4941 }
4942 ReplaceText(Start, OrigLength, buf);
4943
4944 return;
4945}
4946
4947
4948/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4949/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4950/// struct Block_byref_id_object *src) {
4951/// _Block_object_assign (&_dest->object, _src->object,
4952/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4953/// [|BLOCK_FIELD_IS_WEAK]) // object
4954/// _Block_object_assign(&_dest->object, _src->object,
4955/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4956/// [|BLOCK_FIELD_IS_WEAK]) // block
4957/// }
4958/// And:
4959/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4960/// _Block_object_dispose(_src->object,
4961/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4962/// [|BLOCK_FIELD_IS_WEAK]) // object
4963/// _Block_object_dispose(_src->object,
4964/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4965/// [|BLOCK_FIELD_IS_WEAK]) // block
4966/// }
4967
4968std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4969 int flag) {
4970 std::string S;
4971 if (CopyDestroyCache.count(flag))
4972 return S;
4973 CopyDestroyCache.insert(flag);
4974 S = "static void __Block_byref_id_object_copy_";
4975 S += utostr(flag);
4976 S += "(void *dst, void *src) {\n";
4977
4978 // offset into the object pointer is computed as:
4979 // void * + void* + int + int + void* + void *
4980 unsigned IntSize =
4981 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4982 unsigned VoidPtrSize =
4983 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4984
4985 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4986 S += " _Block_object_assign((char*)dst + ";
4987 S += utostr(offset);
4988 S += ", *(void * *) ((char*)src + ";
4989 S += utostr(offset);
4990 S += "), ";
4991 S += utostr(flag);
4992 S += ");\n}\n";
4993
4994 S += "static void __Block_byref_id_object_dispose_";
4995 S += utostr(flag);
4996 S += "(void *src) {\n";
4997 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4998 S += utostr(offset);
4999 S += "), ";
5000 S += utostr(flag);
5001 S += ");\n}\n";
5002 return S;
5003}
5004
5005/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5006/// the declaration into:
5007/// struct __Block_byref_ND {
5008/// void *__isa; // NULL for everything except __weak pointers
5009/// struct __Block_byref_ND *__forwarding;
5010/// int32_t __flags;
5011/// int32_t __size;
5012/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5013/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5014/// typex ND;
5015/// };
5016///
5017/// It then replaces declaration of ND variable with:
5018/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5019/// __size=sizeof(struct __Block_byref_ND),
5020/// ND=initializer-if-any};
5021///
5022///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005023void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5024 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005025 int flag = 0;
5026 int isa = 0;
5027 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5028 if (DeclLoc.isInvalid())
5029 // If type location is missing, it is because of missing type (a warning).
5030 // Use variable's location which is good for this case.
5031 DeclLoc = ND->getLocation();
5032 const char *startBuf = SM->getCharacterData(DeclLoc);
5033 SourceLocation X = ND->getLocEnd();
5034 X = SM->getExpansionLoc(X);
5035 const char *endBuf = SM->getCharacterData(X);
5036 std::string Name(ND->getNameAsString());
5037 std::string ByrefType;
5038 RewriteByRefString(ByrefType, Name, ND, true);
5039 ByrefType += " {\n";
5040 ByrefType += " void *__isa;\n";
5041 RewriteByRefString(ByrefType, Name, ND);
5042 ByrefType += " *__forwarding;\n";
5043 ByrefType += " int __flags;\n";
5044 ByrefType += " int __size;\n";
5045 // Add void *__Block_byref_id_object_copy;
5046 // void *__Block_byref_id_object_dispose; if needed.
5047 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005048 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005049 if (HasCopyAndDispose) {
5050 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5051 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5052 }
5053
5054 QualType T = Ty;
5055 (void)convertBlockPointerToFunctionPointer(T);
5056 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5057
5058 ByrefType += " " + Name + ";\n";
5059 ByrefType += "};\n";
5060 // Insert this type in global scope. It is needed by helper function.
5061 SourceLocation FunLocStart;
5062 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005063 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005064 else {
5065 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5066 FunLocStart = CurMethodDef->getLocStart();
5067 }
5068 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005069
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005070 if (Ty.isObjCGCWeak()) {
5071 flag |= BLOCK_FIELD_IS_WEAK;
5072 isa = 1;
5073 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005074 if (HasCopyAndDispose) {
5075 flag = BLOCK_BYREF_CALLER;
5076 QualType Ty = ND->getType();
5077 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5078 if (Ty->isBlockPointerType())
5079 flag |= BLOCK_FIELD_IS_BLOCK;
5080 else
5081 flag |= BLOCK_FIELD_IS_OBJECT;
5082 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5083 if (!HF.empty())
5084 InsertText(FunLocStart, HF);
5085 }
5086
5087 // struct __Block_byref_ND ND =
5088 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5089 // initializer-if-any};
5090 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005091 // FIXME. rewriter does not support __block c++ objects which
5092 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005093 if (hasInit)
5094 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5095 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5096 if (CXXDecl && CXXDecl->isDefaultConstructor())
5097 hasInit = false;
5098 }
5099
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005100 unsigned flags = 0;
5101 if (HasCopyAndDispose)
5102 flags |= BLOCK_HAS_COPY_DISPOSE;
5103 Name = ND->getNameAsString();
5104 ByrefType.clear();
5105 RewriteByRefString(ByrefType, Name, ND);
5106 std::string ForwardingCastType("(");
5107 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005108 ByrefType += " " + Name + " = {(void*)";
5109 ByrefType += utostr(isa);
5110 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5111 ByrefType += utostr(flags);
5112 ByrefType += ", ";
5113 ByrefType += "sizeof(";
5114 RewriteByRefString(ByrefType, Name, ND);
5115 ByrefType += ")";
5116 if (HasCopyAndDispose) {
5117 ByrefType += ", __Block_byref_id_object_copy_";
5118 ByrefType += utostr(flag);
5119 ByrefType += ", __Block_byref_id_object_dispose_";
5120 ByrefType += utostr(flag);
5121 }
5122
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005123 if (!firstDecl) {
5124 // In multiple __block declarations, and for all but 1st declaration,
5125 // find location of the separating comma. This would be start location
5126 // where new text is to be inserted.
5127 DeclLoc = ND->getLocation();
5128 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5129 const char *commaBuf = startDeclBuf;
5130 while (*commaBuf != ',')
5131 commaBuf--;
5132 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5133 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5134 startBuf = commaBuf;
5135 }
5136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005137 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005138 ByrefType += "};\n";
5139 unsigned nameSize = Name.size();
5140 // for block or function pointer declaration. Name is aleady
5141 // part of the declaration.
5142 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5143 nameSize = 1;
5144 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5145 }
5146 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005147 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005148 SourceLocation startLoc;
5149 Expr *E = ND->getInit();
5150 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5151 startLoc = ECE->getLParenLoc();
5152 else
5153 startLoc = E->getLocStart();
5154 startLoc = SM->getExpansionLoc(startLoc);
5155 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005156 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005157
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005158 const char separator = lastDecl ? ';' : ',';
5159 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5160 const char *separatorBuf = strchr(startInitializerBuf, separator);
5161 assert((*separatorBuf == separator) &&
5162 "RewriteByRefVar: can't find ';' or ','");
5163 SourceLocation separatorLoc =
5164 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5165
5166 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005167 }
5168 return;
5169}
5170
5171void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5172 // Add initializers for any closure decl refs.
5173 GetBlockDeclRefExprs(Exp->getBody());
5174 if (BlockDeclRefs.size()) {
5175 // Unique all "by copy" declarations.
5176 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005177 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005178 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5179 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5180 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5181 }
5182 }
5183 // Unique all "by ref" declarations.
5184 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005185 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005186 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5187 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5188 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5189 }
5190 }
5191 // Find any imported blocks...they will need special attention.
5192 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005193 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005194 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5195 BlockDeclRefs[i]->getType()->isBlockPointerType())
5196 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5197 }
5198}
5199
5200FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5201 IdentifierInfo *ID = &Context->Idents.get(name);
5202 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5203 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5204 SourceLocation(), ID, FType, 0, SC_Extern,
5205 SC_None, false, false);
5206}
5207
5208Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005209 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005210
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005211 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005212
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005213 Blocks.push_back(Exp);
5214
5215 CollectBlockDeclRefInfo(Exp);
5216
5217 // Add inner imported variables now used in current block.
5218 int countOfInnerDecls = 0;
5219 if (!InnerBlockDeclRefs.empty()) {
5220 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005221 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005222 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005223 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005224 // We need to save the copied-in variables in nested
5225 // blocks because it is needed at the end for some of the API generations.
5226 // See SynthesizeBlockLiterals routine.
5227 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5228 BlockDeclRefs.push_back(Exp);
5229 BlockByCopyDeclsPtrSet.insert(VD);
5230 BlockByCopyDecls.push_back(VD);
5231 }
John McCallf4b88a42012-03-10 09:33:50 +00005232 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005233 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5234 BlockDeclRefs.push_back(Exp);
5235 BlockByRefDeclsPtrSet.insert(VD);
5236 BlockByRefDecls.push_back(VD);
5237 }
5238 }
5239 // Find any imported blocks...they will need special attention.
5240 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005241 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005242 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5243 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5244 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5245 }
5246 InnerDeclRefsCount.push_back(countOfInnerDecls);
5247
5248 std::string FuncName;
5249
5250 if (CurFunctionDef)
5251 FuncName = CurFunctionDef->getNameAsString();
5252 else if (CurMethodDef)
5253 BuildUniqueMethodName(FuncName, CurMethodDef);
5254 else if (GlobalVarDecl)
5255 FuncName = std::string(GlobalVarDecl->getNameAsString());
5256
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005257 bool GlobalBlockExpr =
5258 block->getDeclContext()->getRedeclContext()->isFileContext();
5259
5260 if (GlobalBlockExpr && !GlobalVarDecl) {
5261 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5262 GlobalBlockExpr = false;
5263 }
5264
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005265 std::string BlockNumber = utostr(Blocks.size()-1);
5266
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005267 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5268
5269 // Get a pointer to the function type so we can cast appropriately.
5270 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5271 QualType FType = Context->getPointerType(BFT);
5272
5273 FunctionDecl *FD;
5274 Expr *NewRep;
5275
5276 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005277 std::string Tag;
5278
5279 if (GlobalBlockExpr)
5280 Tag = "__global_";
5281 else
5282 Tag = "__";
5283 Tag += FuncName + "_block_impl_" + BlockNumber;
5284
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005285 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005286 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005287 SourceLocation());
5288
5289 SmallVector<Expr*, 4> InitExprs;
5290
5291 // Initialize the block function.
5292 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005293 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5294 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005295 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5296 CK_BitCast, Arg);
5297 InitExprs.push_back(castExpr);
5298
5299 // Initialize the block descriptor.
5300 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5301
5302 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5303 SourceLocation(), SourceLocation(),
5304 &Context->Idents.get(DescData.c_str()),
5305 Context->VoidPtrTy, 0,
5306 SC_Static, SC_None);
5307 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005308 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005309 Context->VoidPtrTy,
5310 VK_LValue,
5311 SourceLocation()),
5312 UO_AddrOf,
5313 Context->getPointerType(Context->VoidPtrTy),
5314 VK_RValue, OK_Ordinary,
5315 SourceLocation());
5316 InitExprs.push_back(DescRefExpr);
5317
5318 // Add initializers for any closure decl refs.
5319 if (BlockDeclRefs.size()) {
5320 Expr *Exp;
5321 // Output all "by copy" declarations.
5322 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5323 E = BlockByCopyDecls.end(); I != E; ++I) {
5324 if (isObjCType((*I)->getType())) {
5325 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5326 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005327 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5328 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005329 if (HasLocalVariableExternalStorage(*I)) {
5330 QualType QT = (*I)->getType();
5331 QT = Context->getPointerType(QT);
5332 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5333 OK_Ordinary, SourceLocation());
5334 }
5335 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5336 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005337 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5338 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005339 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5340 CK_BitCast, Arg);
5341 } else {
5342 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005343 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5344 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005345 if (HasLocalVariableExternalStorage(*I)) {
5346 QualType QT = (*I)->getType();
5347 QT = Context->getPointerType(QT);
5348 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5349 OK_Ordinary, SourceLocation());
5350 }
5351
5352 }
5353 InitExprs.push_back(Exp);
5354 }
5355 // Output all "by ref" declarations.
5356 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5357 E = BlockByRefDecls.end(); I != E; ++I) {
5358 ValueDecl *ND = (*I);
5359 std::string Name(ND->getNameAsString());
5360 std::string RecName;
5361 RewriteByRefString(RecName, Name, ND, true);
5362 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5363 + sizeof("struct"));
5364 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5365 SourceLocation(), SourceLocation(),
5366 II);
5367 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5368 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5369
5370 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005371 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005372 SourceLocation());
5373 bool isNestedCapturedVar = false;
5374 if (block)
5375 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5376 ce = block->capture_end(); ci != ce; ++ci) {
5377 const VarDecl *variable = ci->getVariable();
5378 if (variable == ND && ci->isNested()) {
5379 assert (ci->isByRef() &&
5380 "SynthBlockInitExpr - captured block variable is not byref");
5381 isNestedCapturedVar = true;
5382 break;
5383 }
5384 }
5385 // captured nested byref variable has its address passed. Do not take
5386 // its address again.
5387 if (!isNestedCapturedVar)
5388 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5389 Context->getPointerType(Exp->getType()),
5390 VK_RValue, OK_Ordinary, SourceLocation());
5391 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5392 InitExprs.push_back(Exp);
5393 }
5394 }
5395 if (ImportedBlockDecls.size()) {
5396 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5397 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5398 unsigned IntSize =
5399 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5400 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5401 Context->IntTy, SourceLocation());
5402 InitExprs.push_back(FlagExp);
5403 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005404 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005405 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005406
5407 if (GlobalBlockExpr) {
5408 assert (GlobalConstructionExp == 0 &&
5409 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5410 GlobalConstructionExp = NewRep;
5411 NewRep = DRE;
5412 }
5413
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005414 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5415 Context->getPointerType(NewRep->getType()),
5416 VK_RValue, OK_Ordinary, SourceLocation());
5417 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5418 NewRep);
5419 BlockDeclRefs.clear();
5420 BlockByRefDecls.clear();
5421 BlockByRefDeclsPtrSet.clear();
5422 BlockByCopyDecls.clear();
5423 BlockByCopyDeclsPtrSet.clear();
5424 ImportedBlockDecls.clear();
5425 return NewRep;
5426}
5427
5428bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5429 if (const ObjCForCollectionStmt * CS =
5430 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5431 return CS->getElement() == DS;
5432 return false;
5433}
5434
5435//===----------------------------------------------------------------------===//
5436// Function Body / Expression rewriting
5437//===----------------------------------------------------------------------===//
5438
5439Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5440 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5441 isa<DoStmt>(S) || isa<ForStmt>(S))
5442 Stmts.push_back(S);
5443 else if (isa<ObjCForCollectionStmt>(S)) {
5444 Stmts.push_back(S);
5445 ObjCBcLabelNo.push_back(++BcLabelCount);
5446 }
5447
5448 // Pseudo-object operations and ivar references need special
5449 // treatment because we're going to recursively rewrite them.
5450 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5451 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5452 return RewritePropertyOrImplicitSetter(PseudoOp);
5453 } else {
5454 return RewritePropertyOrImplicitGetter(PseudoOp);
5455 }
5456 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5457 return RewriteObjCIvarRefExpr(IvarRefExpr);
5458 }
5459
5460 SourceRange OrigStmtRange = S->getSourceRange();
5461
5462 // Perform a bottom up rewrite of all children.
5463 for (Stmt::child_range CI = S->children(); CI; ++CI)
5464 if (*CI) {
5465 Stmt *childStmt = (*CI);
5466 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5467 if (newStmt) {
5468 *CI = newStmt;
5469 }
5470 }
5471
5472 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005473 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005474 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5475 InnerContexts.insert(BE->getBlockDecl());
5476 ImportedLocalExternalDecls.clear();
5477 GetInnerBlockDeclRefExprs(BE->getBody(),
5478 InnerBlockDeclRefs, InnerContexts);
5479 // Rewrite the block body in place.
5480 Stmt *SaveCurrentBody = CurrentBody;
5481 CurrentBody = BE->getBody();
5482 PropParentMap = 0;
5483 // block literal on rhs of a property-dot-sytax assignment
5484 // must be replaced by its synthesize ast so getRewrittenText
5485 // works as expected. In this case, what actually ends up on RHS
5486 // is the blockTranscribed which is the helper function for the
5487 // block literal; as in: self.c = ^() {[ace ARR];};
5488 bool saveDisableReplaceStmt = DisableReplaceStmt;
5489 DisableReplaceStmt = false;
5490 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5491 DisableReplaceStmt = saveDisableReplaceStmt;
5492 CurrentBody = SaveCurrentBody;
5493 PropParentMap = 0;
5494 ImportedLocalExternalDecls.clear();
5495 // Now we snarf the rewritten text and stash it away for later use.
5496 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5497 RewrittenBlockExprs[BE] = Str;
5498
5499 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5500
5501 //blockTranscribed->dump();
5502 ReplaceStmt(S, blockTranscribed);
5503 return blockTranscribed;
5504 }
5505 // Handle specific things.
5506 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5507 return RewriteAtEncode(AtEncode);
5508
5509 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5510 return RewriteAtSelector(AtSelector);
5511
5512 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5513 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005514
5515 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5516 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005517
Patrick Beardeb382ec2012-04-19 00:25:12 +00005518 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5519 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005520
5521 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5522 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005523
5524 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5525 dyn_cast<ObjCDictionaryLiteral>(S))
5526 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005527
5528 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5529#if 0
5530 // Before we rewrite it, put the original message expression in a comment.
5531 SourceLocation startLoc = MessExpr->getLocStart();
5532 SourceLocation endLoc = MessExpr->getLocEnd();
5533
5534 const char *startBuf = SM->getCharacterData(startLoc);
5535 const char *endBuf = SM->getCharacterData(endLoc);
5536
5537 std::string messString;
5538 messString += "// ";
5539 messString.append(startBuf, endBuf-startBuf+1);
5540 messString += "\n";
5541
5542 // FIXME: Missing definition of
5543 // InsertText(clang::SourceLocation, char const*, unsigned int).
5544 // InsertText(startLoc, messString.c_str(), messString.size());
5545 // Tried this, but it didn't work either...
5546 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5547#endif
5548 return RewriteMessageExpr(MessExpr);
5549 }
5550
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005551 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5552 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5553 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5554 }
5555
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005556 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5557 return RewriteObjCTryStmt(StmtTry);
5558
5559 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5560 return RewriteObjCSynchronizedStmt(StmtTry);
5561
5562 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5563 return RewriteObjCThrowStmt(StmtThrow);
5564
5565 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5566 return RewriteObjCProtocolExpr(ProtocolExp);
5567
5568 if (ObjCForCollectionStmt *StmtForCollection =
5569 dyn_cast<ObjCForCollectionStmt>(S))
5570 return RewriteObjCForCollectionStmt(StmtForCollection,
5571 OrigStmtRange.getEnd());
5572 if (BreakStmt *StmtBreakStmt =
5573 dyn_cast<BreakStmt>(S))
5574 return RewriteBreakStmt(StmtBreakStmt);
5575 if (ContinueStmt *StmtContinueStmt =
5576 dyn_cast<ContinueStmt>(S))
5577 return RewriteContinueStmt(StmtContinueStmt);
5578
5579 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5580 // and cast exprs.
5581 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5582 // FIXME: What we're doing here is modifying the type-specifier that
5583 // precedes the first Decl. In the future the DeclGroup should have
5584 // a separate type-specifier that we can rewrite.
5585 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5586 // the context of an ObjCForCollectionStmt. For example:
5587 // NSArray *someArray;
5588 // for (id <FooProtocol> index in someArray) ;
5589 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5590 // and it depends on the original text locations/positions.
5591 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5592 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5593
5594 // Blocks rewrite rules.
5595 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5596 DI != DE; ++DI) {
5597 Decl *SD = *DI;
5598 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5599 if (isTopLevelBlockPointerType(ND->getType()))
5600 RewriteBlockPointerDecl(ND);
5601 else if (ND->getType()->isFunctionPointerType())
5602 CheckFunctionPointerDecl(ND->getType(), ND);
5603 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5604 if (VD->hasAttr<BlocksAttr>()) {
5605 static unsigned uniqueByrefDeclCount = 0;
5606 assert(!BlockByRefDeclNo.count(ND) &&
5607 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5608 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005609 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005610 }
5611 else
5612 RewriteTypeOfDecl(VD);
5613 }
5614 }
5615 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5616 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5617 RewriteBlockPointerDecl(TD);
5618 else if (TD->getUnderlyingType()->isFunctionPointerType())
5619 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5620 }
5621 }
5622 }
5623
5624 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5625 RewriteObjCQualifiedInterfaceTypes(CE);
5626
5627 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5628 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5629 assert(!Stmts.empty() && "Statement stack is empty");
5630 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5631 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5632 && "Statement stack mismatch");
5633 Stmts.pop_back();
5634 }
5635 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005636 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5637 ValueDecl *VD = DRE->getDecl();
5638 if (VD->hasAttr<BlocksAttr>())
5639 return RewriteBlockDeclRefExpr(DRE);
5640 if (HasLocalVariableExternalStorage(VD))
5641 return RewriteLocalVariableExternalStorage(DRE);
5642 }
5643
5644 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5645 if (CE->getCallee()->getType()->isBlockPointerType()) {
5646 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5647 ReplaceStmt(S, BlockCall);
5648 return BlockCall;
5649 }
5650 }
5651 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5652 RewriteCastExpr(CE);
5653 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005654 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5655 RewriteImplicitCastObjCExpr(ICE);
5656 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005657#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005658
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005659 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5660 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5661 ICE->getSubExpr(),
5662 SourceLocation());
5663 // Get the new text.
5664 std::string SStr;
5665 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005666 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005667 const std::string &Str = Buf.str();
5668
5669 printf("CAST = %s\n", &Str[0]);
5670 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5671 delete S;
5672 return Replacement;
5673 }
5674#endif
5675 // Return this stmt unmodified.
5676 return S;
5677}
5678
5679void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5680 for (RecordDecl::field_iterator i = RD->field_begin(),
5681 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005682 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005683 if (isTopLevelBlockPointerType(FD->getType()))
5684 RewriteBlockPointerDecl(FD);
5685 if (FD->getType()->isObjCQualifiedIdType() ||
5686 FD->getType()->isObjCQualifiedInterfaceType())
5687 RewriteObjCQualifiedInterfaceTypes(FD);
5688 }
5689}
5690
5691/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5692/// main file of the input.
5693void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5694 switch (D->getKind()) {
5695 case Decl::Function: {
5696 FunctionDecl *FD = cast<FunctionDecl>(D);
5697 if (FD->isOverloadedOperator())
5698 return;
5699
5700 // Since function prototypes don't have ParmDecl's, we check the function
5701 // prototype. This enables us to rewrite function declarations and
5702 // definitions using the same code.
5703 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5704
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005705 if (!FD->isThisDeclarationADefinition())
5706 break;
5707
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005708 // FIXME: If this should support Obj-C++, support CXXTryStmt
5709 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5710 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005711 CurrentBody = Body;
5712 Body =
5713 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5714 FD->setBody(Body);
5715 CurrentBody = 0;
5716 if (PropParentMap) {
5717 delete PropParentMap;
5718 PropParentMap = 0;
5719 }
5720 // This synthesizes and inserts the block "impl" struct, invoke function,
5721 // and any copy/dispose helper functions.
5722 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005723 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005724 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005725 }
5726 break;
5727 }
5728 case Decl::ObjCMethod: {
5729 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5730 if (CompoundStmt *Body = MD->getCompoundBody()) {
5731 CurMethodDef = MD;
5732 CurrentBody = Body;
5733 Body =
5734 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5735 MD->setBody(Body);
5736 CurrentBody = 0;
5737 if (PropParentMap) {
5738 delete PropParentMap;
5739 PropParentMap = 0;
5740 }
5741 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005742 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005743 CurMethodDef = 0;
5744 }
5745 break;
5746 }
5747 case Decl::ObjCImplementation: {
5748 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5749 ClassImplementation.push_back(CI);
5750 break;
5751 }
5752 case Decl::ObjCCategoryImpl: {
5753 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5754 CategoryImplementation.push_back(CI);
5755 break;
5756 }
5757 case Decl::Var: {
5758 VarDecl *VD = cast<VarDecl>(D);
5759 RewriteObjCQualifiedInterfaceTypes(VD);
5760 if (isTopLevelBlockPointerType(VD->getType()))
5761 RewriteBlockPointerDecl(VD);
5762 else if (VD->getType()->isFunctionPointerType()) {
5763 CheckFunctionPointerDecl(VD->getType(), VD);
5764 if (VD->getInit()) {
5765 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5766 RewriteCastExpr(CE);
5767 }
5768 }
5769 } else if (VD->getType()->isRecordType()) {
5770 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5771 if (RD->isCompleteDefinition())
5772 RewriteRecordBody(RD);
5773 }
5774 if (VD->getInit()) {
5775 GlobalVarDecl = VD;
5776 CurrentBody = VD->getInit();
5777 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5778 CurrentBody = 0;
5779 if (PropParentMap) {
5780 delete PropParentMap;
5781 PropParentMap = 0;
5782 }
5783 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5784 GlobalVarDecl = 0;
5785
5786 // This is needed for blocks.
5787 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5788 RewriteCastExpr(CE);
5789 }
5790 }
5791 break;
5792 }
5793 case Decl::TypeAlias:
5794 case Decl::Typedef: {
5795 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5796 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5797 RewriteBlockPointerDecl(TD);
5798 else if (TD->getUnderlyingType()->isFunctionPointerType())
5799 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5800 }
5801 break;
5802 }
5803 case Decl::CXXRecord:
5804 case Decl::Record: {
5805 RecordDecl *RD = cast<RecordDecl>(D);
5806 if (RD->isCompleteDefinition())
5807 RewriteRecordBody(RD);
5808 break;
5809 }
5810 default:
5811 break;
5812 }
5813 // Nothing yet.
5814}
5815
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005816/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5817/// protocol reference symbols in the for of:
5818/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5819static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5820 ObjCProtocolDecl *PDecl,
5821 std::string &Result) {
5822 // Also output .objc_protorefs$B section and its meta-data.
5823 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005824 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005825 Result += "struct _protocol_t *";
5826 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5827 Result += PDecl->getNameAsString();
5828 Result += " = &";
5829 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5830 Result += ";\n";
5831}
5832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005833void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5834 if (Diags.hasErrorOccurred())
5835 return;
5836
5837 RewriteInclude();
5838
5839 // Here's a great place to add any extra declarations that may be needed.
5840 // Write out meta data for each @protocol(<expr>).
5841 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005842 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005843 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005844 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5845 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005846
5847 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00005848
5849 if (ClassImplementation.size() || CategoryImplementation.size())
5850 RewriteImplementations();
5851
Fariborz Jahanian57317782012-02-21 23:58:41 +00005852 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5853 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5854 // Write struct declaration for the class matching its ivar declarations.
5855 // Note that for modern abi, this is postponed until the end of TU
5856 // because class extensions and the implementation might declare their own
5857 // private ivars.
5858 RewriteInterfaceDecl(CDecl);
5859 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005860
5861 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5862 // we are done.
5863 if (const RewriteBuffer *RewriteBuf =
5864 Rewrite.getRewriteBufferFor(MainFileID)) {
5865 //printf("Changed:\n");
5866 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5867 } else {
5868 llvm::errs() << "No changes\n";
5869 }
5870
5871 if (ClassImplementation.size() || CategoryImplementation.size() ||
5872 ProtocolExprDecls.size()) {
5873 // Rewrite Objective-c meta data*
5874 std::string ResultStr;
5875 RewriteMetaDataIntoBuffer(ResultStr);
5876 // Emit metadata.
5877 *OutFile << ResultStr;
5878 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005879 // Emit ImageInfo;
5880 {
5881 std::string ResultStr;
5882 WriteImageInfo(ResultStr);
5883 *OutFile << ResultStr;
5884 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005885 OutFile->flush();
5886}
5887
5888void RewriteModernObjC::Initialize(ASTContext &context) {
5889 InitializeCommon(context);
5890
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005891 Preamble += "#ifndef __OBJC2__\n";
5892 Preamble += "#define __OBJC2__\n";
5893 Preamble += "#endif\n";
5894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005895 // declaring objc_selector outside the parameter list removes a silly
5896 // scope related warning...
5897 if (IsHeader)
5898 Preamble = "#pragma once\n";
5899 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005900 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5901 Preamble += "\n\tstruct objc_object *superClass; ";
5902 // Add a constructor for creating temporary objects.
5903 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5904 Preamble += ": object(o), superClass(s) {} ";
5905 Preamble += "\n};\n";
5906
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005907 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005908 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005909 // These are currently generated.
5910 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005911 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005912 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005913 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5914 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005915 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005916 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005917 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5918 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005919 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005920
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005921 // These need be generated for performance. Currently they are not,
5922 // using API calls instead.
5923 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5924 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5925 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5926
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005927 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005928 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5929 Preamble += "typedef struct objc_object Protocol;\n";
5930 Preamble += "#define _REWRITER_typedef_Protocol\n";
5931 Preamble += "#endif\n";
5932 if (LangOpts.MicrosoftExt) {
5933 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5934 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005935 }
5936 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005937 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005938
5939 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5940 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5941 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5942 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5943 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5944
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005945 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005946 Preamble += "(const char *);\n";
5947 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5948 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00005949 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005950 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005951 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005952 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00005953 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
5954 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005955 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5956 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5957 Preamble += "struct __objcFastEnumerationState {\n\t";
5958 Preamble += "unsigned long state;\n\t";
5959 Preamble += "void **itemsPtr;\n\t";
5960 Preamble += "unsigned long *mutationsPtr;\n\t";
5961 Preamble += "unsigned long extra[5];\n};\n";
5962 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5963 Preamble += "#define __FASTENUMERATIONSTATE\n";
5964 Preamble += "#endif\n";
5965 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5966 Preamble += "struct __NSConstantStringImpl {\n";
5967 Preamble += " int *isa;\n";
5968 Preamble += " int flags;\n";
5969 Preamble += " char *str;\n";
5970 Preamble += " long length;\n";
5971 Preamble += "};\n";
5972 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5973 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5974 Preamble += "#else\n";
5975 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5976 Preamble += "#endif\n";
5977 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5978 Preamble += "#endif\n";
5979 // Blocks preamble.
5980 Preamble += "#ifndef BLOCK_IMPL\n";
5981 Preamble += "#define BLOCK_IMPL\n";
5982 Preamble += "struct __block_impl {\n";
5983 Preamble += " void *isa;\n";
5984 Preamble += " int Flags;\n";
5985 Preamble += " int Reserved;\n";
5986 Preamble += " void *FuncPtr;\n";
5987 Preamble += "};\n";
5988 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5989 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5990 Preamble += "extern \"C\" __declspec(dllexport) "
5991 "void _Block_object_assign(void *, const void *, const int);\n";
5992 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5993 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5994 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5995 Preamble += "#else\n";
5996 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5997 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5998 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5999 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6000 Preamble += "#endif\n";
6001 Preamble += "#endif\n";
6002 if (LangOpts.MicrosoftExt) {
6003 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6004 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6005 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6006 Preamble += "#define __attribute__(X)\n";
6007 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006008 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006009 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006010 Preamble += "#endif\n";
6011 Preamble += "#ifndef __block\n";
6012 Preamble += "#define __block\n";
6013 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006014 }
6015 else {
6016 Preamble += "#define __block\n";
6017 Preamble += "#define __weak\n";
6018 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006019
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006020 // Declarations required for modern objective-c array and dictionary literals.
6021 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006022 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006023 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006024 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006025 Preamble += "\tva_list marker;\n";
6026 Preamble += "\tva_start(marker, count);\n";
6027 Preamble += "\tarr = new void *[count];\n";
6028 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6029 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6030 Preamble += "\tva_end( marker );\n";
6031 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006032 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006033 Preamble += "\tdelete[] arr;\n";
6034 Preamble += " }\n";
6035 Preamble += "};\n";
6036
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006037 // Declaration required for implementation of @autoreleasepool statement.
6038 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6039 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6040 Preamble += "struct __AtAutoreleasePool {\n";
6041 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6042 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6043 Preamble += " void * atautoreleasepoolobj;\n";
6044 Preamble += "};\n";
6045
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006046 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6047 // as this avoids warning in any 64bit/32bit compilation model.
6048 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6049}
6050
6051/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6052/// ivar offset.
6053void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6054 std::string &Result) {
6055 if (ivar->isBitField()) {
6056 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6057 // place all bitfields at offset 0.
6058 Result += "0";
6059 } else {
6060 Result += "__OFFSETOFIVAR__(struct ";
6061 Result += ivar->getContainingInterface()->getNameAsString();
6062 if (LangOpts.MicrosoftExt)
6063 Result += "_IMPL";
6064 Result += ", ";
6065 Result += ivar->getNameAsString();
6066 Result += ")";
6067 }
6068}
6069
6070/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6071/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006072/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006073/// char *attributes;
6074/// }
6075
6076/// struct _prop_list_t {
6077/// uint32_t entsize; // sizeof(struct _prop_t)
6078/// uint32_t count_of_properties;
6079/// struct _prop_t prop_list[count_of_properties];
6080/// }
6081
6082/// struct _protocol_t;
6083
6084/// struct _protocol_list_t {
6085/// long protocol_count; // Note, this is 32/64 bit
6086/// struct _protocol_t * protocol_list[protocol_count];
6087/// }
6088
6089/// struct _objc_method {
6090/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006091/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006092/// char *_imp;
6093/// }
6094
6095/// struct _method_list_t {
6096/// uint32_t entsize; // sizeof(struct _objc_method)
6097/// uint32_t method_count;
6098/// struct _objc_method method_list[method_count];
6099/// }
6100
6101/// struct _protocol_t {
6102/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006103/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006104/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006105/// const struct method_list_t *instance_methods;
6106/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006107/// const struct method_list_t *optionalInstanceMethods;
6108/// const struct method_list_t *optionalClassMethods;
6109/// const struct _prop_list_t * properties;
6110/// const uint32_t size; // sizeof(struct _protocol_t)
6111/// const uint32_t flags; // = 0
6112/// const char ** extendedMethodTypes;
6113/// }
6114
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006115/// struct _ivar_t {
6116/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006117/// const char *name;
6118/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006119/// uint32_t alignment;
6120/// uint32_t size;
6121/// }
6122
6123/// struct _ivar_list_t {
6124/// uint32 entsize; // sizeof(struct _ivar_t)
6125/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006126/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006127/// }
6128
6129/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006130/// uint32_t flags;
6131/// uint32_t instanceStart;
6132/// uint32_t instanceSize;
6133/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006134/// const uint8_t *ivarLayout;
6135/// const char *name;
6136/// const struct _method_list_t *baseMethods;
6137/// const struct _protocol_list_t *baseProtocols;
6138/// const struct _ivar_list_t *ivars;
6139/// const uint8_t *weakIvarLayout;
6140/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006141/// }
6142
6143/// struct _class_t {
6144/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006145/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006146/// void *cache;
6147/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006148/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006149/// }
6150
6151/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006152/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006153/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006154/// const struct _method_list_t *instance_methods;
6155/// const struct _method_list_t *class_methods;
6156/// const struct _protocol_list_t *protocols;
6157/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006158/// }
6159
6160/// MessageRefTy - LLVM for:
6161/// struct _message_ref_t {
6162/// IMP messenger;
6163/// SEL name;
6164/// };
6165
6166/// SuperMessageRefTy - LLVM for:
6167/// struct _super_message_ref_t {
6168/// SUPER_IMP messenger;
6169/// SEL name;
6170/// };
6171
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006172static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006173 static bool meta_data_declared = false;
6174 if (meta_data_declared)
6175 return;
6176
6177 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006178 Result += "\tconst char *name;\n";
6179 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006180 Result += "};\n";
6181
6182 Result += "\nstruct _protocol_t;\n";
6183
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006184 Result += "\nstruct _objc_method {\n";
6185 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006186 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006187 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006188 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006189
6190 Result += "\nstruct _protocol_t {\n";
6191 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006192 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006193 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006194 Result += "\tconst struct method_list_t *instance_methods;\n";
6195 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006196 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6197 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6198 Result += "\tconst struct _prop_list_t * properties;\n";
6199 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6200 Result += "\tconst unsigned int flags; // = 0\n";
6201 Result += "\tconst char ** extendedMethodTypes;\n";
6202 Result += "};\n";
6203
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006204 Result += "\nstruct _ivar_t {\n";
6205 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006206 Result += "\tconst char *name;\n";
6207 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006208 Result += "\tunsigned int alignment;\n";
6209 Result += "\tunsigned int size;\n";
6210 Result += "};\n";
6211
6212 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006213 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006214 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006215 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006216 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6217 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006218 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006219 Result += "\tconst unsigned char *ivarLayout;\n";
6220 Result += "\tconst char *name;\n";
6221 Result += "\tconst struct _method_list_t *baseMethods;\n";
6222 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6223 Result += "\tconst struct _ivar_list_t *ivars;\n";
6224 Result += "\tconst unsigned char *weakIvarLayout;\n";
6225 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006226 Result += "};\n";
6227
6228 Result += "\nstruct _class_t {\n";
6229 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006230 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006231 Result += "\tvoid *cache;\n";
6232 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006233 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006234 Result += "};\n";
6235
6236 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006237 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006238 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006239 Result += "\tconst struct _method_list_t *instance_methods;\n";
6240 Result += "\tconst struct _method_list_t *class_methods;\n";
6241 Result += "\tconst struct _protocol_list_t *protocols;\n";
6242 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006243 Result += "};\n";
6244
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006245 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006246 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006247 meta_data_declared = true;
6248}
6249
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006250static void Write_protocol_list_t_TypeDecl(std::string &Result,
6251 long super_protocol_count) {
6252 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6253 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6254 Result += "\tstruct _protocol_t *super_protocols[";
6255 Result += utostr(super_protocol_count); Result += "];\n";
6256 Result += "}";
6257}
6258
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006259static void Write_method_list_t_TypeDecl(std::string &Result,
6260 unsigned int method_count) {
6261 Result += "struct /*_method_list_t*/"; Result += " {\n";
6262 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6263 Result += "\tunsigned int method_count;\n";
6264 Result += "\tstruct _objc_method method_list[";
6265 Result += utostr(method_count); Result += "];\n";
6266 Result += "}";
6267}
6268
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006269static void Write__prop_list_t_TypeDecl(std::string &Result,
6270 unsigned int property_count) {
6271 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6272 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6273 Result += "\tunsigned int count_of_properties;\n";
6274 Result += "\tstruct _prop_t prop_list[";
6275 Result += utostr(property_count); Result += "];\n";
6276 Result += "}";
6277}
6278
Fariborz Jahanianae932952012-02-10 20:47:10 +00006279static void Write__ivar_list_t_TypeDecl(std::string &Result,
6280 unsigned int ivar_count) {
6281 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6282 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6283 Result += "\tunsigned int count;\n";
6284 Result += "\tstruct _ivar_t ivar_list[";
6285 Result += utostr(ivar_count); Result += "];\n";
6286 Result += "}";
6287}
6288
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006289static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6290 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6291 StringRef VarName,
6292 StringRef ProtocolName) {
6293 if (SuperProtocols.size() > 0) {
6294 Result += "\nstatic ";
6295 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6296 Result += " "; Result += VarName;
6297 Result += ProtocolName;
6298 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6299 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6300 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6301 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6302 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6303 Result += SuperPD->getNameAsString();
6304 if (i == e-1)
6305 Result += "\n};\n";
6306 else
6307 Result += ",\n";
6308 }
6309 }
6310}
6311
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006312static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6313 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006314 ArrayRef<ObjCMethodDecl *> Methods,
6315 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006316 StringRef TopLevelDeclName,
6317 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006318 if (Methods.size() > 0) {
6319 Result += "\nstatic ";
6320 Write_method_list_t_TypeDecl(Result, Methods.size());
6321 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006322 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006323 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6324 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6325 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6326 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6327 ObjCMethodDecl *MD = Methods[i];
6328 if (i == 0)
6329 Result += "\t{{(struct objc_selector *)\"";
6330 else
6331 Result += "\t{(struct objc_selector *)\"";
6332 Result += (MD)->getSelector().getAsString(); Result += "\"";
6333 Result += ", ";
6334 std::string MethodTypeString;
6335 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6336 Result += "\""; Result += MethodTypeString; Result += "\"";
6337 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006338 if (!MethodImpl)
6339 Result += "0";
6340 else {
6341 Result += "(void *)";
6342 Result += RewriteObj.MethodInternalNames[MD];
6343 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006344 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006345 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006346 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006347 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006348 }
6349 Result += "};\n";
6350 }
6351}
6352
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006353static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006354 ASTContext *Context, std::string &Result,
6355 ArrayRef<ObjCPropertyDecl *> Properties,
6356 const Decl *Container,
6357 StringRef VarName,
6358 StringRef ProtocolName) {
6359 if (Properties.size() > 0) {
6360 Result += "\nstatic ";
6361 Write__prop_list_t_TypeDecl(Result, Properties.size());
6362 Result += " "; Result += VarName;
6363 Result += ProtocolName;
6364 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6365 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6366 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6367 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6368 ObjCPropertyDecl *PropDecl = Properties[i];
6369 if (i == 0)
6370 Result += "\t{{\"";
6371 else
6372 Result += "\t{\"";
6373 Result += PropDecl->getName(); Result += "\",";
6374 std::string PropertyTypeString, QuotePropertyTypeString;
6375 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6376 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6377 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6378 if (i == e-1)
6379 Result += "}}\n";
6380 else
6381 Result += "},\n";
6382 }
6383 Result += "};\n";
6384 }
6385}
6386
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006387// Metadata flags
6388enum MetaDataDlags {
6389 CLS = 0x0,
6390 CLS_META = 0x1,
6391 CLS_ROOT = 0x2,
6392 OBJC2_CLS_HIDDEN = 0x10,
6393 CLS_EXCEPTION = 0x20,
6394
6395 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6396 CLS_HAS_IVAR_RELEASER = 0x40,
6397 /// class was compiled with -fobjc-arr
6398 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6399};
6400
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006401static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6402 unsigned int flags,
6403 const std::string &InstanceStart,
6404 const std::string &InstanceSize,
6405 ArrayRef<ObjCMethodDecl *>baseMethods,
6406 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6407 ArrayRef<ObjCIvarDecl *>ivars,
6408 ArrayRef<ObjCPropertyDecl *>Properties,
6409 StringRef VarName,
6410 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006411 Result += "\nstatic struct _class_ro_t ";
6412 Result += VarName; Result += ClassName;
6413 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6414 Result += "\t";
6415 Result += llvm::utostr(flags); Result += ", ";
6416 Result += InstanceStart; Result += ", ";
6417 Result += InstanceSize; Result += ", \n";
6418 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006419 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6420 if (Triple.getArch() == llvm::Triple::x86_64)
6421 // uint32_t const reserved; // only when building for 64bit targets
6422 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006423 // const uint8_t * const ivarLayout;
6424 Result += "0, \n\t";
6425 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006426 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006427 if (baseMethods.size() > 0) {
6428 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006429 if (metaclass)
6430 Result += "_OBJC_$_CLASS_METHODS_";
6431 else
6432 Result += "_OBJC_$_INSTANCE_METHODS_";
6433 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006434 Result += ",\n\t";
6435 }
6436 else
6437 Result += "0, \n\t";
6438
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006439 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006440 Result += "(const struct _objc_protocol_list *)&";
6441 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6442 Result += ",\n\t";
6443 }
6444 else
6445 Result += "0, \n\t";
6446
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006447 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006448 Result += "(const struct _ivar_list_t *)&";
6449 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6450 Result += ",\n\t";
6451 }
6452 else
6453 Result += "0, \n\t";
6454
6455 // weakIvarLayout
6456 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006457 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006458 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006459 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006460 Result += ",\n";
6461 }
6462 else
6463 Result += "0, \n";
6464
6465 Result += "};\n";
6466}
6467
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006468static void Write_class_t(ASTContext *Context, std::string &Result,
6469 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006470 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6471 bool rootClass = (!CDecl->getSuperClass());
6472 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006473
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006474 if (!rootClass) {
6475 // Find the Root class
6476 RootClass = CDecl->getSuperClass();
6477 while (RootClass->getSuperClass()) {
6478 RootClass = RootClass->getSuperClass();
6479 }
6480 }
6481
6482 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006483 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006484 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006485 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006486 if (CDecl->getImplementation())
6487 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006488 else
6489 Result += "__declspec(dllimport) ";
6490
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006491 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006492 Result += CDecl->getNameAsString();
6493 Result += ";\n";
6494 }
6495 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006496 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006497 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006498 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006499 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006500 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006501 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006502 else
6503 Result += "__declspec(dllimport) ";
6504
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006505 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006506 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006507 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006508 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006509
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006510 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006511 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006512 if (RootClass->getImplementation())
6513 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006514 else
6515 Result += "__declspec(dllimport) ";
6516
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006517 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006518 Result += VarName;
6519 Result += RootClass->getNameAsString();
6520 Result += ";\n";
6521 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006522 }
6523
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006524 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6525 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006526 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6527 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006528 if (metaclass) {
6529 if (!rootClass) {
6530 Result += "0, // &"; Result += VarName;
6531 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006532 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006533 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006534 Result += CDecl->getSuperClass()->getNameAsString();
6535 Result += ",\n\t";
6536 }
6537 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006538 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006539 Result += CDecl->getNameAsString();
6540 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006541 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006542 Result += ",\n\t";
6543 }
6544 }
6545 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006546 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006547 Result += CDecl->getNameAsString();
6548 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006549 if (!rootClass) {
6550 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006551 Result += CDecl->getSuperClass()->getNameAsString();
6552 Result += ",\n\t";
6553 }
6554 else
6555 Result += "0,\n\t";
6556 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006557 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6558 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6559 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006560 Result += "&_OBJC_METACLASS_RO_$_";
6561 else
6562 Result += "&_OBJC_CLASS_RO_$_";
6563 Result += CDecl->getNameAsString();
6564 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006565
6566 // Add static function to initialize some of the meta-data fields.
6567 // avoid doing it twice.
6568 if (metaclass)
6569 return;
6570
6571 const ObjCInterfaceDecl *SuperClass =
6572 rootClass ? CDecl : CDecl->getSuperClass();
6573
6574 Result += "static void OBJC_CLASS_SETUP_$_";
6575 Result += CDecl->getNameAsString();
6576 Result += "(void ) {\n";
6577 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6578 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006579 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006580
6581 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006582 Result += ".superclass = ";
6583 if (rootClass)
6584 Result += "&OBJC_CLASS_$_";
6585 else
6586 Result += "&OBJC_METACLASS_$_";
6587
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006588 Result += SuperClass->getNameAsString(); Result += ";\n";
6589
6590 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6591 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6592
6593 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6594 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6595 Result += CDecl->getNameAsString(); Result += ";\n";
6596
6597 if (!rootClass) {
6598 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6599 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6600 Result += SuperClass->getNameAsString(); Result += ";\n";
6601 }
6602
6603 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6604 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6605 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006606}
6607
Fariborz Jahanian61186122012-02-17 18:40:41 +00006608static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6609 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006610 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006611 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006612 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6613 ArrayRef<ObjCMethodDecl *> ClassMethods,
6614 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6615 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006616 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006617 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006618 // must declare an extern class object in case this class is not implemented
6619 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006620 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006621 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006622 if (ClassDecl->getImplementation())
6623 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006624 else
6625 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006626
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006627 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006628 Result += "OBJC_CLASS_$_"; Result += ClassName;
6629 Result += ";\n";
6630
Fariborz Jahanian61186122012-02-17 18:40:41 +00006631 Result += "\nstatic struct _category_t ";
6632 Result += "_OBJC_$_CATEGORY_";
6633 Result += ClassName; Result += "_$_"; Result += CatName;
6634 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6635 Result += "{\n";
6636 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006637 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006638 Result += ",\n";
6639 if (InstanceMethods.size() > 0) {
6640 Result += "\t(const struct _method_list_t *)&";
6641 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6642 Result += ClassName; Result += "_$_"; Result += CatName;
6643 Result += ",\n";
6644 }
6645 else
6646 Result += "\t0,\n";
6647
6648 if (ClassMethods.size() > 0) {
6649 Result += "\t(const struct _method_list_t *)&";
6650 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6651 Result += ClassName; Result += "_$_"; Result += CatName;
6652 Result += ",\n";
6653 }
6654 else
6655 Result += "\t0,\n";
6656
6657 if (RefedProtocols.size() > 0) {
6658 Result += "\t(const struct _protocol_list_t *)&";
6659 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6660 Result += ClassName; Result += "_$_"; Result += CatName;
6661 Result += ",\n";
6662 }
6663 else
6664 Result += "\t0,\n";
6665
6666 if (ClassProperties.size() > 0) {
6667 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6668 Result += ClassName; Result += "_$_"; Result += CatName;
6669 Result += ",\n";
6670 }
6671 else
6672 Result += "\t0,\n";
6673
6674 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006675
6676 // Add static function to initialize the class pointer in the category structure.
6677 Result += "static void OBJC_CATEGORY_SETUP_$_";
6678 Result += ClassDecl->getNameAsString();
6679 Result += "_$_";
6680 Result += CatName;
6681 Result += "(void ) {\n";
6682 Result += "\t_OBJC_$_CATEGORY_";
6683 Result += ClassDecl->getNameAsString();
6684 Result += "_$_";
6685 Result += CatName;
6686 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6687 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006688}
6689
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006690static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6691 ASTContext *Context, std::string &Result,
6692 ArrayRef<ObjCMethodDecl *> Methods,
6693 StringRef VarName,
6694 StringRef ProtocolName) {
6695 if (Methods.size() == 0)
6696 return;
6697
6698 Result += "\nstatic const char *";
6699 Result += VarName; Result += ProtocolName;
6700 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6701 Result += "{\n";
6702 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6703 ObjCMethodDecl *MD = Methods[i];
6704 std::string MethodTypeString, QuoteMethodTypeString;
6705 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6706 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6707 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6708 if (i == e-1)
6709 Result += "\n};\n";
6710 else {
6711 Result += ",\n";
6712 }
6713 }
6714}
6715
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006716static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6717 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006718 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006719 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006720 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006721 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6722 // this is what happens:
6723 /**
6724 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6725 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6726 Class->getVisibility() == HiddenVisibility)
6727 Visibility shoud be: HiddenVisibility;
6728 else
6729 Visibility shoud be: DefaultVisibility;
6730 */
6731
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006732 Result += "\n";
6733 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6734 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006735 if (Context->getLangOpts().MicrosoftExt)
6736 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6737
6738 if (!Context->getLangOpts().MicrosoftExt ||
6739 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006740 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006741 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006742 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006743 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006744 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006745 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6746 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006747 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6748 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006749 }
6750}
6751
Fariborz Jahanianae932952012-02-10 20:47:10 +00006752static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6753 ASTContext *Context, std::string &Result,
6754 ArrayRef<ObjCIvarDecl *> Ivars,
6755 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006756 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006757 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006758 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006759
Fariborz Jahanianae932952012-02-10 20:47:10 +00006760 Result += "\nstatic ";
6761 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6762 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006763 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006764 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6765 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6766 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6767 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6768 ObjCIvarDecl *IvarDecl = Ivars[i];
6769 if (i == 0)
6770 Result += "\t{{";
6771 else
6772 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006773 Result += "(unsigned long int *)&";
6774 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006775 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006776
6777 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6778 std::string IvarTypeString, QuoteIvarTypeString;
6779 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6780 IvarDecl);
6781 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6782 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6783
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006784 // FIXME. this alignment represents the host alignment and need be changed to
6785 // represent the target alignment.
6786 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6787 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006788 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006789 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6790 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006791 if (i == e-1)
6792 Result += "}}\n";
6793 else
6794 Result += "},\n";
6795 }
6796 Result += "};\n";
6797 }
6798}
6799
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006800/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006801void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6802 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006803
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006804 // Do not synthesize the protocol more than once.
6805 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6806 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006807 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006808
6809 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6810 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006811 // Must write out all protocol definitions in current qualifier list,
6812 // and in their nested qualifiers before writing out current definition.
6813 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6814 E = PDecl->protocol_end(); I != E; ++I)
6815 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006816
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006817 // Construct method lists.
6818 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6819 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6820 for (ObjCProtocolDecl::instmeth_iterator
6821 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6822 I != E; ++I) {
6823 ObjCMethodDecl *MD = *I;
6824 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6825 OptInstanceMethods.push_back(MD);
6826 } else {
6827 InstanceMethods.push_back(MD);
6828 }
6829 }
6830
6831 for (ObjCProtocolDecl::classmeth_iterator
6832 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6833 I != E; ++I) {
6834 ObjCMethodDecl *MD = *I;
6835 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6836 OptClassMethods.push_back(MD);
6837 } else {
6838 ClassMethods.push_back(MD);
6839 }
6840 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006841 std::vector<ObjCMethodDecl *> AllMethods;
6842 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6843 AllMethods.push_back(InstanceMethods[i]);
6844 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6845 AllMethods.push_back(ClassMethods[i]);
6846 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6847 AllMethods.push_back(OptInstanceMethods[i]);
6848 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6849 AllMethods.push_back(OptClassMethods[i]);
6850
6851 Write__extendedMethodTypes_initializer(*this, Context, Result,
6852 AllMethods,
6853 "_OBJC_PROTOCOL_METHOD_TYPES_",
6854 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006855 // Protocol's super protocol list
6856 std::vector<ObjCProtocolDecl *> SuperProtocols;
6857 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6858 E = PDecl->protocol_end(); I != E; ++I)
6859 SuperProtocols.push_back(*I);
6860
6861 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6862 "_OBJC_PROTOCOL_REFS_",
6863 PDecl->getNameAsString());
6864
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006865 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006866 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006867 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006868
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006869 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006870 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006871 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006872
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006873 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006874 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006875 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006876
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006877 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006878 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006879 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006880
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006881 // Protocol's property metadata.
6882 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6883 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6884 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00006885 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006886
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006887 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006888 /* Container */0,
6889 "_OBJC_PROTOCOL_PROPERTIES_",
6890 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006891
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006892 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006893 Result += "\n";
6894 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006895 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006896 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006897 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006898 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6899 Result += "\t0,\n"; // id is; is null
6900 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006901 if (SuperProtocols.size() > 0) {
6902 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6903 Result += PDecl->getNameAsString(); Result += ",\n";
6904 }
6905 else
6906 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006907 if (InstanceMethods.size() > 0) {
6908 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6909 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006910 }
6911 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006912 Result += "\t0,\n";
6913
6914 if (ClassMethods.size() > 0) {
6915 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6916 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006917 }
6918 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006919 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006920
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006921 if (OptInstanceMethods.size() > 0) {
6922 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6923 Result += PDecl->getNameAsString(); Result += ",\n";
6924 }
6925 else
6926 Result += "\t0,\n";
6927
6928 if (OptClassMethods.size() > 0) {
6929 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6930 Result += PDecl->getNameAsString(); Result += ",\n";
6931 }
6932 else
6933 Result += "\t0,\n";
6934
6935 if (ProtocolProperties.size() > 0) {
6936 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6937 Result += PDecl->getNameAsString(); Result += ",\n";
6938 }
6939 else
6940 Result += "\t0,\n";
6941
6942 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6943 Result += "\t0,\n";
6944
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006945 if (AllMethods.size() > 0) {
6946 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6947 Result += PDecl->getNameAsString();
6948 Result += "\n};\n";
6949 }
6950 else
6951 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006952
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006953 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006954 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006955 Result += "struct _protocol_t *";
6956 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6957 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6958 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006959
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006960 // Mark this protocol as having been generated.
6961 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6962 llvm_unreachable("protocol already synthesized");
6963
6964}
6965
6966void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6967 const ObjCList<ObjCProtocolDecl> &Protocols,
6968 StringRef prefix, StringRef ClassName,
6969 std::string &Result) {
6970 if (Protocols.empty()) return;
6971
6972 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006973 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006974
6975 // Output the top lovel protocol meta-data for the class.
6976 /* struct _objc_protocol_list {
6977 struct _objc_protocol_list *next;
6978 int protocol_count;
6979 struct _objc_protocol *class_protocols[];
6980 }
6981 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006982 Result += "\n";
6983 if (LangOpts.MicrosoftExt)
6984 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6985 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006986 Result += "\tstruct _objc_protocol_list *next;\n";
6987 Result += "\tint protocol_count;\n";
6988 Result += "\tstruct _objc_protocol *class_protocols[";
6989 Result += utostr(Protocols.size());
6990 Result += "];\n} _OBJC_";
6991 Result += prefix;
6992 Result += "_PROTOCOLS_";
6993 Result += ClassName;
6994 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6995 "{\n\t0, ";
6996 Result += utostr(Protocols.size());
6997 Result += "\n";
6998
6999 Result += "\t,{&_OBJC_PROTOCOL_";
7000 Result += Protocols[0]->getNameAsString();
7001 Result += " \n";
7002
7003 for (unsigned i = 1; i != Protocols.size(); i++) {
7004 Result += "\t ,&_OBJC_PROTOCOL_";
7005 Result += Protocols[i]->getNameAsString();
7006 Result += "\n";
7007 }
7008 Result += "\t }\n};\n";
7009}
7010
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007011/// hasObjCExceptionAttribute - Return true if this class or any super
7012/// class has the __objc_exception__ attribute.
7013/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7014static bool hasObjCExceptionAttribute(ASTContext &Context,
7015 const ObjCInterfaceDecl *OID) {
7016 if (OID->hasAttr<ObjCExceptionAttr>())
7017 return true;
7018 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7019 return hasObjCExceptionAttribute(Context, Super);
7020 return false;
7021}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007022
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007023void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7024 std::string &Result) {
7025 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7026
7027 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007028 if (CDecl->isImplicitInterfaceDecl())
7029 assert(false &&
7030 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007031
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007032 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007033 SmallVector<ObjCIvarDecl *, 8> IVars;
7034
7035 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7036 IVD; IVD = IVD->getNextIvar()) {
7037 // Ignore unnamed bit-fields.
7038 if (!IVD->getDeclName())
7039 continue;
7040 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007041 }
7042
Fariborz Jahanianae932952012-02-10 20:47:10 +00007043 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007044 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007045 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007046
7047 // Build _objc_method_list for class's instance methods if needed
7048 SmallVector<ObjCMethodDecl *, 32>
7049 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7050
7051 // If any of our property implementations have associated getters or
7052 // setters, produce metadata for them as well.
7053 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7054 PropEnd = IDecl->propimpl_end();
7055 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007056 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007057 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007058 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007059 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007060 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007061 if (!PD)
7062 continue;
7063 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007064 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007065 InstanceMethods.push_back(Getter);
7066 if (PD->isReadOnly())
7067 continue;
7068 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007069 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007070 InstanceMethods.push_back(Setter);
7071 }
7072
7073 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7074 "_OBJC_$_INSTANCE_METHODS_",
7075 IDecl->getNameAsString(), true);
7076
7077 SmallVector<ObjCMethodDecl *, 32>
7078 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7079
7080 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7081 "_OBJC_$_CLASS_METHODS_",
7082 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007083
7084 // Protocols referenced in class declaration?
7085 // Protocol's super protocol list
7086 std::vector<ObjCProtocolDecl *> RefedProtocols;
7087 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7088 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7089 E = Protocols.end();
7090 I != E; ++I) {
7091 RefedProtocols.push_back(*I);
7092 // Must write out all protocol definitions in current qualifier list,
7093 // and in their nested qualifiers before writing out current definition.
7094 RewriteObjCProtocolMetaData(*I, Result);
7095 }
7096
7097 Write_protocol_list_initializer(Context, Result,
7098 RefedProtocols,
7099 "_OBJC_CLASS_PROTOCOLS_$_",
7100 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007101
7102 // Protocol's property metadata.
7103 std::vector<ObjCPropertyDecl *> ClassProperties;
7104 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7105 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007106 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007107
7108 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007109 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007110 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007111 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007112
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007113
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007114 // Data for initializing _class_ro_t metaclass meta-data
7115 uint32_t flags = CLS_META;
7116 std::string InstanceSize;
7117 std::string InstanceStart;
7118
7119
7120 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7121 if (classIsHidden)
7122 flags |= OBJC2_CLS_HIDDEN;
7123
7124 if (!CDecl->getSuperClass())
7125 // class is root
7126 flags |= CLS_ROOT;
7127 InstanceSize = "sizeof(struct _class_t)";
7128 InstanceStart = InstanceSize;
7129 Write__class_ro_t_initializer(Context, Result, flags,
7130 InstanceStart, InstanceSize,
7131 ClassMethods,
7132 0,
7133 0,
7134 0,
7135 "_OBJC_METACLASS_RO_$_",
7136 CDecl->getNameAsString());
7137
7138
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007139 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007140 flags = CLS;
7141 if (classIsHidden)
7142 flags |= OBJC2_CLS_HIDDEN;
7143
7144 if (hasObjCExceptionAttribute(*Context, CDecl))
7145 flags |= CLS_EXCEPTION;
7146
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007147 if (!CDecl->getSuperClass())
7148 // class is root
7149 flags |= CLS_ROOT;
7150
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007151 InstanceSize.clear();
7152 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007153 if (!ObjCSynthesizedStructs.count(CDecl)) {
7154 InstanceSize = "0";
7155 InstanceStart = "0";
7156 }
7157 else {
7158 InstanceSize = "sizeof(struct ";
7159 InstanceSize += CDecl->getNameAsString();
7160 InstanceSize += "_IMPL)";
7161
7162 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7163 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007164 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007165 }
7166 else
7167 InstanceStart = InstanceSize;
7168 }
7169 Write__class_ro_t_initializer(Context, Result, flags,
7170 InstanceStart, InstanceSize,
7171 InstanceMethods,
7172 RefedProtocols,
7173 IVars,
7174 ClassProperties,
7175 "_OBJC_CLASS_RO_$_",
7176 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007177
7178 Write_class_t(Context, Result,
7179 "OBJC_METACLASS_$_",
7180 CDecl, /*metaclass*/true);
7181
7182 Write_class_t(Context, Result,
7183 "OBJC_CLASS_$_",
7184 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007185
7186 if (ImplementationIsNonLazy(IDecl))
7187 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007188
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007189}
7190
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007191void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7192 int ClsDefCount = ClassImplementation.size();
7193 if (!ClsDefCount)
7194 return;
7195 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7196 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7197 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7198 for (int i = 0; i < ClsDefCount; i++) {
7199 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7200 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7201 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7202 Result += CDecl->getName(); Result += ",\n";
7203 }
7204 Result += "};\n";
7205}
7206
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007207void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7208 int ClsDefCount = ClassImplementation.size();
7209 int CatDefCount = CategoryImplementation.size();
7210
7211 // For each implemented class, write out all its meta data.
7212 for (int i = 0; i < ClsDefCount; i++)
7213 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7214
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007215 RewriteClassSetupInitHook(Result);
7216
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007217 // For each implemented category, write out all its meta data.
7218 for (int i = 0; i < CatDefCount; i++)
7219 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7220
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007221 RewriteCategorySetupInitHook(Result);
7222
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007223 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007224 if (LangOpts.MicrosoftExt)
7225 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007226 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7227 Result += llvm::utostr(ClsDefCount); Result += "]";
7228 Result +=
7229 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7230 "regular,no_dead_strip\")))= {\n";
7231 for (int i = 0; i < ClsDefCount; i++) {
7232 Result += "\t&OBJC_CLASS_$_";
7233 Result += ClassImplementation[i]->getNameAsString();
7234 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007235 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007236 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007237
7238 if (!DefinedNonLazyClasses.empty()) {
7239 if (LangOpts.MicrosoftExt)
7240 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7241 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7242 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7243 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7244 Result += ",\n";
7245 }
7246 Result += "};\n";
7247 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007248 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007249
7250 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007251 if (LangOpts.MicrosoftExt)
7252 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007253 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7254 Result += llvm::utostr(CatDefCount); Result += "]";
7255 Result +=
7256 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7257 "regular,no_dead_strip\")))= {\n";
7258 for (int i = 0; i < CatDefCount; i++) {
7259 Result += "\t&_OBJC_$_CATEGORY_";
7260 Result +=
7261 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7262 Result += "_$_";
7263 Result += CategoryImplementation[i]->getNameAsString();
7264 Result += ",\n";
7265 }
7266 Result += "};\n";
7267 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007268
7269 if (!DefinedNonLazyCategories.empty()) {
7270 if (LangOpts.MicrosoftExt)
7271 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7272 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7273 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7274 Result += "\t&_OBJC_$_CATEGORY_";
7275 Result +=
7276 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7277 Result += "_$_";
7278 Result += DefinedNonLazyCategories[i]->getNameAsString();
7279 Result += ",\n";
7280 }
7281 Result += "};\n";
7282 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007283}
7284
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007285void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7286 if (LangOpts.MicrosoftExt)
7287 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7288
7289 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7290 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007291 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007292}
7293
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007294/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7295/// implementation.
7296void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7297 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007298 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007299 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7300 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007301 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007302 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7303 CDecl = CDecl->getNextClassCategory())
7304 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7305 break;
7306
7307 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007308 FullCategoryName += "_$_";
7309 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007310
7311 // Build _objc_method_list for class's instance methods if needed
7312 SmallVector<ObjCMethodDecl *, 32>
7313 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7314
7315 // If any of our property implementations have associated getters or
7316 // setters, produce metadata for them as well.
7317 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7318 PropEnd = IDecl->propimpl_end();
7319 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007320 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007321 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007322 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007323 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007324 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007325 if (!PD)
7326 continue;
7327 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7328 InstanceMethods.push_back(Getter);
7329 if (PD->isReadOnly())
7330 continue;
7331 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7332 InstanceMethods.push_back(Setter);
7333 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007334
Fariborz Jahanian61186122012-02-17 18:40:41 +00007335 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7336 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7337 FullCategoryName, true);
7338
7339 SmallVector<ObjCMethodDecl *, 32>
7340 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7341
7342 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7343 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7344 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007345
7346 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007347 // Protocol's super protocol list
7348 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007349 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7350 E = CDecl->protocol_end();
7351
7352 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007353 RefedProtocols.push_back(*I);
7354 // Must write out all protocol definitions in current qualifier list,
7355 // and in their nested qualifiers before writing out current definition.
7356 RewriteObjCProtocolMetaData(*I, Result);
7357 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007358
Fariborz Jahanian61186122012-02-17 18:40:41 +00007359 Write_protocol_list_initializer(Context, Result,
7360 RefedProtocols,
7361 "_OBJC_CATEGORY_PROTOCOLS_$_",
7362 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007363
Fariborz Jahanian61186122012-02-17 18:40:41 +00007364 // Protocol's property metadata.
7365 std::vector<ObjCPropertyDecl *> ClassProperties;
7366 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7367 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007368 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007369
Fariborz Jahanian61186122012-02-17 18:40:41 +00007370 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007371 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007372 "_OBJC_$_PROP_LIST_",
7373 FullCategoryName);
7374
7375 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007376 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007377 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007378 InstanceMethods,
7379 ClassMethods,
7380 RefedProtocols,
7381 ClassProperties);
7382
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007383 // Determine if this category is also "non-lazy".
7384 if (ImplementationIsNonLazy(IDecl))
7385 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007386
7387}
7388
7389void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7390 int CatDefCount = CategoryImplementation.size();
7391 if (!CatDefCount)
7392 return;
7393 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7394 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7395 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7396 for (int i = 0; i < CatDefCount; i++) {
7397 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7398 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7399 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7400 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7401 Result += ClassDecl->getName();
7402 Result += "_$_";
7403 Result += CatDecl->getName();
7404 Result += ",\n";
7405 }
7406 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007407}
7408
7409// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7410/// class methods.
7411template<typename MethodIterator>
7412void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7413 MethodIterator MethodEnd,
7414 bool IsInstanceMethod,
7415 StringRef prefix,
7416 StringRef ClassName,
7417 std::string &Result) {
7418 if (MethodBegin == MethodEnd) return;
7419
7420 if (!objc_impl_method) {
7421 /* struct _objc_method {
7422 SEL _cmd;
7423 char *method_types;
7424 void *_imp;
7425 }
7426 */
7427 Result += "\nstruct _objc_method {\n";
7428 Result += "\tSEL _cmd;\n";
7429 Result += "\tchar *method_types;\n";
7430 Result += "\tvoid *_imp;\n";
7431 Result += "};\n";
7432
7433 objc_impl_method = true;
7434 }
7435
7436 // Build _objc_method_list for class's methods if needed
7437
7438 /* struct {
7439 struct _objc_method_list *next_method;
7440 int method_count;
7441 struct _objc_method method_list[];
7442 }
7443 */
7444 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007445 Result += "\n";
7446 if (LangOpts.MicrosoftExt) {
7447 if (IsInstanceMethod)
7448 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7449 else
7450 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7451 }
7452 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007453 Result += "\tstruct _objc_method_list *next_method;\n";
7454 Result += "\tint method_count;\n";
7455 Result += "\tstruct _objc_method method_list[";
7456 Result += utostr(NumMethods);
7457 Result += "];\n} _OBJC_";
7458 Result += prefix;
7459 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7460 Result += "_METHODS_";
7461 Result += ClassName;
7462 Result += " __attribute__ ((used, section (\"__OBJC, __";
7463 Result += IsInstanceMethod ? "inst" : "cls";
7464 Result += "_meth\")))= ";
7465 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7466
7467 Result += "\t,{{(SEL)\"";
7468 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7469 std::string MethodTypeString;
7470 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7471 Result += "\", \"";
7472 Result += MethodTypeString;
7473 Result += "\", (void *)";
7474 Result += MethodInternalNames[*MethodBegin];
7475 Result += "}\n";
7476 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7477 Result += "\t ,{(SEL)\"";
7478 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7479 std::string MethodTypeString;
7480 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7481 Result += "\", \"";
7482 Result += MethodTypeString;
7483 Result += "\", (void *)";
7484 Result += MethodInternalNames[*MethodBegin];
7485 Result += "}\n";
7486 }
7487 Result += "\t }\n};\n";
7488}
7489
7490Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7491 SourceRange OldRange = IV->getSourceRange();
7492 Expr *BaseExpr = IV->getBase();
7493
7494 // Rewrite the base, but without actually doing replaces.
7495 {
7496 DisableReplaceStmtScope S(*this);
7497 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7498 IV->setBase(BaseExpr);
7499 }
7500
7501 ObjCIvarDecl *D = IV->getDecl();
7502
7503 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007504
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007505 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7506 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007507 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007508 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7509 // lookup which class implements the instance variable.
7510 ObjCInterfaceDecl *clsDeclared = 0;
7511 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7512 clsDeclared);
7513 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7514
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007515 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007516 std::string IvarOffsetName;
7517 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7518
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007519 ReferencedIvars[clsDeclared].insert(D);
7520
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007521 // cast offset to "char *".
7522 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7523 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007524 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007525 BaseExpr);
7526 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7527 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7528 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007529 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7530 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007531 SourceLocation());
7532 BinaryOperator *addExpr =
7533 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7534 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007535 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007536 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007537 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7538 SourceLocation(),
7539 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007540 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007541
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007542 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007543 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007544 RD = RD->getDefinition();
7545 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007546 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007547 ObjCContainerDecl *CDecl =
7548 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7549 // ivar in class extensions requires special treatment.
7550 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7551 CDecl = CatDecl->getClassInterface();
7552 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007553 RecName += "_IMPL";
7554 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7555 SourceLocation(), SourceLocation(),
7556 &Context->Idents.get(RecName.c_str()));
7557 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7558 unsigned UnsignedIntSize =
7559 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7560 Expr *Zero = IntegerLiteral::Create(*Context,
7561 llvm::APInt(UnsignedIntSize, 0),
7562 Context->UnsignedIntTy, SourceLocation());
7563 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7564 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7565 Zero);
7566 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7567 SourceLocation(),
7568 &Context->Idents.get(D->getNameAsString()),
7569 IvarT, 0,
7570 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007571 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007572 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7573 FD->getType(), VK_LValue,
7574 OK_Ordinary);
7575 IvarT = Context->getDecltypeType(ME, ME->getType());
7576 }
7577 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007578 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007579 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007580
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007581 castExpr = NoTypeInfoCStyleCastExpr(Context,
7582 castT,
7583 CK_BitCast,
7584 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007585
7586
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007587 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007588 VK_LValue, OK_Ordinary,
7589 SourceLocation());
7590 PE = new (Context) ParenExpr(OldRange.getBegin(),
7591 OldRange.getEnd(),
7592 Exp);
7593
7594 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007595 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007596
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007597 ReplaceStmtWithRange(IV, Replacement, OldRange);
7598 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007599}