blob: 05883d43df25c5f06435b94dcbd2f3ec71d7c76c [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
14#include "clang/Rewrite/ASTConsumers.h"
15#include "clang/Rewrite/Rewriter.h"
16#include "clang/AST/AST.h"
17#include "clang/AST/ASTConsumer.h"
18#include "clang/AST/ParentMap.h"
19#include "clang/Basic/SourceManager.h"
20#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/Diagnostic.h"
22#include "clang/Lex/Lexer.h"
23#include "llvm/Support/MemoryBuffer.h"
24#include "llvm/Support/raw_ostream.h"
25#include "llvm/ADT/StringExtras.h"
26#include "llvm/ADT/SmallPtrSet.h"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/DenseSet.h"
29
30using namespace clang;
31using llvm::utostr;
32
33namespace {
34 class RewriteModernObjC : public ASTConsumer {
35 protected:
36
37 enum {
38 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
39 block, ... */
40 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
41 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
42 __block variable */
43 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
44 helpers */
45 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
46 support routines */
47 BLOCK_BYREF_CURRENT_MAX = 256
48 };
49
50 enum {
51 BLOCK_NEEDS_FREE = (1 << 24),
52 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
53 BLOCK_HAS_CXX_OBJ = (1 << 26),
54 BLOCK_IS_GC = (1 << 27),
55 BLOCK_IS_GLOBAL = (1 << 28),
56 BLOCK_HAS_DESCRIPTOR = (1 << 29)
57 };
58 static const int OBJC_ABI_VERSION = 7;
59
60 Rewriter Rewrite;
61 DiagnosticsEngine &Diags;
62 const LangOptions &LangOpts;
63 ASTContext *Context;
64 SourceManager *SM;
65 TranslationUnitDecl *TUDecl;
66 FileID MainFileID;
67 const char *MainFileStart, *MainFileEnd;
68 Stmt *CurrentBody;
69 ParentMap *PropParentMap; // created lazily.
70 std::string InFileName;
71 raw_ostream* OutFile;
72 std::string Preamble;
73
74 TypeDecl *ProtocolTypeDecl;
75 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000076 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000077 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000078 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 // ObjC string constant support.
80 unsigned NumObjCStringLiterals;
81 VarDecl *ConstantStringClassReference;
82 RecordDecl *NSStringRecord;
83
84 // ObjC foreach break/continue generation support.
85 int BcLabelCount;
86
87 unsigned TryFinallyContainsReturnDiag;
88 // Needed for super.
89 ObjCMethodDecl *CurMethodDef;
90 RecordDecl *SuperStructDecl;
91 RecordDecl *ConstantStringDecl;
92
93 FunctionDecl *MsgSendFunctionDecl;
94 FunctionDecl *MsgSendSuperFunctionDecl;
95 FunctionDecl *MsgSendStretFunctionDecl;
96 FunctionDecl *MsgSendSuperStretFunctionDecl;
97 FunctionDecl *MsgSendFpretFunctionDecl;
98 FunctionDecl *GetClassFunctionDecl;
99 FunctionDecl *GetMetaClassFunctionDecl;
100 FunctionDecl *GetSuperClassFunctionDecl;
101 FunctionDecl *SelGetUidFunctionDecl;
102 FunctionDecl *CFStringFunctionDecl;
103 FunctionDecl *SuperContructorFunctionDecl;
104 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000105
106 /* Misc. containers needed for meta-data rewrite. */
107 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
108 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
109 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
110 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000112 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000114 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
115 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
116
117 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
118 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
119
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000120 SmallVector<Stmt *, 32> Stmts;
121 SmallVector<int, 8> ObjCBcLabelNo;
122 // Remember all the @protocol(<expr>) expressions.
123 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
124
125 llvm::DenseSet<uint64_t> CopyDestroyCache;
126
127 // Block expressions.
128 SmallVector<BlockExpr *, 32> Blocks;
129 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000130 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000131
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
134 // Block related declarations.
135 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
136 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
137 SmallVector<ValueDecl *, 8> BlockByRefDecls;
138 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
139 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
140 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
141 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
142
143 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000144 llvm::DenseMap<ObjCInterfaceDecl *,
145 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
146
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000147 // This maps an original source AST to it's rewritten form. This allows
148 // us to avoid rewriting the same node twice (which is very uncommon).
149 // This is needed to support some of the exotic property rewriting.
150 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
151
152 // Needed for header files being rewritten
153 bool IsHeader;
154 bool SilenceRewriteMacroWarning;
155 bool objc_impl_method;
156
157 bool DisableReplaceStmt;
158 class DisableReplaceStmtScope {
159 RewriteModernObjC &R;
160 bool SavedValue;
161
162 public:
163 DisableReplaceStmtScope(RewriteModernObjC &R)
164 : R(R), SavedValue(R.DisableReplaceStmt) {
165 R.DisableReplaceStmt = true;
166 }
167 ~DisableReplaceStmtScope() {
168 R.DisableReplaceStmt = SavedValue;
169 }
170 };
171 void InitializeCommon(ASTContext &context);
172
173 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000174 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000175 // Top Level Driver code.
176 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
177 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
178 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
179 if (!Class->isThisDeclarationADefinition()) {
180 RewriteForwardClassDecl(D);
181 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000182 } else {
183 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000184 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000185 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 }
187 }
188
189 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
190 if (!Proto->isThisDeclarationADefinition()) {
191 RewriteForwardProtocolDecl(D);
192 break;
193 }
194 }
195
196 HandleTopLevelSingleDecl(*I);
197 }
198 return true;
199 }
200 void HandleTopLevelSingleDecl(Decl *D);
201 void HandleDeclInMainFile(Decl *D);
202 RewriteModernObjC(std::string inFile, raw_ostream *OS,
203 DiagnosticsEngine &D, const LangOptions &LOpts,
204 bool silenceMacroWarn);
205
206 ~RewriteModernObjC() {}
207
208 virtual void HandleTranslationUnit(ASTContext &C);
209
210 void ReplaceStmt(Stmt *Old, Stmt *New) {
211 Stmt *ReplacingStmt = ReplacedNodes[Old];
212
213 if (ReplacingStmt)
214 return; // We can't rewrite the same node twice.
215
216 if (DisableReplaceStmt)
217 return;
218
219 // If replacement succeeded or warning disabled return with no warning.
220 if (!Rewrite.ReplaceStmt(Old, New)) {
221 ReplacedNodes[Old] = New;
222 return;
223 }
224 if (SilenceRewriteMacroWarning)
225 return;
226 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
227 << Old->getSourceRange();
228 }
229
230 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
231 if (DisableReplaceStmt)
232 return;
233
234 // Measure the old text.
235 int Size = Rewrite.getRangeSize(SrcRange);
236 if (Size == -1) {
237 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
238 << Old->getSourceRange();
239 return;
240 }
241 // Get the new text.
242 std::string SStr;
243 llvm::raw_string_ostream S(SStr);
244 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
245 const std::string &Str = S.str();
246
247 // If replacement succeeded or warning disabled return with no warning.
248 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
249 ReplacedNodes[Old] = New;
250 return;
251 }
252 if (SilenceRewriteMacroWarning)
253 return;
254 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
255 << Old->getSourceRange();
256 }
257
258 void InsertText(SourceLocation Loc, StringRef Str,
259 bool InsertAfter = true) {
260 // If insertion succeeded or warning disabled return with no warning.
261 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
262 SilenceRewriteMacroWarning)
263 return;
264
265 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
266 }
267
268 void ReplaceText(SourceLocation Start, unsigned OrigLength,
269 StringRef Str) {
270 // If removal succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
276 }
277
278 // Syntactic Rewriting.
279 void RewriteRecordBody(RecordDecl *RD);
280 void RewriteInclude();
281 void RewriteForwardClassDecl(DeclGroupRef D);
282 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
283 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
284 const std::string &typedefString);
285 void RewriteImplementations();
286 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
287 ObjCImplementationDecl *IMD,
288 ObjCCategoryImplDecl *CID);
289 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
290 void RewriteImplementationDecl(Decl *Dcl);
291 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
292 ObjCMethodDecl *MDecl, std::string &ResultStr);
293 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
294 const FunctionType *&FPRetType);
295 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
296 ValueDecl *VD, bool def=false);
297 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
298 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
299 void RewriteForwardProtocolDecl(DeclGroupRef D);
300 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
301 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
302 void RewriteProperty(ObjCPropertyDecl *prop);
303 void RewriteFunctionDecl(FunctionDecl *FD);
304 void RewriteBlockPointerType(std::string& Str, QualType Type);
305 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000306 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
308 void RewriteTypeOfDecl(VarDecl *VD);
309 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
310
311 // Expression Rewriting.
312 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
313 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
314 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
317 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
318 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000319 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000320 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000321 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000322 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000323 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000324 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
325 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
326 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
327 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
328 SourceLocation OrigEnd);
329 Stmt *RewriteBreakStmt(BreakStmt *S);
330 Stmt *RewriteContinueStmt(ContinueStmt *S);
331 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000332 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000333 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334
335 // Block rewriting.
336 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
337
338 // Block specific rewrite rules.
339 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000340 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000341 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000342 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
343 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
344
345 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000348 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000349 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000350 bool &IsNamedDefinition);
351 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
352 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000353
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000354 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
355
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000356 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
357 std::string &Result);
358
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000359 virtual void Initialize(ASTContext &context);
360
361 // Misc. AST transformation routines. Somtimes they end up calling
362 // rewriting routines on the new ASTs.
363 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
364 Expr **args, unsigned nargs,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
369 SourceLocation StartLoc=SourceLocation(),
370 SourceLocation EndLoc=SourceLocation());
371
372 void SynthCountByEnumWithState(std::string &buf);
373 void SynthMsgSendFunctionDecl();
374 void SynthMsgSendSuperFunctionDecl();
375 void SynthMsgSendStretFunctionDecl();
376 void SynthMsgSendFpretFunctionDecl();
377 void SynthMsgSendSuperStretFunctionDecl();
378 void SynthGetClassFunctionDecl();
379 void SynthGetMetaClassFunctionDecl();
380 void SynthGetSuperClassFunctionDecl();
381 void SynthSelGetUidFunctionDecl();
382 void SynthSuperContructorFunctionDecl();
383
384 // Rewriting metadata
385 template<typename MethodIterator>
386 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
387 MethodIterator MethodEnd,
388 bool IsInstanceMethod,
389 StringRef prefix,
390 StringRef ClassName,
391 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000392 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
393 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000394 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000395 const ObjCList<ObjCProtocolDecl> &Prots,
396 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000397 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000399 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000400
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000401 void RewriteMetaDataIntoBuffer(std::string &Result);
402 void WriteImageInfo(std::string &Result);
403 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000404 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000405 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406
407 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000408 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000409 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000410 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000411
412
413 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
414 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
415 StringRef funcName, std::string Tag);
416 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
417 StringRef funcName, std::string Tag);
418 std::string SynthesizeBlockImpl(BlockExpr *CE,
419 std::string Tag, std::string Desc);
420 std::string SynthesizeBlockDescriptor(std::string DescTag,
421 std::string ImplTag,
422 int i, StringRef funcName,
423 unsigned hasCopy);
424 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
425 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
426 StringRef FunName);
427 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
428 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000429 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430
431 // Misc. helper routines.
432 QualType getProtocolType();
433 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000434 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
435 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
436 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
437
438 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
439 void CollectBlockDeclRefInfo(BlockExpr *Exp);
440 void GetBlockDeclRefExprs(Stmt *S);
441 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000442 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000443 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
444
445 // We avoid calling Type::isBlockPointerType(), since it operates on the
446 // canonical type. We only care if the top-level type is a closure pointer.
447 bool isTopLevelBlockPointerType(QualType T) {
448 return isa<BlockPointerType>(T);
449 }
450
451 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
452 /// to a function pointer type and upon success, returns true; false
453 /// otherwise.
454 bool convertBlockPointerToFunctionPointer(QualType &T) {
455 if (isTopLevelBlockPointerType(T)) {
456 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
457 T = Context->getPointerType(BPT->getPointeeType());
458 return true;
459 }
460 return false;
461 }
462
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000463 bool convertObjCTypeToCStyleType(QualType &T);
464
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000465 bool needToScanForQualifiers(QualType T);
466 QualType getSuperStructType();
467 QualType getConstantStringStructType();
468 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
469 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
470
471 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000472 if (T->isObjCQualifiedIdType()) {
473 bool isConst = T.isConstQualified();
474 T = isConst ? Context->getObjCIdType().withConst()
475 : Context->getObjCIdType();
476 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000477 else if (T->isObjCQualifiedClassType())
478 T = Context->getObjCClassType();
479 else if (T->isObjCObjectPointerType() &&
480 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
481 if (const ObjCObjectPointerType * OBJPT =
482 T->getAsObjCInterfacePointerType()) {
483 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
484 T = QualType(IFaceT, 0);
485 T = Context->getPointerType(T);
486 }
487 }
488 }
489
490 // FIXME: This predicate seems like it would be useful to add to ASTContext.
491 bool isObjCType(QualType T) {
492 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
493 return false;
494
495 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
496
497 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
498 OCT == Context->getCanonicalType(Context->getObjCClassType()))
499 return true;
500
501 if (const PointerType *PT = OCT->getAs<PointerType>()) {
502 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
503 PT->getPointeeType()->isObjCQualifiedIdType())
504 return true;
505 }
506 return false;
507 }
508 bool PointerTypeTakesAnyBlockArguments(QualType QT);
509 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
510 void GetExtentOfArgList(const char *Name, const char *&LParen,
511 const char *&RParen);
512
513 void QuoteDoublequotes(std::string &From, std::string &To) {
514 for (unsigned i = 0; i < From.length(); i++) {
515 if (From[i] == '"')
516 To += "\\\"";
517 else
518 To += From[i];
519 }
520 }
521
522 QualType getSimpleFunctionType(QualType result,
523 const QualType *args,
524 unsigned numArgs,
525 bool variadic = false) {
526 if (result == Context->getObjCInstanceType())
527 result = Context->getObjCIdType();
528 FunctionProtoType::ExtProtoInfo fpi;
529 fpi.Variadic = variadic;
530 return Context->getFunctionType(result, args, numArgs, fpi);
531 }
532
533 // Helper function: create a CStyleCastExpr with trivial type source info.
534 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
535 CastKind Kind, Expr *E) {
536 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
537 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
538 SourceLocation(), SourceLocation());
539 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000540
541 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
542 IdentifierInfo* II = &Context->Idents.get("load");
543 Selector LoadSel = Context->Selectors.getSelector(0, &II);
544 return OD->getClassMethod(LoadSel) != 0;
545 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000546 };
547
548}
549
550void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
551 NamedDecl *D) {
552 if (const FunctionProtoType *fproto
553 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
554 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
555 E = fproto->arg_type_end(); I && (I != E); ++I)
556 if (isTopLevelBlockPointerType(*I)) {
557 // All the args are checked/rewritten. Don't call twice!
558 RewriteBlockPointerDecl(D);
559 break;
560 }
561 }
562}
563
564void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
565 const PointerType *PT = funcType->getAs<PointerType>();
566 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
567 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
568}
569
570static bool IsHeaderFile(const std::string &Filename) {
571 std::string::size_type DotPos = Filename.rfind('.');
572
573 if (DotPos == std::string::npos) {
574 // no file extension
575 return false;
576 }
577
578 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
579 // C header: .h
580 // C++ header: .hh or .H;
581 return Ext == "h" || Ext == "hh" || Ext == "H";
582}
583
584RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
585 DiagnosticsEngine &D, const LangOptions &LOpts,
586 bool silenceMacroWarn)
587 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
588 SilenceRewriteMacroWarning(silenceMacroWarn) {
589 IsHeader = IsHeaderFile(inFile);
590 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
591 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000592 // FIXME. This should be an error. But if block is not called, it is OK. And it
593 // may break including some headers.
594 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
595 "rewriting block literal declared in global scope is not implemented");
596
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000597 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
598 DiagnosticsEngine::Warning,
599 "rewriter doesn't support user-specified control flow semantics "
600 "for @try/@finally (code may not execute properly)");
601}
602
603ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
604 raw_ostream* OS,
605 DiagnosticsEngine &Diags,
606 const LangOptions &LOpts,
607 bool SilenceRewriteMacroWarning) {
608 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
609}
610
611void RewriteModernObjC::InitializeCommon(ASTContext &context) {
612 Context = &context;
613 SM = &Context->getSourceManager();
614 TUDecl = Context->getTranslationUnitDecl();
615 MsgSendFunctionDecl = 0;
616 MsgSendSuperFunctionDecl = 0;
617 MsgSendStretFunctionDecl = 0;
618 MsgSendSuperStretFunctionDecl = 0;
619 MsgSendFpretFunctionDecl = 0;
620 GetClassFunctionDecl = 0;
621 GetMetaClassFunctionDecl = 0;
622 GetSuperClassFunctionDecl = 0;
623 SelGetUidFunctionDecl = 0;
624 CFStringFunctionDecl = 0;
625 ConstantStringClassReference = 0;
626 NSStringRecord = 0;
627 CurMethodDef = 0;
628 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000629 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000630 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000631 SuperStructDecl = 0;
632 ProtocolTypeDecl = 0;
633 ConstantStringDecl = 0;
634 BcLabelCount = 0;
635 SuperContructorFunctionDecl = 0;
636 NumObjCStringLiterals = 0;
637 PropParentMap = 0;
638 CurrentBody = 0;
639 DisableReplaceStmt = false;
640 objc_impl_method = false;
641
642 // Get the ID and start/end of the main file.
643 MainFileID = SM->getMainFileID();
644 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
645 MainFileStart = MainBuf->getBufferStart();
646 MainFileEnd = MainBuf->getBufferEnd();
647
David Blaikie4e4d0842012-03-11 07:00:24 +0000648 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000649}
650
651//===----------------------------------------------------------------------===//
652// Top Level Driver Code
653//===----------------------------------------------------------------------===//
654
655void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
656 if (Diags.hasErrorOccurred())
657 return;
658
659 // Two cases: either the decl could be in the main file, or it could be in a
660 // #included file. If the former, rewrite it now. If the later, check to see
661 // if we rewrote the #include/#import.
662 SourceLocation Loc = D->getLocation();
663 Loc = SM->getExpansionLoc(Loc);
664
665 // If this is for a builtin, ignore it.
666 if (Loc.isInvalid()) return;
667
668 // Look for built-in declarations that we need to refer during the rewrite.
669 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
670 RewriteFunctionDecl(FD);
671 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
672 // declared in <Foundation/NSString.h>
673 if (FVD->getName() == "_NSConstantStringClassReference") {
674 ConstantStringClassReference = FVD;
675 return;
676 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000677 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
678 RewriteCategoryDecl(CD);
679 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
680 if (PD->isThisDeclarationADefinition())
681 RewriteProtocolDecl(PD);
682 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000683 // FIXME. This will not work in all situations and leaving it out
684 // is harmless.
685 // RewriteLinkageSpec(LSD);
686
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000687 // Recurse into linkage specifications
688 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
689 DIEnd = LSD->decls_end();
690 DI != DIEnd; ) {
691 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
692 if (!IFace->isThisDeclarationADefinition()) {
693 SmallVector<Decl *, 8> DG;
694 SourceLocation StartLoc = IFace->getLocStart();
695 do {
696 if (isa<ObjCInterfaceDecl>(*DI) &&
697 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
698 StartLoc == (*DI)->getLocStart())
699 DG.push_back(*DI);
700 else
701 break;
702
703 ++DI;
704 } while (DI != DIEnd);
705 RewriteForwardClassDecl(DG);
706 continue;
707 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000708 else {
709 // Keep track of all interface declarations seen.
710 ObjCInterfacesSeen.push_back(IFace);
711 ++DI;
712 continue;
713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000714 }
715
716 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
717 if (!Proto->isThisDeclarationADefinition()) {
718 SmallVector<Decl *, 8> DG;
719 SourceLocation StartLoc = Proto->getLocStart();
720 do {
721 if (isa<ObjCProtocolDecl>(*DI) &&
722 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
723 StartLoc == (*DI)->getLocStart())
724 DG.push_back(*DI);
725 else
726 break;
727
728 ++DI;
729 } while (DI != DIEnd);
730 RewriteForwardProtocolDecl(DG);
731 continue;
732 }
733 }
734
735 HandleTopLevelSingleDecl(*DI);
736 ++DI;
737 }
738 }
739 // If we have a decl in the main file, see if we should rewrite it.
740 if (SM->isFromMainFile(Loc))
741 return HandleDeclInMainFile(D);
742}
743
744//===----------------------------------------------------------------------===//
745// Syntactic (non-AST) Rewriting Code
746//===----------------------------------------------------------------------===//
747
748void RewriteModernObjC::RewriteInclude() {
749 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
750 StringRef MainBuf = SM->getBufferData(MainFileID);
751 const char *MainBufStart = MainBuf.begin();
752 const char *MainBufEnd = MainBuf.end();
753 size_t ImportLen = strlen("import");
754
755 // Loop over the whole file, looking for includes.
756 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
757 if (*BufPtr == '#') {
758 if (++BufPtr == MainBufEnd)
759 return;
760 while (*BufPtr == ' ' || *BufPtr == '\t')
761 if (++BufPtr == MainBufEnd)
762 return;
763 if (!strncmp(BufPtr, "import", ImportLen)) {
764 // replace import with include
765 SourceLocation ImportLoc =
766 LocStart.getLocWithOffset(BufPtr-MainBufStart);
767 ReplaceText(ImportLoc, ImportLen, "include");
768 BufPtr += ImportLen;
769 }
770 }
771 }
772}
773
774static std::string getIvarAccessString(ObjCIvarDecl *OID) {
775 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
776 std::string S;
777 S = "((struct ";
778 S += ClassDecl->getIdentifier()->getName();
779 S += "_IMPL *)self)->";
780 S += OID->getName();
781 return S;
782}
783
784void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
785 ObjCImplementationDecl *IMD,
786 ObjCCategoryImplDecl *CID) {
787 static bool objcGetPropertyDefined = false;
788 static bool objcSetPropertyDefined = false;
789 SourceLocation startLoc = PID->getLocStart();
790 InsertText(startLoc, "// ");
791 const char *startBuf = SM->getCharacterData(startLoc);
792 assert((*startBuf == '@') && "bogus @synthesize location");
793 const char *semiBuf = strchr(startBuf, ';');
794 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
795 SourceLocation onePastSemiLoc =
796 startLoc.getLocWithOffset(semiBuf-startBuf+1);
797
798 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
799 return; // FIXME: is this correct?
800
801 // Generate the 'getter' function.
802 ObjCPropertyDecl *PD = PID->getPropertyDecl();
803 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
804
805 if (!OID)
806 return;
807 unsigned Attributes = PD->getPropertyAttributes();
808 if (!PD->getGetterMethodDecl()->isDefined()) {
809 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
810 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
811 ObjCPropertyDecl::OBJC_PR_copy));
812 std::string Getr;
813 if (GenGetProperty && !objcGetPropertyDefined) {
814 objcGetPropertyDefined = true;
815 // FIXME. Is this attribute correct in all cases?
816 Getr = "\nextern \"C\" __declspec(dllimport) "
817 "id objc_getProperty(id, SEL, long, bool);\n";
818 }
819 RewriteObjCMethodDecl(OID->getContainingInterface(),
820 PD->getGetterMethodDecl(), Getr);
821 Getr += "{ ";
822 // Synthesize an explicit cast to gain access to the ivar.
823 // See objc-act.c:objc_synthesize_new_getter() for details.
824 if (GenGetProperty) {
825 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
826 Getr += "typedef ";
827 const FunctionType *FPRetType = 0;
828 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
829 FPRetType);
830 Getr += " _TYPE";
831 if (FPRetType) {
832 Getr += ")"; // close the precedence "scope" for "*".
833
834 // Now, emit the argument types (if any).
835 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
836 Getr += "(";
837 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
838 if (i) Getr += ", ";
839 std::string ParamStr = FT->getArgType(i).getAsString(
840 Context->getPrintingPolicy());
841 Getr += ParamStr;
842 }
843 if (FT->isVariadic()) {
844 if (FT->getNumArgs()) Getr += ", ";
845 Getr += "...";
846 }
847 Getr += ")";
848 } else
849 Getr += "()";
850 }
851 Getr += ";\n";
852 Getr += "return (_TYPE)";
853 Getr += "objc_getProperty(self, _cmd, ";
854 RewriteIvarOffsetComputation(OID, Getr);
855 Getr += ", 1)";
856 }
857 else
858 Getr += "return " + getIvarAccessString(OID);
859 Getr += "; }";
860 InsertText(onePastSemiLoc, Getr);
861 }
862
863 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
864 return;
865
866 // Generate the 'setter' function.
867 std::string Setr;
868 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
869 ObjCPropertyDecl::OBJC_PR_copy);
870 if (GenSetProperty && !objcSetPropertyDefined) {
871 objcSetPropertyDefined = true;
872 // FIXME. Is this attribute correct in all cases?
873 Setr = "\nextern \"C\" __declspec(dllimport) "
874 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
875 }
876
877 RewriteObjCMethodDecl(OID->getContainingInterface(),
878 PD->getSetterMethodDecl(), Setr);
879 Setr += "{ ";
880 // Synthesize an explicit cast to initialize the ivar.
881 // See objc-act.c:objc_synthesize_new_setter() for details.
882 if (GenSetProperty) {
883 Setr += "objc_setProperty (self, _cmd, ";
884 RewriteIvarOffsetComputation(OID, Setr);
885 Setr += ", (id)";
886 Setr += PD->getName();
887 Setr += ", ";
888 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
889 Setr += "0, ";
890 else
891 Setr += "1, ";
892 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
893 Setr += "1)";
894 else
895 Setr += "0)";
896 }
897 else {
898 Setr += getIvarAccessString(OID) + " = ";
899 Setr += PD->getName();
900 }
901 Setr += "; }";
902 InsertText(onePastSemiLoc, Setr);
903}
904
905static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
906 std::string &typedefString) {
907 typedefString += "#ifndef _REWRITER_typedef_";
908 typedefString += ForwardDecl->getNameAsString();
909 typedefString += "\n";
910 typedefString += "#define _REWRITER_typedef_";
911 typedefString += ForwardDecl->getNameAsString();
912 typedefString += "\n";
913 typedefString += "typedef struct objc_object ";
914 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000915 // typedef struct { } _objc_exc_Classname;
916 typedefString += ";\ntypedef struct {} _objc_exc_";
917 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000918 typedefString += ";\n#endif\n";
919}
920
921void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
922 const std::string &typedefString) {
923 SourceLocation startLoc = ClassDecl->getLocStart();
924 const char *startBuf = SM->getCharacterData(startLoc);
925 const char *semiPtr = strchr(startBuf, ';');
926 // Replace the @class with typedefs corresponding to the classes.
927 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
928}
929
930void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
931 std::string typedefString;
932 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
933 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
934 if (I == D.begin()) {
935 // Translate to typedef's that forward reference structs with the same name
936 // as the class. As a convenience, we include the original declaration
937 // as a comment.
938 typedefString += "// @class ";
939 typedefString += ForwardDecl->getNameAsString();
940 typedefString += ";\n";
941 }
942 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
943 }
944 DeclGroupRef::iterator I = D.begin();
945 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
946}
947
948void RewriteModernObjC::RewriteForwardClassDecl(
949 const llvm::SmallVector<Decl*, 8> &D) {
950 std::string typedefString;
951 for (unsigned i = 0; i < D.size(); i++) {
952 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
953 if (i == 0) {
954 typedefString += "// @class ";
955 typedefString += ForwardDecl->getNameAsString();
956 typedefString += ";\n";
957 }
958 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
959 }
960 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
961}
962
963void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
964 // When method is a synthesized one, such as a getter/setter there is
965 // nothing to rewrite.
966 if (Method->isImplicit())
967 return;
968 SourceLocation LocStart = Method->getLocStart();
969 SourceLocation LocEnd = Method->getLocEnd();
970
971 if (SM->getExpansionLineNumber(LocEnd) >
972 SM->getExpansionLineNumber(LocStart)) {
973 InsertText(LocStart, "#if 0\n");
974 ReplaceText(LocEnd, 1, ";\n#endif\n");
975 } else {
976 InsertText(LocStart, "// ");
977 }
978}
979
980void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
981 SourceLocation Loc = prop->getAtLoc();
982
983 ReplaceText(Loc, 0, "// ");
984 // FIXME: handle properties that are declared across multiple lines.
985}
986
987void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
988 SourceLocation LocStart = CatDecl->getLocStart();
989
990 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000991 if (CatDecl->getIvarRBraceLoc().isValid()) {
992 ReplaceText(LocStart, 1, "/** ");
993 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
994 }
995 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000996 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000997 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000999 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1000 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001001 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001002
1003 for (ObjCCategoryDecl::instmeth_iterator
1004 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1005 I != E; ++I)
1006 RewriteMethodDeclaration(*I);
1007 for (ObjCCategoryDecl::classmeth_iterator
1008 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1009 I != E; ++I)
1010 RewriteMethodDeclaration(*I);
1011
1012 // Lastly, comment out the @end.
1013 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1014 strlen("@end"), "/* @end */");
1015}
1016
1017void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1018 SourceLocation LocStart = PDecl->getLocStart();
1019 assert(PDecl->isThisDeclarationADefinition());
1020
1021 // FIXME: handle protocol headers that are declared across multiple lines.
1022 ReplaceText(LocStart, 0, "// ");
1023
1024 for (ObjCProtocolDecl::instmeth_iterator
1025 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1026 I != E; ++I)
1027 RewriteMethodDeclaration(*I);
1028 for (ObjCProtocolDecl::classmeth_iterator
1029 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1030 I != E; ++I)
1031 RewriteMethodDeclaration(*I);
1032
1033 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1034 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001035 RewriteProperty(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001036
1037 // Lastly, comment out the @end.
1038 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1039 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1040
1041 // Must comment out @optional/@required
1042 const char *startBuf = SM->getCharacterData(LocStart);
1043 const char *endBuf = SM->getCharacterData(LocEnd);
1044 for (const char *p = startBuf; p < endBuf; p++) {
1045 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1046 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1047 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1048
1049 }
1050 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1051 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1052 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1053
1054 }
1055 }
1056}
1057
1058void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1059 SourceLocation LocStart = (*D.begin())->getLocStart();
1060 if (LocStart.isInvalid())
1061 llvm_unreachable("Invalid SourceLocation");
1062 // FIXME: handle forward protocol that are declared across multiple lines.
1063 ReplaceText(LocStart, 0, "// ");
1064}
1065
1066void
1067RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1068 SourceLocation LocStart = DG[0]->getLocStart();
1069 if (LocStart.isInvalid())
1070 llvm_unreachable("Invalid SourceLocation");
1071 // FIXME: handle forward protocol that are declared across multiple lines.
1072 ReplaceText(LocStart, 0, "// ");
1073}
1074
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001075void
1076RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1077 SourceLocation LocStart = LSD->getExternLoc();
1078 if (LocStart.isInvalid())
1079 llvm_unreachable("Invalid extern SourceLocation");
1080
1081 ReplaceText(LocStart, 0, "// ");
1082 if (!LSD->hasBraces())
1083 return;
1084 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1085 SourceLocation LocRBrace = LSD->getRBraceLoc();
1086 if (LocRBrace.isInvalid())
1087 llvm_unreachable("Invalid rbrace SourceLocation");
1088 ReplaceText(LocRBrace, 0, "// ");
1089}
1090
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001091void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1092 const FunctionType *&FPRetType) {
1093 if (T->isObjCQualifiedIdType())
1094 ResultStr += "id";
1095 else if (T->isFunctionPointerType() ||
1096 T->isBlockPointerType()) {
1097 // needs special handling, since pointer-to-functions have special
1098 // syntax (where a decaration models use).
1099 QualType retType = T;
1100 QualType PointeeTy;
1101 if (const PointerType* PT = retType->getAs<PointerType>())
1102 PointeeTy = PT->getPointeeType();
1103 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1104 PointeeTy = BPT->getPointeeType();
1105 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1106 ResultStr += FPRetType->getResultType().getAsString(
1107 Context->getPrintingPolicy());
1108 ResultStr += "(*";
1109 }
1110 } else
1111 ResultStr += T.getAsString(Context->getPrintingPolicy());
1112}
1113
1114void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1115 ObjCMethodDecl *OMD,
1116 std::string &ResultStr) {
1117 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1118 const FunctionType *FPRetType = 0;
1119 ResultStr += "\nstatic ";
1120 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1121 ResultStr += " ";
1122
1123 // Unique method name
1124 std::string NameStr;
1125
1126 if (OMD->isInstanceMethod())
1127 NameStr += "_I_";
1128 else
1129 NameStr += "_C_";
1130
1131 NameStr += IDecl->getNameAsString();
1132 NameStr += "_";
1133
1134 if (ObjCCategoryImplDecl *CID =
1135 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1136 NameStr += CID->getNameAsString();
1137 NameStr += "_";
1138 }
1139 // Append selector names, replacing ':' with '_'
1140 {
1141 std::string selString = OMD->getSelector().getAsString();
1142 int len = selString.size();
1143 for (int i = 0; i < len; i++)
1144 if (selString[i] == ':')
1145 selString[i] = '_';
1146 NameStr += selString;
1147 }
1148 // Remember this name for metadata emission
1149 MethodInternalNames[OMD] = NameStr;
1150 ResultStr += NameStr;
1151
1152 // Rewrite arguments
1153 ResultStr += "(";
1154
1155 // invisible arguments
1156 if (OMD->isInstanceMethod()) {
1157 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1158 selfTy = Context->getPointerType(selfTy);
1159 if (!LangOpts.MicrosoftExt) {
1160 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1161 ResultStr += "struct ";
1162 }
1163 // When rewriting for Microsoft, explicitly omit the structure name.
1164 ResultStr += IDecl->getNameAsString();
1165 ResultStr += " *";
1166 }
1167 else
1168 ResultStr += Context->getObjCClassType().getAsString(
1169 Context->getPrintingPolicy());
1170
1171 ResultStr += " self, ";
1172 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1173 ResultStr += " _cmd";
1174
1175 // Method arguments.
1176 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1177 E = OMD->param_end(); PI != E; ++PI) {
1178 ParmVarDecl *PDecl = *PI;
1179 ResultStr += ", ";
1180 if (PDecl->getType()->isObjCQualifiedIdType()) {
1181 ResultStr += "id ";
1182 ResultStr += PDecl->getNameAsString();
1183 } else {
1184 std::string Name = PDecl->getNameAsString();
1185 QualType QT = PDecl->getType();
1186 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001187 (void)convertBlockPointerToFunctionPointer(QT);
1188 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001189 ResultStr += Name;
1190 }
1191 }
1192 if (OMD->isVariadic())
1193 ResultStr += ", ...";
1194 ResultStr += ") ";
1195
1196 if (FPRetType) {
1197 ResultStr += ")"; // close the precedence "scope" for "*".
1198
1199 // Now, emit the argument types (if any).
1200 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1201 ResultStr += "(";
1202 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1203 if (i) ResultStr += ", ";
1204 std::string ParamStr = FT->getArgType(i).getAsString(
1205 Context->getPrintingPolicy());
1206 ResultStr += ParamStr;
1207 }
1208 if (FT->isVariadic()) {
1209 if (FT->getNumArgs()) ResultStr += ", ";
1210 ResultStr += "...";
1211 }
1212 ResultStr += ")";
1213 } else {
1214 ResultStr += "()";
1215 }
1216 }
1217}
1218void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1219 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1220 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1221
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001222 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001223 if (IMD->getIvarRBraceLoc().isValid()) {
1224 ReplaceText(IMD->getLocStart(), 1, "/** ");
1225 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001226 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001227 else {
1228 InsertText(IMD->getLocStart(), "// ");
1229 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001230 }
1231 else
1232 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001233
1234 for (ObjCCategoryImplDecl::instmeth_iterator
1235 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1236 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1237 I != E; ++I) {
1238 std::string ResultStr;
1239 ObjCMethodDecl *OMD = *I;
1240 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1241 SourceLocation LocStart = OMD->getLocStart();
1242 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1243
1244 const char *startBuf = SM->getCharacterData(LocStart);
1245 const char *endBuf = SM->getCharacterData(LocEnd);
1246 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1247 }
1248
1249 for (ObjCCategoryImplDecl::classmeth_iterator
1250 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1251 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1252 I != E; ++I) {
1253 std::string ResultStr;
1254 ObjCMethodDecl *OMD = *I;
1255 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1256 SourceLocation LocStart = OMD->getLocStart();
1257 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1258
1259 const char *startBuf = SM->getCharacterData(LocStart);
1260 const char *endBuf = SM->getCharacterData(LocEnd);
1261 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1262 }
1263 for (ObjCCategoryImplDecl::propimpl_iterator
1264 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1265 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1266 I != E; ++I) {
David Blaikie262bc182012-04-30 02:36:29 +00001267 RewritePropertyImplDecl(&*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001268 }
1269
1270 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1271}
1272
1273void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001274 // Do not synthesize more than once.
1275 if (ObjCSynthesizedStructs.count(ClassDecl))
1276 return;
1277 // Make sure super class's are written before current class is written.
1278 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1279 while (SuperClass) {
1280 RewriteInterfaceDecl(SuperClass);
1281 SuperClass = SuperClass->getSuperClass();
1282 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001283 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001284 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001285 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001286 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001287 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1288
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001289 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001290 // Mark this typedef as having been written into its c++ equivalent.
1291 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001292
1293 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001294 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00001295 RewriteProperty(&*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001296 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001297 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001298 I != E; ++I)
1299 RewriteMethodDeclaration(*I);
1300 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001301 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001302 I != E; ++I)
1303 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001304
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001305 // Lastly, comment out the @end.
1306 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1307 "/* @end */");
1308 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001309}
1310
1311Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1312 SourceRange OldRange = PseudoOp->getSourceRange();
1313
1314 // We just magically know some things about the structure of this
1315 // expression.
1316 ObjCMessageExpr *OldMsg =
1317 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1318 PseudoOp->getNumSemanticExprs() - 1));
1319
1320 // Because the rewriter doesn't allow us to rewrite rewritten code,
1321 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001322 Expr *Base;
1323 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001324 {
1325 DisableReplaceStmtScope S(*this);
1326
1327 // Rebuild the base expression if we have one.
1328 Base = 0;
1329 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1330 Base = OldMsg->getInstanceReceiver();
1331 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1332 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1333 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001334
1335 unsigned numArgs = OldMsg->getNumArgs();
1336 for (unsigned i = 0; i < numArgs; i++) {
1337 Expr *Arg = OldMsg->getArg(i);
1338 if (isa<OpaqueValueExpr>(Arg))
1339 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1340 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1341 Args.push_back(Arg);
1342 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001343 }
1344
1345 // TODO: avoid this copy.
1346 SmallVector<SourceLocation, 1> SelLocs;
1347 OldMsg->getSelectorLocs(SelLocs);
1348
1349 ObjCMessageExpr *NewMsg = 0;
1350 switch (OldMsg->getReceiverKind()) {
1351 case ObjCMessageExpr::Class:
1352 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1353 OldMsg->getValueKind(),
1354 OldMsg->getLeftLoc(),
1355 OldMsg->getClassReceiverTypeInfo(),
1356 OldMsg->getSelector(),
1357 SelLocs,
1358 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001359 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001360 OldMsg->getRightLoc(),
1361 OldMsg->isImplicit());
1362 break;
1363
1364 case ObjCMessageExpr::Instance:
1365 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1366 OldMsg->getValueKind(),
1367 OldMsg->getLeftLoc(),
1368 Base,
1369 OldMsg->getSelector(),
1370 SelLocs,
1371 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001372 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001373 OldMsg->getRightLoc(),
1374 OldMsg->isImplicit());
1375 break;
1376
1377 case ObjCMessageExpr::SuperClass:
1378 case ObjCMessageExpr::SuperInstance:
1379 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1380 OldMsg->getValueKind(),
1381 OldMsg->getLeftLoc(),
1382 OldMsg->getSuperLoc(),
1383 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1384 OldMsg->getSuperType(),
1385 OldMsg->getSelector(),
1386 SelLocs,
1387 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001388 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001389 OldMsg->getRightLoc(),
1390 OldMsg->isImplicit());
1391 break;
1392 }
1393
1394 Stmt *Replacement = SynthMessageExpr(NewMsg);
1395 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1396 return Replacement;
1397}
1398
1399Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1400 SourceRange OldRange = PseudoOp->getSourceRange();
1401
1402 // We just magically know some things about the structure of this
1403 // expression.
1404 ObjCMessageExpr *OldMsg =
1405 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1406
1407 // Because the rewriter doesn't allow us to rewrite rewritten code,
1408 // we need to suppress rewriting the sub-statements.
1409 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001410 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001411 {
1412 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001413 // Rebuild the base expression if we have one.
1414 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1415 Base = OldMsg->getInstanceReceiver();
1416 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1417 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1418 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001419 unsigned numArgs = OldMsg->getNumArgs();
1420 for (unsigned i = 0; i < numArgs; i++) {
1421 Expr *Arg = OldMsg->getArg(i);
1422 if (isa<OpaqueValueExpr>(Arg))
1423 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1424 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1425 Args.push_back(Arg);
1426 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001427 }
1428
1429 // Intentionally empty.
1430 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001431
1432 ObjCMessageExpr *NewMsg = 0;
1433 switch (OldMsg->getReceiverKind()) {
1434 case ObjCMessageExpr::Class:
1435 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1436 OldMsg->getValueKind(),
1437 OldMsg->getLeftLoc(),
1438 OldMsg->getClassReceiverTypeInfo(),
1439 OldMsg->getSelector(),
1440 SelLocs,
1441 OldMsg->getMethodDecl(),
1442 Args,
1443 OldMsg->getRightLoc(),
1444 OldMsg->isImplicit());
1445 break;
1446
1447 case ObjCMessageExpr::Instance:
1448 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1449 OldMsg->getValueKind(),
1450 OldMsg->getLeftLoc(),
1451 Base,
1452 OldMsg->getSelector(),
1453 SelLocs,
1454 OldMsg->getMethodDecl(),
1455 Args,
1456 OldMsg->getRightLoc(),
1457 OldMsg->isImplicit());
1458 break;
1459
1460 case ObjCMessageExpr::SuperClass:
1461 case ObjCMessageExpr::SuperInstance:
1462 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1463 OldMsg->getValueKind(),
1464 OldMsg->getLeftLoc(),
1465 OldMsg->getSuperLoc(),
1466 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1467 OldMsg->getSuperType(),
1468 OldMsg->getSelector(),
1469 SelLocs,
1470 OldMsg->getMethodDecl(),
1471 Args,
1472 OldMsg->getRightLoc(),
1473 OldMsg->isImplicit());
1474 break;
1475 }
1476
1477 Stmt *Replacement = SynthMessageExpr(NewMsg);
1478 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1479 return Replacement;
1480}
1481
1482/// SynthCountByEnumWithState - To print:
1483/// ((unsigned int (*)
1484/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1485/// (void *)objc_msgSend)((id)l_collection,
1486/// sel_registerName(
1487/// "countByEnumeratingWithState:objects:count:"),
1488/// &enumState,
1489/// (id *)__rw_items, (unsigned int)16)
1490///
1491void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1492 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1493 "id *, unsigned int))(void *)objc_msgSend)";
1494 buf += "\n\t\t";
1495 buf += "((id)l_collection,\n\t\t";
1496 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1497 buf += "\n\t\t";
1498 buf += "&enumState, "
1499 "(id *)__rw_items, (unsigned int)16)";
1500}
1501
1502/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1503/// statement to exit to its outer synthesized loop.
1504///
1505Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1506 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1507 return S;
1508 // replace break with goto __break_label
1509 std::string buf;
1510
1511 SourceLocation startLoc = S->getLocStart();
1512 buf = "goto __break_label_";
1513 buf += utostr(ObjCBcLabelNo.back());
1514 ReplaceText(startLoc, strlen("break"), buf);
1515
1516 return 0;
1517}
1518
1519/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1520/// statement to continue with its inner synthesized loop.
1521///
1522Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1523 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1524 return S;
1525 // replace continue with goto __continue_label
1526 std::string buf;
1527
1528 SourceLocation startLoc = S->getLocStart();
1529 buf = "goto __continue_label_";
1530 buf += utostr(ObjCBcLabelNo.back());
1531 ReplaceText(startLoc, strlen("continue"), buf);
1532
1533 return 0;
1534}
1535
1536/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1537/// It rewrites:
1538/// for ( type elem in collection) { stmts; }
1539
1540/// Into:
1541/// {
1542/// type elem;
1543/// struct __objcFastEnumerationState enumState = { 0 };
1544/// id __rw_items[16];
1545/// id l_collection = (id)collection;
1546/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1547/// objects:__rw_items count:16];
1548/// if (limit) {
1549/// unsigned long startMutations = *enumState.mutationsPtr;
1550/// do {
1551/// unsigned long counter = 0;
1552/// do {
1553/// if (startMutations != *enumState.mutationsPtr)
1554/// objc_enumerationMutation(l_collection);
1555/// elem = (type)enumState.itemsPtr[counter++];
1556/// stmts;
1557/// __continue_label: ;
1558/// } while (counter < limit);
1559/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1560/// objects:__rw_items count:16]);
1561/// elem = nil;
1562/// __break_label: ;
1563/// }
1564/// else
1565/// elem = nil;
1566/// }
1567///
1568Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1569 SourceLocation OrigEnd) {
1570 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1571 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1572 "ObjCForCollectionStmt Statement stack mismatch");
1573 assert(!ObjCBcLabelNo.empty() &&
1574 "ObjCForCollectionStmt - Label No stack empty");
1575
1576 SourceLocation startLoc = S->getLocStart();
1577 const char *startBuf = SM->getCharacterData(startLoc);
1578 StringRef elementName;
1579 std::string elementTypeAsString;
1580 std::string buf;
1581 buf = "\n{\n\t";
1582 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1583 // type elem;
1584 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1585 QualType ElementType = cast<ValueDecl>(D)->getType();
1586 if (ElementType->isObjCQualifiedIdType() ||
1587 ElementType->isObjCQualifiedInterfaceType())
1588 // Simply use 'id' for all qualified types.
1589 elementTypeAsString = "id";
1590 else
1591 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1592 buf += elementTypeAsString;
1593 buf += " ";
1594 elementName = D->getName();
1595 buf += elementName;
1596 buf += ";\n\t";
1597 }
1598 else {
1599 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1600 elementName = DR->getDecl()->getName();
1601 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1602 if (VD->getType()->isObjCQualifiedIdType() ||
1603 VD->getType()->isObjCQualifiedInterfaceType())
1604 // Simply use 'id' for all qualified types.
1605 elementTypeAsString = "id";
1606 else
1607 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1608 }
1609
1610 // struct __objcFastEnumerationState enumState = { 0 };
1611 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1612 // id __rw_items[16];
1613 buf += "id __rw_items[16];\n\t";
1614 // id l_collection = (id)
1615 buf += "id l_collection = (id)";
1616 // Find start location of 'collection' the hard way!
1617 const char *startCollectionBuf = startBuf;
1618 startCollectionBuf += 3; // skip 'for'
1619 startCollectionBuf = strchr(startCollectionBuf, '(');
1620 startCollectionBuf++; // skip '('
1621 // find 'in' and skip it.
1622 while (*startCollectionBuf != ' ' ||
1623 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1624 (*(startCollectionBuf+3) != ' ' &&
1625 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1626 startCollectionBuf++;
1627 startCollectionBuf += 3;
1628
1629 // Replace: "for (type element in" with string constructed thus far.
1630 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1631 // Replace ')' in for '(' type elem in collection ')' with ';'
1632 SourceLocation rightParenLoc = S->getRParenLoc();
1633 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1634 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1635 buf = ";\n\t";
1636
1637 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1638 // objects:__rw_items count:16];
1639 // which is synthesized into:
1640 // unsigned int limit =
1641 // ((unsigned int (*)
1642 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1643 // (void *)objc_msgSend)((id)l_collection,
1644 // sel_registerName(
1645 // "countByEnumeratingWithState:objects:count:"),
1646 // (struct __objcFastEnumerationState *)&state,
1647 // (id *)__rw_items, (unsigned int)16);
1648 buf += "unsigned long limit =\n\t\t";
1649 SynthCountByEnumWithState(buf);
1650 buf += ";\n\t";
1651 /// if (limit) {
1652 /// unsigned long startMutations = *enumState.mutationsPtr;
1653 /// do {
1654 /// unsigned long counter = 0;
1655 /// do {
1656 /// if (startMutations != *enumState.mutationsPtr)
1657 /// objc_enumerationMutation(l_collection);
1658 /// elem = (type)enumState.itemsPtr[counter++];
1659 buf += "if (limit) {\n\t";
1660 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1661 buf += "do {\n\t\t";
1662 buf += "unsigned long counter = 0;\n\t\t";
1663 buf += "do {\n\t\t\t";
1664 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1665 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1666 buf += elementName;
1667 buf += " = (";
1668 buf += elementTypeAsString;
1669 buf += ")enumState.itemsPtr[counter++];";
1670 // Replace ')' in for '(' type elem in collection ')' with all of these.
1671 ReplaceText(lparenLoc, 1, buf);
1672
1673 /// __continue_label: ;
1674 /// } while (counter < limit);
1675 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1676 /// objects:__rw_items count:16]);
1677 /// elem = nil;
1678 /// __break_label: ;
1679 /// }
1680 /// else
1681 /// elem = nil;
1682 /// }
1683 ///
1684 buf = ";\n\t";
1685 buf += "__continue_label_";
1686 buf += utostr(ObjCBcLabelNo.back());
1687 buf += ": ;";
1688 buf += "\n\t\t";
1689 buf += "} while (counter < limit);\n\t";
1690 buf += "} while (limit = ";
1691 SynthCountByEnumWithState(buf);
1692 buf += ");\n\t";
1693 buf += elementName;
1694 buf += " = ((";
1695 buf += elementTypeAsString;
1696 buf += ")0);\n\t";
1697 buf += "__break_label_";
1698 buf += utostr(ObjCBcLabelNo.back());
1699 buf += ": ;\n\t";
1700 buf += "}\n\t";
1701 buf += "else\n\t\t";
1702 buf += elementName;
1703 buf += " = ((";
1704 buf += elementTypeAsString;
1705 buf += ")0);\n\t";
1706 buf += "}\n";
1707
1708 // Insert all these *after* the statement body.
1709 // FIXME: If this should support Obj-C++, support CXXTryStmt
1710 if (isa<CompoundStmt>(S->getBody())) {
1711 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1712 InsertText(endBodyLoc, buf);
1713 } else {
1714 /* Need to treat single statements specially. For example:
1715 *
1716 * for (A *a in b) if (stuff()) break;
1717 * for (A *a in b) xxxyy;
1718 *
1719 * The following code simply scans ahead to the semi to find the actual end.
1720 */
1721 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1722 const char *semiBuf = strchr(stmtBuf, ';');
1723 assert(semiBuf && "Can't find ';'");
1724 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1725 InsertText(endBodyLoc, buf);
1726 }
1727 Stmts.pop_back();
1728 ObjCBcLabelNo.pop_back();
1729 return 0;
1730}
1731
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001732static void Write_RethrowObject(std::string &buf) {
1733 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1734 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1735 buf += "\tid rethrow;\n";
1736 buf += "\t} _fin_force_rethow(_rethrow);";
1737}
1738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001739/// RewriteObjCSynchronizedStmt -
1740/// This routine rewrites @synchronized(expr) stmt;
1741/// into:
1742/// objc_sync_enter(expr);
1743/// @try stmt @finally { objc_sync_exit(expr); }
1744///
1745Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1746 // Get the start location and compute the semi location.
1747 SourceLocation startLoc = S->getLocStart();
1748 const char *startBuf = SM->getCharacterData(startLoc);
1749
1750 assert((*startBuf == '@') && "bogus @synchronized location");
1751
1752 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001753 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001754
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001755 const char *lparenBuf = startBuf;
1756 while (*lparenBuf != '(') lparenBuf++;
1757 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001758
1759 buf = "; objc_sync_enter(_sync_obj);\n";
1760 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1761 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1762 buf += "\n\tid sync_exit;";
1763 buf += "\n\t} _sync_exit(_sync_obj);\n";
1764
1765 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1766 // the sync expression is typically a message expression that's already
1767 // been rewritten! (which implies the SourceLocation's are invalid).
1768 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1769 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1770 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1771 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1772
1773 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1774 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1775 assert (*LBraceLocBuf == '{');
1776 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001777
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001778 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001779 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1780 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001781
1782 buf = "} catch (id e) {_rethrow = e;}\n";
1783 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001784 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001785 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001786
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001787 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001788
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001789 return 0;
1790}
1791
1792void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1793{
1794 // Perform a bottom up traversal of all children.
1795 for (Stmt::child_range CI = S->children(); CI; ++CI)
1796 if (*CI)
1797 WarnAboutReturnGotoStmts(*CI);
1798
1799 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1800 Diags.Report(Context->getFullLoc(S->getLocStart()),
1801 TryFinallyContainsReturnDiag);
1802 }
1803 return;
1804}
1805
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001806Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001807 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001808 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001809 std::string buf;
1810
1811 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001812 if (noCatch)
1813 buf = "{ id volatile _rethrow = 0;\n";
1814 else {
1815 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1816 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001817 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001818 // Get the start location and compute the semi location.
1819 SourceLocation startLoc = S->getLocStart();
1820 const char *startBuf = SM->getCharacterData(startLoc);
1821
1822 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001823 if (finalStmt)
1824 ReplaceText(startLoc, 1, buf);
1825 else
1826 // @try -> try
1827 ReplaceText(startLoc, 1, "");
1828
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001829 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1830 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001831 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001833 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001834 bool AtRemoved = false;
1835 if (catchDecl) {
1836 QualType t = catchDecl->getType();
1837 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1838 // Should be a pointer to a class.
1839 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1840 if (IDecl) {
1841 std::string Result;
1842 startBuf = SM->getCharacterData(startLoc);
1843 assert((*startBuf == '@') && "bogus @catch location");
1844 SourceLocation rParenLoc = Catch->getRParenLoc();
1845 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1846
1847 // _objc_exc_Foo *_e as argument to catch.
1848 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1849 Result += " *_"; Result += catchDecl->getNameAsString();
1850 Result += ")";
1851 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1852 // Foo *e = (Foo *)_e;
1853 Result.clear();
1854 Result = "{ ";
1855 Result += IDecl->getNameAsString();
1856 Result += " *"; Result += catchDecl->getNameAsString();
1857 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1858 Result += "_"; Result += catchDecl->getNameAsString();
1859
1860 Result += "; ";
1861 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1862 ReplaceText(lBraceLoc, 1, Result);
1863 AtRemoved = true;
1864 }
1865 }
1866 }
1867 if (!AtRemoved)
1868 // @catch -> catch
1869 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001870
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001871 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001872 if (finalStmt) {
1873 buf.clear();
1874 if (noCatch)
1875 buf = "catch (id e) {_rethrow = e;}\n";
1876 else
1877 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1878
1879 SourceLocation startFinalLoc = finalStmt->getLocStart();
1880 ReplaceText(startFinalLoc, 8, buf);
1881 Stmt *body = finalStmt->getFinallyBody();
1882 SourceLocation startFinalBodyLoc = body->getLocStart();
1883 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001884 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001885 ReplaceText(startFinalBodyLoc, 1, buf);
1886
1887 SourceLocation endFinalBodyLoc = body->getLocEnd();
1888 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001889 // Now check for any return/continue/go statements within the @try.
1890 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001891 }
1892
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001893 return 0;
1894}
1895
1896// This can't be done with ReplaceStmt(S, ThrowExpr), since
1897// the throw expression is typically a message expression that's already
1898// been rewritten! (which implies the SourceLocation's are invalid).
1899Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1900 // Get the start location and compute the semi location.
1901 SourceLocation startLoc = S->getLocStart();
1902 const char *startBuf = SM->getCharacterData(startLoc);
1903
1904 assert((*startBuf == '@') && "bogus @throw location");
1905
1906 std::string buf;
1907 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1908 if (S->getThrowExpr())
1909 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001910 else
1911 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001912
1913 // handle "@ throw" correctly.
1914 const char *wBuf = strchr(startBuf, 'w');
1915 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1916 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1917
1918 const char *semiBuf = strchr(startBuf, ';');
1919 assert((*semiBuf == ';') && "@throw: can't find ';'");
1920 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001921 if (S->getThrowExpr())
1922 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001923 return 0;
1924}
1925
1926Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1927 // Create a new string expression.
1928 QualType StrType = Context->getPointerType(Context->CharTy);
1929 std::string StrEncoding;
1930 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1931 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1932 StringLiteral::Ascii, false,
1933 StrType, SourceLocation());
1934 ReplaceStmt(Exp, Replacement);
1935
1936 // Replace this subexpr in the parent.
1937 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1938 return Replacement;
1939}
1940
1941Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1942 if (!SelGetUidFunctionDecl)
1943 SynthSelGetUidFunctionDecl();
1944 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1945 // Create a call to sel_registerName("selName").
1946 SmallVector<Expr*, 8> SelExprs;
1947 QualType argType = Context->getPointerType(Context->CharTy);
1948 SelExprs.push_back(StringLiteral::Create(*Context,
1949 Exp->getSelector().getAsString(),
1950 StringLiteral::Ascii, false,
1951 argType, SourceLocation()));
1952 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1953 &SelExprs[0], SelExprs.size());
1954 ReplaceStmt(Exp, SelExp);
1955 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1956 return SelExp;
1957}
1958
1959CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1960 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1961 SourceLocation EndLoc) {
1962 // Get the type, we will need to reference it in a couple spots.
1963 QualType msgSendType = FD->getType();
1964
1965 // Create a reference to the objc_msgSend() declaration.
1966 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001967 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001968
1969 // Now, we cast the reference to a pointer to the objc_msgSend type.
1970 QualType pToFunc = Context->getPointerType(msgSendType);
1971 ImplicitCastExpr *ICE =
1972 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1973 DRE, 0, VK_RValue);
1974
1975 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1976
1977 CallExpr *Exp =
1978 new (Context) CallExpr(*Context, ICE, args, nargs,
1979 FT->getCallResultType(*Context),
1980 VK_RValue, EndLoc);
1981 return Exp;
1982}
1983
1984static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1985 const char *&startRef, const char *&endRef) {
1986 while (startBuf < endBuf) {
1987 if (*startBuf == '<')
1988 startRef = startBuf; // mark the start.
1989 if (*startBuf == '>') {
1990 if (startRef && *startRef == '<') {
1991 endRef = startBuf; // mark the end.
1992 return true;
1993 }
1994 return false;
1995 }
1996 startBuf++;
1997 }
1998 return false;
1999}
2000
2001static void scanToNextArgument(const char *&argRef) {
2002 int angle = 0;
2003 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2004 if (*argRef == '<')
2005 angle++;
2006 else if (*argRef == '>')
2007 angle--;
2008 argRef++;
2009 }
2010 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2011}
2012
2013bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2014 if (T->isObjCQualifiedIdType())
2015 return true;
2016 if (const PointerType *PT = T->getAs<PointerType>()) {
2017 if (PT->getPointeeType()->isObjCQualifiedIdType())
2018 return true;
2019 }
2020 if (T->isObjCObjectPointerType()) {
2021 T = T->getPointeeType();
2022 return T->isObjCQualifiedInterfaceType();
2023 }
2024 if (T->isArrayType()) {
2025 QualType ElemTy = Context->getBaseElementType(T);
2026 return needToScanForQualifiers(ElemTy);
2027 }
2028 return false;
2029}
2030
2031void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2032 QualType Type = E->getType();
2033 if (needToScanForQualifiers(Type)) {
2034 SourceLocation Loc, EndLoc;
2035
2036 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2037 Loc = ECE->getLParenLoc();
2038 EndLoc = ECE->getRParenLoc();
2039 } else {
2040 Loc = E->getLocStart();
2041 EndLoc = E->getLocEnd();
2042 }
2043 // This will defend against trying to rewrite synthesized expressions.
2044 if (Loc.isInvalid() || EndLoc.isInvalid())
2045 return;
2046
2047 const char *startBuf = SM->getCharacterData(Loc);
2048 const char *endBuf = SM->getCharacterData(EndLoc);
2049 const char *startRef = 0, *endRef = 0;
2050 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2051 // Get the locations of the startRef, endRef.
2052 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2053 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2054 // Comment out the protocol references.
2055 InsertText(LessLoc, "/*");
2056 InsertText(GreaterLoc, "*/");
2057 }
2058 }
2059}
2060
2061void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2062 SourceLocation Loc;
2063 QualType Type;
2064 const FunctionProtoType *proto = 0;
2065 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2066 Loc = VD->getLocation();
2067 Type = VD->getType();
2068 }
2069 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2070 Loc = FD->getLocation();
2071 // Check for ObjC 'id' and class types that have been adorned with protocol
2072 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2073 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2074 assert(funcType && "missing function type");
2075 proto = dyn_cast<FunctionProtoType>(funcType);
2076 if (!proto)
2077 return;
2078 Type = proto->getResultType();
2079 }
2080 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2081 Loc = FD->getLocation();
2082 Type = FD->getType();
2083 }
2084 else
2085 return;
2086
2087 if (needToScanForQualifiers(Type)) {
2088 // Since types are unique, we need to scan the buffer.
2089
2090 const char *endBuf = SM->getCharacterData(Loc);
2091 const char *startBuf = endBuf;
2092 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2093 startBuf--; // scan backward (from the decl location) for return type.
2094 const char *startRef = 0, *endRef = 0;
2095 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2096 // Get the locations of the startRef, endRef.
2097 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2098 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2099 // Comment out the protocol references.
2100 InsertText(LessLoc, "/*");
2101 InsertText(GreaterLoc, "*/");
2102 }
2103 }
2104 if (!proto)
2105 return; // most likely, was a variable
2106 // Now check arguments.
2107 const char *startBuf = SM->getCharacterData(Loc);
2108 const char *startFuncBuf = startBuf;
2109 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2110 if (needToScanForQualifiers(proto->getArgType(i))) {
2111 // Since types are unique, we need to scan the buffer.
2112
2113 const char *endBuf = startBuf;
2114 // scan forward (from the decl location) for argument types.
2115 scanToNextArgument(endBuf);
2116 const char *startRef = 0, *endRef = 0;
2117 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2118 // Get the locations of the startRef, endRef.
2119 SourceLocation LessLoc =
2120 Loc.getLocWithOffset(startRef-startFuncBuf);
2121 SourceLocation GreaterLoc =
2122 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2123 // Comment out the protocol references.
2124 InsertText(LessLoc, "/*");
2125 InsertText(GreaterLoc, "*/");
2126 }
2127 startBuf = ++endBuf;
2128 }
2129 else {
2130 // If the function name is derived from a macro expansion, then the
2131 // argument buffer will not follow the name. Need to speak with Chris.
2132 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2133 startBuf++; // scan forward (from the decl location) for argument types.
2134 startBuf++;
2135 }
2136 }
2137}
2138
2139void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2140 QualType QT = ND->getType();
2141 const Type* TypePtr = QT->getAs<Type>();
2142 if (!isa<TypeOfExprType>(TypePtr))
2143 return;
2144 while (isa<TypeOfExprType>(TypePtr)) {
2145 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2146 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2147 TypePtr = QT->getAs<Type>();
2148 }
2149 // FIXME. This will not work for multiple declarators; as in:
2150 // __typeof__(a) b,c,d;
2151 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2152 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2153 const char *startBuf = SM->getCharacterData(DeclLoc);
2154 if (ND->getInit()) {
2155 std::string Name(ND->getNameAsString());
2156 TypeAsString += " " + Name + " = ";
2157 Expr *E = ND->getInit();
2158 SourceLocation startLoc;
2159 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2160 startLoc = ECE->getLParenLoc();
2161 else
2162 startLoc = E->getLocStart();
2163 startLoc = SM->getExpansionLoc(startLoc);
2164 const char *endBuf = SM->getCharacterData(startLoc);
2165 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2166 }
2167 else {
2168 SourceLocation X = ND->getLocEnd();
2169 X = SM->getExpansionLoc(X);
2170 const char *endBuf = SM->getCharacterData(X);
2171 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2172 }
2173}
2174
2175// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2176void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2177 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2178 SmallVector<QualType, 16> ArgTys;
2179 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2180 QualType getFuncType =
2181 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2182 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2183 SourceLocation(),
2184 SourceLocation(),
2185 SelGetUidIdent, getFuncType, 0,
2186 SC_Extern,
2187 SC_None, false);
2188}
2189
2190void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2191 // declared in <objc/objc.h>
2192 if (FD->getIdentifier() &&
2193 FD->getName() == "sel_registerName") {
2194 SelGetUidFunctionDecl = FD;
2195 return;
2196 }
2197 RewriteObjCQualifiedInterfaceTypes(FD);
2198}
2199
2200void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2201 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2202 const char *argPtr = TypeString.c_str();
2203 if (!strchr(argPtr, '^')) {
2204 Str += TypeString;
2205 return;
2206 }
2207 while (*argPtr) {
2208 Str += (*argPtr == '^' ? '*' : *argPtr);
2209 argPtr++;
2210 }
2211}
2212
2213// FIXME. Consolidate this routine with RewriteBlockPointerType.
2214void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2215 ValueDecl *VD) {
2216 QualType Type = VD->getType();
2217 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2218 const char *argPtr = TypeString.c_str();
2219 int paren = 0;
2220 while (*argPtr) {
2221 switch (*argPtr) {
2222 case '(':
2223 Str += *argPtr;
2224 paren++;
2225 break;
2226 case ')':
2227 Str += *argPtr;
2228 paren--;
2229 break;
2230 case '^':
2231 Str += '*';
2232 if (paren == 1)
2233 Str += VD->getNameAsString();
2234 break;
2235 default:
2236 Str += *argPtr;
2237 break;
2238 }
2239 argPtr++;
2240 }
2241}
2242
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002243void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2244 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2245 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2246 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2247 if (!proto)
2248 return;
2249 QualType Type = proto->getResultType();
2250 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2251 FdStr += " ";
2252 FdStr += FD->getName();
2253 FdStr += "(";
2254 unsigned numArgs = proto->getNumArgs();
2255 for (unsigned i = 0; i < numArgs; i++) {
2256 QualType ArgType = proto->getArgType(i);
2257 RewriteBlockPointerType(FdStr, ArgType);
2258 if (i+1 < numArgs)
2259 FdStr += ", ";
2260 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002261 if (FD->isVariadic()) {
2262 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2263 }
2264 else
2265 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002266 InsertText(FunLocStart, FdStr);
2267}
2268
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002269// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002270void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2271 if (SuperContructorFunctionDecl)
2272 return;
2273 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2274 SmallVector<QualType, 16> ArgTys;
2275 QualType argT = Context->getObjCIdType();
2276 assert(!argT.isNull() && "Can't find 'id' type");
2277 ArgTys.push_back(argT);
2278 ArgTys.push_back(argT);
2279 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2280 &ArgTys[0], ArgTys.size());
2281 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2282 SourceLocation(),
2283 SourceLocation(),
2284 msgSendIdent, msgSendType, 0,
2285 SC_Extern,
2286 SC_None, false);
2287}
2288
2289// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2290void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2291 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2292 SmallVector<QualType, 16> ArgTys;
2293 QualType argT = Context->getObjCIdType();
2294 assert(!argT.isNull() && "Can't find 'id' type");
2295 ArgTys.push_back(argT);
2296 argT = Context->getObjCSelType();
2297 assert(!argT.isNull() && "Can't find 'SEL' type");
2298 ArgTys.push_back(argT);
2299 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2300 &ArgTys[0], ArgTys.size(),
2301 true /*isVariadic*/);
2302 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2303 SourceLocation(),
2304 SourceLocation(),
2305 msgSendIdent, msgSendType, 0,
2306 SC_Extern,
2307 SC_None, false);
2308}
2309
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002310// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002311void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2312 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002313 SmallVector<QualType, 2> ArgTys;
2314 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002315 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002316 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002317 true /*isVariadic*/);
2318 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2319 SourceLocation(),
2320 SourceLocation(),
2321 msgSendIdent, msgSendType, 0,
2322 SC_Extern,
2323 SC_None, false);
2324}
2325
2326// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2327void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2328 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2329 SmallVector<QualType, 16> ArgTys;
2330 QualType argT = Context->getObjCIdType();
2331 assert(!argT.isNull() && "Can't find 'id' type");
2332 ArgTys.push_back(argT);
2333 argT = Context->getObjCSelType();
2334 assert(!argT.isNull() && "Can't find 'SEL' type");
2335 ArgTys.push_back(argT);
2336 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2337 &ArgTys[0], ArgTys.size(),
2338 true /*isVariadic*/);
2339 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2340 SourceLocation(),
2341 SourceLocation(),
2342 msgSendIdent, msgSendType, 0,
2343 SC_Extern,
2344 SC_None, false);
2345}
2346
2347// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002348// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002349void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2350 IdentifierInfo *msgSendIdent =
2351 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002352 SmallVector<QualType, 2> ArgTys;
2353 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002354 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002355 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002356 true /*isVariadic*/);
2357 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 msgSendIdent, msgSendType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2366void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2367 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2368 SmallVector<QualType, 16> ArgTys;
2369 QualType argT = Context->getObjCIdType();
2370 assert(!argT.isNull() && "Can't find 'id' type");
2371 ArgTys.push_back(argT);
2372 argT = Context->getObjCSelType();
2373 assert(!argT.isNull() && "Can't find 'SEL' type");
2374 ArgTys.push_back(argT);
2375 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2376 &ArgTys[0], ArgTys.size(),
2377 true /*isVariadic*/);
2378 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2379 SourceLocation(),
2380 SourceLocation(),
2381 msgSendIdent, msgSendType, 0,
2382 SC_Extern,
2383 SC_None, false);
2384}
2385
2386// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2387void RewriteModernObjC::SynthGetClassFunctionDecl() {
2388 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2389 SmallVector<QualType, 16> ArgTys;
2390 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2391 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2392 &ArgTys[0], ArgTys.size());
2393 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2394 SourceLocation(),
2395 SourceLocation(),
2396 getClassIdent, getClassType, 0,
2397 SC_Extern,
2398 SC_None, false);
2399}
2400
2401// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2402void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2403 IdentifierInfo *getSuperClassIdent =
2404 &Context->Idents.get("class_getSuperclass");
2405 SmallVector<QualType, 16> ArgTys;
2406 ArgTys.push_back(Context->getObjCClassType());
2407 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2408 &ArgTys[0], ArgTys.size());
2409 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 SourceLocation(),
2411 SourceLocation(),
2412 getSuperClassIdent,
2413 getClassType, 0,
2414 SC_Extern,
2415 SC_None,
2416 false);
2417}
2418
2419// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2420void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2421 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2422 SmallVector<QualType, 16> ArgTys;
2423 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2424 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2425 &ArgTys[0], ArgTys.size());
2426 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2427 SourceLocation(),
2428 SourceLocation(),
2429 getClassIdent, getClassType, 0,
2430 SC_Extern,
2431 SC_None, false);
2432}
2433
2434Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2435 QualType strType = getConstantStringStructType();
2436
2437 std::string S = "__NSConstantStringImpl_";
2438
2439 std::string tmpName = InFileName;
2440 unsigned i;
2441 for (i=0; i < tmpName.length(); i++) {
2442 char c = tmpName.at(i);
2443 // replace any non alphanumeric characters with '_'.
2444 if (!isalpha(c) && (c < '0' || c > '9'))
2445 tmpName[i] = '_';
2446 }
2447 S += tmpName;
2448 S += "_";
2449 S += utostr(NumObjCStringLiterals++);
2450
2451 Preamble += "static __NSConstantStringImpl " + S;
2452 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2453 Preamble += "0x000007c8,"; // utf8_str
2454 // The pretty printer for StringLiteral handles escape characters properly.
2455 std::string prettyBufS;
2456 llvm::raw_string_ostream prettyBuf(prettyBufS);
2457 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2458 PrintingPolicy(LangOpts));
2459 Preamble += prettyBuf.str();
2460 Preamble += ",";
2461 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2462
2463 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2464 SourceLocation(), &Context->Idents.get(S),
2465 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002466 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002467 SourceLocation());
2468 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2469 Context->getPointerType(DRE->getType()),
2470 VK_RValue, OK_Ordinary,
2471 SourceLocation());
2472 // cast to NSConstantString *
2473 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2474 CK_CPointerToObjCPointerCast, Unop);
2475 ReplaceStmt(Exp, cast);
2476 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2477 return cast;
2478}
2479
Fariborz Jahanian55947042012-03-27 20:17:30 +00002480Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2481 unsigned IntSize =
2482 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2483
2484 Expr *FlagExp = IntegerLiteral::Create(*Context,
2485 llvm::APInt(IntSize, Exp->getValue()),
2486 Context->IntTy, Exp->getLocation());
2487 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2488 CK_BitCast, FlagExp);
2489 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2490 cast);
2491 ReplaceStmt(Exp, PE);
2492 return PE;
2493}
2494
Patrick Beardeb382ec2012-04-19 00:25:12 +00002495Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002496 // synthesize declaration of helper functions needed in this routine.
2497 if (!SelGetUidFunctionDecl)
2498 SynthSelGetUidFunctionDecl();
2499 // use objc_msgSend() for all.
2500 if (!MsgSendFunctionDecl)
2501 SynthMsgSendFunctionDecl();
2502 if (!GetClassFunctionDecl)
2503 SynthGetClassFunctionDecl();
2504
2505 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2506 SourceLocation StartLoc = Exp->getLocStart();
2507 SourceLocation EndLoc = Exp->getLocEnd();
2508
2509 // Synthesize a call to objc_msgSend().
2510 SmallVector<Expr*, 4> MsgExprs;
2511 SmallVector<Expr*, 4> ClsExprs;
2512 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002513
Patrick Beardeb382ec2012-04-19 00:25:12 +00002514 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2515 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2516 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002517
Patrick Beardeb382ec2012-04-19 00:25:12 +00002518 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002519 ClsExprs.push_back(StringLiteral::Create(*Context,
2520 clsName->getName(),
2521 StringLiteral::Ascii, false,
2522 argType, SourceLocation()));
2523 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2524 &ClsExprs[0],
2525 ClsExprs.size(),
2526 StartLoc, EndLoc);
2527 MsgExprs.push_back(Cls);
2528
Patrick Beardeb382ec2012-04-19 00:25:12 +00002529 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002530 // it will be the 2nd argument.
2531 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002532 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002533 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002534 StringLiteral::Ascii, false,
2535 argType, SourceLocation()));
2536 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2537 &SelExprs[0], SelExprs.size(),
2538 StartLoc, EndLoc);
2539 MsgExprs.push_back(SelExp);
2540
Patrick Beardeb382ec2012-04-19 00:25:12 +00002541 // User provided sub-expression is the 3rd, and last, argument.
2542 Expr *subExpr = Exp->getSubExpr();
2543 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002544 QualType type = ICE->getType();
2545 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2546 CastKind CK = CK_BitCast;
2547 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2548 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002549 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002550 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002551 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002552
2553 SmallVector<QualType, 4> ArgTypes;
2554 ArgTypes.push_back(Context->getObjCIdType());
2555 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002556 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2557 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002558 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002559
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002560 QualType returnType = Exp->getType();
2561 // Get the type, we will need to reference it in a couple spots.
2562 QualType msgSendType = MsgSendFlavor->getType();
2563
2564 // Create a reference to the objc_msgSend() declaration.
2565 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2566 VK_LValue, SourceLocation());
2567
2568 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002569 Context->getPointerType(Context->VoidTy),
2570 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002571
2572 // Now do the "normal" pointer to function cast.
2573 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002574 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2575 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002576 castType = Context->getPointerType(castType);
2577 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2578 cast);
2579
2580 // Don't forget the parens to enforce the proper binding.
2581 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2582
2583 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2584 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2585 MsgExprs.size(),
2586 FT->getResultType(), VK_RValue,
2587 EndLoc);
2588 ReplaceStmt(Exp, CE);
2589 return CE;
2590}
2591
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002592Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2593 // synthesize declaration of helper functions needed in this routine.
2594 if (!SelGetUidFunctionDecl)
2595 SynthSelGetUidFunctionDecl();
2596 // use objc_msgSend() for all.
2597 if (!MsgSendFunctionDecl)
2598 SynthMsgSendFunctionDecl();
2599 if (!GetClassFunctionDecl)
2600 SynthGetClassFunctionDecl();
2601
2602 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2603 SourceLocation StartLoc = Exp->getLocStart();
2604 SourceLocation EndLoc = Exp->getLocEnd();
2605
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002606 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002607 QualType IntQT = Context->IntTy;
2608 QualType NSArrayFType =
2609 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002610 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002611 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2612 DeclRefExpr *NSArrayDRE =
2613 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2614 SourceLocation());
2615
2616 SmallVector<Expr*, 16> InitExprs;
2617 unsigned NumElements = Exp->getNumElements();
2618 unsigned UnsignedIntSize =
2619 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2620 Expr *count = IntegerLiteral::Create(*Context,
2621 llvm::APInt(UnsignedIntSize, NumElements),
2622 Context->UnsignedIntTy, SourceLocation());
2623 InitExprs.push_back(count);
2624 for (unsigned i = 0; i < NumElements; i++)
2625 InitExprs.push_back(Exp->getElement(i));
2626 Expr *NSArrayCallExpr =
2627 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2628 NSArrayFType, VK_LValue, SourceLocation());
2629
2630 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2631 SourceLocation(),
2632 &Context->Idents.get("arr"),
2633 Context->getPointerType(Context->VoidPtrTy), 0,
2634 /*BitWidth=*/0, /*Mutable=*/true,
2635 /*HasInit=*/false);
2636 MemberExpr *ArrayLiteralME =
2637 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2638 SourceLocation(),
2639 ARRFD->getType(), VK_LValue,
2640 OK_Ordinary);
2641 QualType ConstIdT = Context->getObjCIdType().withConst();
2642 CStyleCastExpr * ArrayLiteralObjects =
2643 NoTypeInfoCStyleCastExpr(Context,
2644 Context->getPointerType(ConstIdT),
2645 CK_BitCast,
2646 ArrayLiteralME);
2647
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002648 // Synthesize a call to objc_msgSend().
2649 SmallVector<Expr*, 32> MsgExprs;
2650 SmallVector<Expr*, 4> ClsExprs;
2651 QualType argType = Context->getPointerType(Context->CharTy);
2652 QualType expType = Exp->getType();
2653
2654 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2655 ObjCInterfaceDecl *Class =
2656 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2657
2658 IdentifierInfo *clsName = Class->getIdentifier();
2659 ClsExprs.push_back(StringLiteral::Create(*Context,
2660 clsName->getName(),
2661 StringLiteral::Ascii, false,
2662 argType, SourceLocation()));
2663 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2664 &ClsExprs[0],
2665 ClsExprs.size(),
2666 StartLoc, EndLoc);
2667 MsgExprs.push_back(Cls);
2668
2669 // Create a call to sel_registerName("arrayWithObjects:count:").
2670 // it will be the 2nd argument.
2671 SmallVector<Expr*, 4> SelExprs;
2672 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2673 SelExprs.push_back(StringLiteral::Create(*Context,
2674 ArrayMethod->getSelector().getAsString(),
2675 StringLiteral::Ascii, false,
2676 argType, SourceLocation()));
2677 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2678 &SelExprs[0], SelExprs.size(),
2679 StartLoc, EndLoc);
2680 MsgExprs.push_back(SelExp);
2681
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002682 // (const id [])objects
2683 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002684
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002685 // (NSUInteger)cnt
2686 Expr *cnt = IntegerLiteral::Create(*Context,
2687 llvm::APInt(UnsignedIntSize, NumElements),
2688 Context->UnsignedIntTy, SourceLocation());
2689 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002690
2691
2692 SmallVector<QualType, 4> ArgTypes;
2693 ArgTypes.push_back(Context->getObjCIdType());
2694 ArgTypes.push_back(Context->getObjCSelType());
2695 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2696 E = ArrayMethod->param_end(); PI != E; ++PI)
2697 ArgTypes.push_back((*PI)->getType());
2698
2699 QualType returnType = Exp->getType();
2700 // Get the type, we will need to reference it in a couple spots.
2701 QualType msgSendType = MsgSendFlavor->getType();
2702
2703 // Create a reference to the objc_msgSend() declaration.
2704 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2705 VK_LValue, SourceLocation());
2706
2707 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2708 Context->getPointerType(Context->VoidTy),
2709 CK_BitCast, DRE);
2710
2711 // Now do the "normal" pointer to function cast.
2712 QualType castType =
2713 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2714 ArrayMethod->isVariadic());
2715 castType = Context->getPointerType(castType);
2716 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2717 cast);
2718
2719 // Don't forget the parens to enforce the proper binding.
2720 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2721
2722 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2723 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2724 MsgExprs.size(),
2725 FT->getResultType(), VK_RValue,
2726 EndLoc);
2727 ReplaceStmt(Exp, CE);
2728 return CE;
2729}
2730
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002731Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2732 // synthesize declaration of helper functions needed in this routine.
2733 if (!SelGetUidFunctionDecl)
2734 SynthSelGetUidFunctionDecl();
2735 // use objc_msgSend() for all.
2736 if (!MsgSendFunctionDecl)
2737 SynthMsgSendFunctionDecl();
2738 if (!GetClassFunctionDecl)
2739 SynthGetClassFunctionDecl();
2740
2741 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2742 SourceLocation StartLoc = Exp->getLocStart();
2743 SourceLocation EndLoc = Exp->getLocEnd();
2744
2745 // Build the expression: __NSContainer_literal(int, ...).arr
2746 QualType IntQT = Context->IntTy;
2747 QualType NSDictFType =
2748 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2749 std::string NSDictFName("__NSContainer_literal");
2750 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2751 DeclRefExpr *NSDictDRE =
2752 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2753 SourceLocation());
2754
2755 SmallVector<Expr*, 16> KeyExprs;
2756 SmallVector<Expr*, 16> ValueExprs;
2757
2758 unsigned NumElements = Exp->getNumElements();
2759 unsigned UnsignedIntSize =
2760 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2761 Expr *count = IntegerLiteral::Create(*Context,
2762 llvm::APInt(UnsignedIntSize, NumElements),
2763 Context->UnsignedIntTy, SourceLocation());
2764 KeyExprs.push_back(count);
2765 ValueExprs.push_back(count);
2766 for (unsigned i = 0; i < NumElements; i++) {
2767 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2768 KeyExprs.push_back(Element.Key);
2769 ValueExprs.push_back(Element.Value);
2770 }
2771
2772 // (const id [])objects
2773 Expr *NSValueCallExpr =
2774 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2775 NSDictFType, VK_LValue, SourceLocation());
2776
2777 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2778 SourceLocation(),
2779 &Context->Idents.get("arr"),
2780 Context->getPointerType(Context->VoidPtrTy), 0,
2781 /*BitWidth=*/0, /*Mutable=*/true,
2782 /*HasInit=*/false);
2783 MemberExpr *DictLiteralValueME =
2784 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2785 SourceLocation(),
2786 ARRFD->getType(), VK_LValue,
2787 OK_Ordinary);
2788 QualType ConstIdT = Context->getObjCIdType().withConst();
2789 CStyleCastExpr * DictValueObjects =
2790 NoTypeInfoCStyleCastExpr(Context,
2791 Context->getPointerType(ConstIdT),
2792 CK_BitCast,
2793 DictLiteralValueME);
2794 // (const id <NSCopying> [])keys
2795 Expr *NSKeyCallExpr =
2796 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2797 NSDictFType, VK_LValue, SourceLocation());
2798
2799 MemberExpr *DictLiteralKeyME =
2800 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2801 SourceLocation(),
2802 ARRFD->getType(), VK_LValue,
2803 OK_Ordinary);
2804
2805 CStyleCastExpr * DictKeyObjects =
2806 NoTypeInfoCStyleCastExpr(Context,
2807 Context->getPointerType(ConstIdT),
2808 CK_BitCast,
2809 DictLiteralKeyME);
2810
2811
2812
2813 // Synthesize a call to objc_msgSend().
2814 SmallVector<Expr*, 32> MsgExprs;
2815 SmallVector<Expr*, 4> ClsExprs;
2816 QualType argType = Context->getPointerType(Context->CharTy);
2817 QualType expType = Exp->getType();
2818
2819 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2820 ObjCInterfaceDecl *Class =
2821 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2822
2823 IdentifierInfo *clsName = Class->getIdentifier();
2824 ClsExprs.push_back(StringLiteral::Create(*Context,
2825 clsName->getName(),
2826 StringLiteral::Ascii, false,
2827 argType, SourceLocation()));
2828 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2829 &ClsExprs[0],
2830 ClsExprs.size(),
2831 StartLoc, EndLoc);
2832 MsgExprs.push_back(Cls);
2833
2834 // Create a call to sel_registerName("arrayWithObjects:count:").
2835 // it will be the 2nd argument.
2836 SmallVector<Expr*, 4> SelExprs;
2837 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2838 SelExprs.push_back(StringLiteral::Create(*Context,
2839 DictMethod->getSelector().getAsString(),
2840 StringLiteral::Ascii, false,
2841 argType, SourceLocation()));
2842 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2843 &SelExprs[0], SelExprs.size(),
2844 StartLoc, EndLoc);
2845 MsgExprs.push_back(SelExp);
2846
2847 // (const id [])objects
2848 MsgExprs.push_back(DictValueObjects);
2849
2850 // (const id <NSCopying> [])keys
2851 MsgExprs.push_back(DictKeyObjects);
2852
2853 // (NSUInteger)cnt
2854 Expr *cnt = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 MsgExprs.push_back(cnt);
2858
2859
2860 SmallVector<QualType, 8> ArgTypes;
2861 ArgTypes.push_back(Context->getObjCIdType());
2862 ArgTypes.push_back(Context->getObjCSelType());
2863 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2864 E = DictMethod->param_end(); PI != E; ++PI) {
2865 QualType T = (*PI)->getType();
2866 if (const PointerType* PT = T->getAs<PointerType>()) {
2867 QualType PointeeTy = PT->getPointeeType();
2868 convertToUnqualifiedObjCType(PointeeTy);
2869 T = Context->getPointerType(PointeeTy);
2870 }
2871 ArgTypes.push_back(T);
2872 }
2873
2874 QualType returnType = Exp->getType();
2875 // Get the type, we will need to reference it in a couple spots.
2876 QualType msgSendType = MsgSendFlavor->getType();
2877
2878 // Create a reference to the objc_msgSend() declaration.
2879 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2880 VK_LValue, SourceLocation());
2881
2882 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2883 Context->getPointerType(Context->VoidTy),
2884 CK_BitCast, DRE);
2885
2886 // Now do the "normal" pointer to function cast.
2887 QualType castType =
2888 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2889 DictMethod->isVariadic());
2890 castType = Context->getPointerType(castType);
2891 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2892 cast);
2893
2894 // Don't forget the parens to enforce the proper binding.
2895 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2896
2897 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2898 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2899 MsgExprs.size(),
2900 FT->getResultType(), VK_RValue,
2901 EndLoc);
2902 ReplaceStmt(Exp, CE);
2903 return CE;
2904}
2905
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002906// struct __rw_objc_super {
2907// struct objc_object *object; struct objc_object *superClass;
2908// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002909QualType RewriteModernObjC::getSuperStructType() {
2910 if (!SuperStructDecl) {
2911 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2912 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002913 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002914 QualType FieldTypes[2];
2915
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002916 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002917 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002918 // struct objc_object *superClass;
2919 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002920
2921 // Create fields
2922 for (unsigned i = 0; i < 2; ++i) {
2923 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2924 SourceLocation(),
2925 SourceLocation(), 0,
2926 FieldTypes[i], 0,
2927 /*BitWidth=*/0,
2928 /*Mutable=*/false,
2929 /*HasInit=*/false));
2930 }
2931
2932 SuperStructDecl->completeDefinition();
2933 }
2934 return Context->getTagDeclType(SuperStructDecl);
2935}
2936
2937QualType RewriteModernObjC::getConstantStringStructType() {
2938 if (!ConstantStringDecl) {
2939 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2940 SourceLocation(), SourceLocation(),
2941 &Context->Idents.get("__NSConstantStringImpl"));
2942 QualType FieldTypes[4];
2943
2944 // struct objc_object *receiver;
2945 FieldTypes[0] = Context->getObjCIdType();
2946 // int flags;
2947 FieldTypes[1] = Context->IntTy;
2948 // char *str;
2949 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2950 // long length;
2951 FieldTypes[3] = Context->LongTy;
2952
2953 // Create fields
2954 for (unsigned i = 0; i < 4; ++i) {
2955 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2956 ConstantStringDecl,
2957 SourceLocation(),
2958 SourceLocation(), 0,
2959 FieldTypes[i], 0,
2960 /*BitWidth=*/0,
2961 /*Mutable=*/true,
2962 /*HasInit=*/false));
2963 }
2964
2965 ConstantStringDecl->completeDefinition();
2966 }
2967 return Context->getTagDeclType(ConstantStringDecl);
2968}
2969
2970Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2971 SourceLocation StartLoc,
2972 SourceLocation EndLoc) {
2973 if (!SelGetUidFunctionDecl)
2974 SynthSelGetUidFunctionDecl();
2975 if (!MsgSendFunctionDecl)
2976 SynthMsgSendFunctionDecl();
2977 if (!MsgSendSuperFunctionDecl)
2978 SynthMsgSendSuperFunctionDecl();
2979 if (!MsgSendStretFunctionDecl)
2980 SynthMsgSendStretFunctionDecl();
2981 if (!MsgSendSuperStretFunctionDecl)
2982 SynthMsgSendSuperStretFunctionDecl();
2983 if (!MsgSendFpretFunctionDecl)
2984 SynthMsgSendFpretFunctionDecl();
2985 if (!GetClassFunctionDecl)
2986 SynthGetClassFunctionDecl();
2987 if (!GetSuperClassFunctionDecl)
2988 SynthGetSuperClassFunctionDecl();
2989 if (!GetMetaClassFunctionDecl)
2990 SynthGetMetaClassFunctionDecl();
2991
2992 // default to objc_msgSend().
2993 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2994 // May need to use objc_msgSend_stret() as well.
2995 FunctionDecl *MsgSendStretFlavor = 0;
2996 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2997 QualType resultType = mDecl->getResultType();
2998 if (resultType->isRecordType())
2999 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3000 else if (resultType->isRealFloatingType())
3001 MsgSendFlavor = MsgSendFpretFunctionDecl;
3002 }
3003
3004 // Synthesize a call to objc_msgSend().
3005 SmallVector<Expr*, 8> MsgExprs;
3006 switch (Exp->getReceiverKind()) {
3007 case ObjCMessageExpr::SuperClass: {
3008 MsgSendFlavor = MsgSendSuperFunctionDecl;
3009 if (MsgSendStretFlavor)
3010 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3011 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3012
3013 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3014
3015 SmallVector<Expr*, 4> InitExprs;
3016
3017 // set the receiver to self, the first argument to all methods.
3018 InitExprs.push_back(
3019 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3020 CK_BitCast,
3021 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003022 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003023 Context->getObjCIdType(),
3024 VK_RValue,
3025 SourceLocation()))
3026 ); // set the 'receiver'.
3027
3028 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3029 SmallVector<Expr*, 8> ClsExprs;
3030 QualType argType = Context->getPointerType(Context->CharTy);
3031 ClsExprs.push_back(StringLiteral::Create(*Context,
3032 ClassDecl->getIdentifier()->getName(),
3033 StringLiteral::Ascii, false,
3034 argType, SourceLocation()));
3035 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3036 &ClsExprs[0],
3037 ClsExprs.size(),
3038 StartLoc,
3039 EndLoc);
3040 // (Class)objc_getClass("CurrentClass")
3041 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3042 Context->getObjCClassType(),
3043 CK_BitCast, Cls);
3044 ClsExprs.clear();
3045 ClsExprs.push_back(ArgExpr);
3046 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3047 &ClsExprs[0], ClsExprs.size(),
3048 StartLoc, EndLoc);
3049
3050 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3051 // To turn off a warning, type-cast to 'id'
3052 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3053 NoTypeInfoCStyleCastExpr(Context,
3054 Context->getObjCIdType(),
3055 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003056 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003057 QualType superType = getSuperStructType();
3058 Expr *SuperRep;
3059
3060 if (LangOpts.MicrosoftExt) {
3061 SynthSuperContructorFunctionDecl();
3062 // Simulate a contructor call...
3063 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003064 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003065 SourceLocation());
3066 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3067 InitExprs.size(),
3068 superType, VK_LValue,
3069 SourceLocation());
3070 // The code for super is a little tricky to prevent collision with
3071 // the structure definition in the header. The rewriter has it's own
3072 // internal definition (__rw_objc_super) that is uses. This is why
3073 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003074 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003075 //
3076 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3077 Context->getPointerType(SuperRep->getType()),
3078 VK_RValue, OK_Ordinary,
3079 SourceLocation());
3080 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3081 Context->getPointerType(superType),
3082 CK_BitCast, SuperRep);
3083 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003084 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003085 InitListExpr *ILE =
3086 new (Context) InitListExpr(*Context, SourceLocation(),
3087 &InitExprs[0], InitExprs.size(),
3088 SourceLocation());
3089 TypeSourceInfo *superTInfo
3090 = Context->getTrivialTypeSourceInfo(superType);
3091 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3092 superType, VK_LValue,
3093 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003094 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003095 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3096 Context->getPointerType(SuperRep->getType()),
3097 VK_RValue, OK_Ordinary,
3098 SourceLocation());
3099 }
3100 MsgExprs.push_back(SuperRep);
3101 break;
3102 }
3103
3104 case ObjCMessageExpr::Class: {
3105 SmallVector<Expr*, 8> ClsExprs;
3106 QualType argType = Context->getPointerType(Context->CharTy);
3107 ObjCInterfaceDecl *Class
3108 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3109 IdentifierInfo *clsName = Class->getIdentifier();
3110 ClsExprs.push_back(StringLiteral::Create(*Context,
3111 clsName->getName(),
3112 StringLiteral::Ascii, false,
3113 argType, SourceLocation()));
3114 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3115 &ClsExprs[0],
3116 ClsExprs.size(),
3117 StartLoc, EndLoc);
3118 MsgExprs.push_back(Cls);
3119 break;
3120 }
3121
3122 case ObjCMessageExpr::SuperInstance:{
3123 MsgSendFlavor = MsgSendSuperFunctionDecl;
3124 if (MsgSendStretFlavor)
3125 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3126 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3127 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3128 SmallVector<Expr*, 4> InitExprs;
3129
3130 InitExprs.push_back(
3131 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3132 CK_BitCast,
3133 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003134 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003135 Context->getObjCIdType(),
3136 VK_RValue, SourceLocation()))
3137 ); // set the 'receiver'.
3138
3139 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3140 SmallVector<Expr*, 8> ClsExprs;
3141 QualType argType = Context->getPointerType(Context->CharTy);
3142 ClsExprs.push_back(StringLiteral::Create(*Context,
3143 ClassDecl->getIdentifier()->getName(),
3144 StringLiteral::Ascii, false, argType,
3145 SourceLocation()));
3146 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3147 &ClsExprs[0],
3148 ClsExprs.size(),
3149 StartLoc, EndLoc);
3150 // (Class)objc_getClass("CurrentClass")
3151 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3152 Context->getObjCClassType(),
3153 CK_BitCast, Cls);
3154 ClsExprs.clear();
3155 ClsExprs.push_back(ArgExpr);
3156 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3157 &ClsExprs[0], ClsExprs.size(),
3158 StartLoc, EndLoc);
3159
3160 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3161 // To turn off a warning, type-cast to 'id'
3162 InitExprs.push_back(
3163 // set 'super class', using class_getSuperclass().
3164 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3165 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003166 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003167 QualType superType = getSuperStructType();
3168 Expr *SuperRep;
3169
3170 if (LangOpts.MicrosoftExt) {
3171 SynthSuperContructorFunctionDecl();
3172 // Simulate a contructor call...
3173 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003174 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003175 SourceLocation());
3176 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3177 InitExprs.size(),
3178 superType, VK_LValue, SourceLocation());
3179 // The code for super is a little tricky to prevent collision with
3180 // the structure definition in the header. The rewriter has it's own
3181 // internal definition (__rw_objc_super) that is uses. This is why
3182 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003183 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003184 //
3185 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3186 Context->getPointerType(SuperRep->getType()),
3187 VK_RValue, OK_Ordinary,
3188 SourceLocation());
3189 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3190 Context->getPointerType(superType),
3191 CK_BitCast, SuperRep);
3192 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003193 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003194 InitListExpr *ILE =
3195 new (Context) InitListExpr(*Context, SourceLocation(),
3196 &InitExprs[0], InitExprs.size(),
3197 SourceLocation());
3198 TypeSourceInfo *superTInfo
3199 = Context->getTrivialTypeSourceInfo(superType);
3200 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3201 superType, VK_RValue, ILE,
3202 false);
3203 }
3204 MsgExprs.push_back(SuperRep);
3205 break;
3206 }
3207
3208 case ObjCMessageExpr::Instance: {
3209 // Remove all type-casts because it may contain objc-style types; e.g.
3210 // Foo<Proto> *.
3211 Expr *recExpr = Exp->getInstanceReceiver();
3212 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3213 recExpr = CE->getSubExpr();
3214 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3215 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3216 ? CK_BlockPointerToObjCPointerCast
3217 : CK_CPointerToObjCPointerCast;
3218
3219 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3220 CK, recExpr);
3221 MsgExprs.push_back(recExpr);
3222 break;
3223 }
3224 }
3225
3226 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3227 SmallVector<Expr*, 8> SelExprs;
3228 QualType argType = Context->getPointerType(Context->CharTy);
3229 SelExprs.push_back(StringLiteral::Create(*Context,
3230 Exp->getSelector().getAsString(),
3231 StringLiteral::Ascii, false,
3232 argType, SourceLocation()));
3233 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3234 &SelExprs[0], SelExprs.size(),
3235 StartLoc,
3236 EndLoc);
3237 MsgExprs.push_back(SelExp);
3238
3239 // Now push any user supplied arguments.
3240 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3241 Expr *userExpr = Exp->getArg(i);
3242 // Make all implicit casts explicit...ICE comes in handy:-)
3243 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3244 // Reuse the ICE type, it is exactly what the doctor ordered.
3245 QualType type = ICE->getType();
3246 if (needToScanForQualifiers(type))
3247 type = Context->getObjCIdType();
3248 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3249 (void)convertBlockPointerToFunctionPointer(type);
3250 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3251 CastKind CK;
3252 if (SubExpr->getType()->isIntegralType(*Context) &&
3253 type->isBooleanType()) {
3254 CK = CK_IntegralToBoolean;
3255 } else if (type->isObjCObjectPointerType()) {
3256 if (SubExpr->getType()->isBlockPointerType()) {
3257 CK = CK_BlockPointerToObjCPointerCast;
3258 } else if (SubExpr->getType()->isPointerType()) {
3259 CK = CK_CPointerToObjCPointerCast;
3260 } else {
3261 CK = CK_BitCast;
3262 }
3263 } else {
3264 CK = CK_BitCast;
3265 }
3266
3267 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3268 }
3269 // Make id<P...> cast into an 'id' cast.
3270 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3271 if (CE->getType()->isObjCQualifiedIdType()) {
3272 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3273 userExpr = CE->getSubExpr();
3274 CastKind CK;
3275 if (userExpr->getType()->isIntegralType(*Context)) {
3276 CK = CK_IntegralToPointer;
3277 } else if (userExpr->getType()->isBlockPointerType()) {
3278 CK = CK_BlockPointerToObjCPointerCast;
3279 } else if (userExpr->getType()->isPointerType()) {
3280 CK = CK_CPointerToObjCPointerCast;
3281 } else {
3282 CK = CK_BitCast;
3283 }
3284 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3285 CK, userExpr);
3286 }
3287 }
3288 MsgExprs.push_back(userExpr);
3289 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3290 // out the argument in the original expression (since we aren't deleting
3291 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3292 //Exp->setArg(i, 0);
3293 }
3294 // Generate the funky cast.
3295 CastExpr *cast;
3296 SmallVector<QualType, 8> ArgTypes;
3297 QualType returnType;
3298
3299 // Push 'id' and 'SEL', the 2 implicit arguments.
3300 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3301 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3302 else
3303 ArgTypes.push_back(Context->getObjCIdType());
3304 ArgTypes.push_back(Context->getObjCSelType());
3305 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3306 // Push any user argument types.
3307 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3308 E = OMD->param_end(); PI != E; ++PI) {
3309 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3310 ? Context->getObjCIdType()
3311 : (*PI)->getType();
3312 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3313 (void)convertBlockPointerToFunctionPointer(t);
3314 ArgTypes.push_back(t);
3315 }
3316 returnType = Exp->getType();
3317 convertToUnqualifiedObjCType(returnType);
3318 (void)convertBlockPointerToFunctionPointer(returnType);
3319 } else {
3320 returnType = Context->getObjCIdType();
3321 }
3322 // Get the type, we will need to reference it in a couple spots.
3323 QualType msgSendType = MsgSendFlavor->getType();
3324
3325 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003326 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003327 VK_LValue, SourceLocation());
3328
3329 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3330 // If we don't do this cast, we get the following bizarre warning/note:
3331 // xx.m:13: warning: function called through a non-compatible type
3332 // xx.m:13: note: if this code is reached, the program will abort
3333 cast = NoTypeInfoCStyleCastExpr(Context,
3334 Context->getPointerType(Context->VoidTy),
3335 CK_BitCast, DRE);
3336
3337 // Now do the "normal" pointer to function cast.
3338 QualType castType =
3339 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3340 // If we don't have a method decl, force a variadic cast.
3341 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3342 castType = Context->getPointerType(castType);
3343 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3344 cast);
3345
3346 // Don't forget the parens to enforce the proper binding.
3347 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3348
3349 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3350 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3351 MsgExprs.size(),
3352 FT->getResultType(), VK_RValue,
3353 EndLoc);
3354 Stmt *ReplacingStmt = CE;
3355 if (MsgSendStretFlavor) {
3356 // We have the method which returns a struct/union. Must also generate
3357 // call to objc_msgSend_stret and hang both varieties on a conditional
3358 // expression which dictate which one to envoke depending on size of
3359 // method's return type.
3360
3361 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003362 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3363 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003364 VK_LValue, SourceLocation());
3365 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3366 cast = NoTypeInfoCStyleCastExpr(Context,
3367 Context->getPointerType(Context->VoidTy),
3368 CK_BitCast, STDRE);
3369 // Now do the "normal" pointer to function cast.
3370 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3371 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3372 castType = Context->getPointerType(castType);
3373 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3374 cast);
3375
3376 // Don't forget the parens to enforce the proper binding.
3377 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3378
3379 FT = msgSendType->getAs<FunctionType>();
3380 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3381 MsgExprs.size(),
3382 FT->getResultType(), VK_RValue,
3383 SourceLocation());
3384
3385 // Build sizeof(returnType)
3386 UnaryExprOrTypeTraitExpr *sizeofExpr =
3387 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3388 Context->getTrivialTypeSourceInfo(returnType),
3389 Context->getSizeType(), SourceLocation(),
3390 SourceLocation());
3391 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3392 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3393 // For X86 it is more complicated and some kind of target specific routine
3394 // is needed to decide what to do.
3395 unsigned IntSize =
3396 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3397 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3398 llvm::APInt(IntSize, 8),
3399 Context->IntTy,
3400 SourceLocation());
3401 BinaryOperator *lessThanExpr =
3402 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3403 VK_RValue, OK_Ordinary, SourceLocation());
3404 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3405 ConditionalOperator *CondExpr =
3406 new (Context) ConditionalOperator(lessThanExpr,
3407 SourceLocation(), CE,
3408 SourceLocation(), STCE,
3409 returnType, VK_RValue, OK_Ordinary);
3410 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3411 CondExpr);
3412 }
3413 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3414 return ReplacingStmt;
3415}
3416
3417Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3418 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3419 Exp->getLocEnd());
3420
3421 // Now do the actual rewrite.
3422 ReplaceStmt(Exp, ReplacingStmt);
3423
3424 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3425 return ReplacingStmt;
3426}
3427
3428// typedef struct objc_object Protocol;
3429QualType RewriteModernObjC::getProtocolType() {
3430 if (!ProtocolTypeDecl) {
3431 TypeSourceInfo *TInfo
3432 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3433 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3434 SourceLocation(), SourceLocation(),
3435 &Context->Idents.get("Protocol"),
3436 TInfo);
3437 }
3438 return Context->getTypeDeclType(ProtocolTypeDecl);
3439}
3440
3441/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3442/// a synthesized/forward data reference (to the protocol's metadata).
3443/// The forward references (and metadata) are generated in
3444/// RewriteModernObjC::HandleTranslationUnit().
3445Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003446 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3447 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003448 IdentifierInfo *ID = &Context->Idents.get(Name);
3449 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3450 SourceLocation(), ID, getProtocolType(), 0,
3451 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003452 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3453 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003454 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3455 Context->getPointerType(DRE->getType()),
3456 VK_RValue, OK_Ordinary, SourceLocation());
3457 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3458 CK_BitCast,
3459 DerefExpr);
3460 ReplaceStmt(Exp, castExpr);
3461 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3462 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3463 return castExpr;
3464
3465}
3466
3467bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3468 const char *endBuf) {
3469 while (startBuf < endBuf) {
3470 if (*startBuf == '#') {
3471 // Skip whitespace.
3472 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3473 ;
3474 if (!strncmp(startBuf, "if", strlen("if")) ||
3475 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3476 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3477 !strncmp(startBuf, "define", strlen("define")) ||
3478 !strncmp(startBuf, "undef", strlen("undef")) ||
3479 !strncmp(startBuf, "else", strlen("else")) ||
3480 !strncmp(startBuf, "elif", strlen("elif")) ||
3481 !strncmp(startBuf, "endif", strlen("endif")) ||
3482 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3483 !strncmp(startBuf, "include", strlen("include")) ||
3484 !strncmp(startBuf, "import", strlen("import")) ||
3485 !strncmp(startBuf, "include_next", strlen("include_next")))
3486 return true;
3487 }
3488 startBuf++;
3489 }
3490 return false;
3491}
3492
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003493/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3494/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003495bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003496 TagDecl *Tag,
3497 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003498 if (!IDecl)
3499 return false;
3500 SourceLocation TagLocation;
3501 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3502 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003503 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003504 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003505 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003506 TagLocation = RD->getLocation();
3507 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003508 IDecl->getLocation(), TagLocation);
3509 }
3510 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3511 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3512 return false;
3513 IsNamedDefinition = true;
3514 TagLocation = ED->getLocation();
3515 return Context->getSourceManager().isBeforeInTranslationUnit(
3516 IDecl->getLocation(), TagLocation);
3517
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003518 }
3519 return false;
3520}
3521
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003522/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003523/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003524bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3525 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003526 if (isa<TypedefType>(Type)) {
3527 Result += "\t";
3528 return false;
3529 }
3530
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003531 if (Type->isArrayType()) {
3532 QualType ElemTy = Context->getBaseElementType(Type);
3533 return RewriteObjCFieldDeclType(ElemTy, Result);
3534 }
3535 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003536 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3537 if (RD->isCompleteDefinition()) {
3538 if (RD->isStruct())
3539 Result += "\n\tstruct ";
3540 else if (RD->isUnion())
3541 Result += "\n\tunion ";
3542 else
3543 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003544
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003545 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003546 if (GlobalDefinedTags.count(RD)) {
3547 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003548 Result += " ";
3549 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003550 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003551 Result += " {\n";
3552 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003553 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00003554 FieldDecl *FD = &*i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003555 RewriteObjCFieldDecl(FD, Result);
3556 }
3557 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003558 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003559 }
3560 }
3561 else if (Type->isEnumeralType()) {
3562 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3563 if (ED->isCompleteDefinition()) {
3564 Result += "\n\tenum ";
3565 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003566 if (GlobalDefinedTags.count(ED)) {
3567 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003568 Result += " ";
3569 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003570 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003571
3572 Result += " {\n";
3573 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3574 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3575 Result += "\t"; Result += EC->getName(); Result += " = ";
3576 llvm::APSInt Val = EC->getInitVal();
3577 Result += Val.toString(10);
3578 Result += ",\n";
3579 }
3580 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003581 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003582 }
3583 }
3584
3585 Result += "\t";
3586 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003587 return false;
3588}
3589
3590
3591/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3592/// It handles elaborated types, as well as enum types in the process.
3593void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3594 std::string &Result) {
3595 QualType Type = fieldDecl->getType();
3596 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003597
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003598 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3599 if (!EleboratedType)
3600 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003601 Result += Name;
3602 if (fieldDecl->isBitField()) {
3603 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3604 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003605 else if (EleboratedType && Type->isArrayType()) {
3606 CanQualType CType = Context->getCanonicalType(Type);
3607 while (isa<ArrayType>(CType)) {
3608 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3609 Result += "[";
3610 llvm::APInt Dim = CAT->getSize();
3611 Result += utostr(Dim.getZExtValue());
3612 Result += "]";
3613 }
3614 CType = CType->getAs<ArrayType>()->getElementType();
3615 }
3616 }
3617
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003618 Result += ";\n";
3619}
3620
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003621/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3622/// named aggregate types into the input buffer.
3623void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3624 std::string &Result) {
3625 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003626 if (isa<TypedefType>(Type))
3627 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003628 if (Type->isArrayType())
3629 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003630 ObjCContainerDecl *IDecl =
3631 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003632
3633 TagDecl *TD = 0;
3634 if (Type->isRecordType()) {
3635 TD = Type->getAs<RecordType>()->getDecl();
3636 }
3637 else if (Type->isEnumeralType()) {
3638 TD = Type->getAs<EnumType>()->getDecl();
3639 }
3640
3641 if (TD) {
3642 if (GlobalDefinedTags.count(TD))
3643 return;
3644
3645 bool IsNamedDefinition = false;
3646 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3647 RewriteObjCFieldDeclType(Type, Result);
3648 Result += ";";
3649 }
3650 if (IsNamedDefinition)
3651 GlobalDefinedTags.insert(TD);
3652 }
3653
3654}
3655
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003656/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3657/// an objective-c class with ivars.
3658void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3659 std::string &Result) {
3660 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3661 assert(CDecl->getName() != "" &&
3662 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003663 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003664 SmallVector<ObjCIvarDecl *, 8> IVars;
3665 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003666 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003667 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003668
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003669 SourceLocation LocStart = CDecl->getLocStart();
3670 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003671
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003672 const char *startBuf = SM->getCharacterData(LocStart);
3673 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003674
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003675 // If no ivars and no root or if its root, directly or indirectly,
3676 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003677 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003678 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3679 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3680 ReplaceText(LocStart, endBuf-startBuf, Result);
3681 return;
3682 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003683
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003684 // Insert named struct/union definitions inside class to
3685 // outer scope. This follows semantics of locally defined
3686 // struct/unions in objective-c classes.
3687 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3688 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3689
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003690 Result += "\nstruct ";
3691 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003692 Result += "_IMPL {\n";
3693
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003694 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003695 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3696 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3697 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003698 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003699
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003700 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3701 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003702
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003703 Result += "};\n";
3704 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3705 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003706 // Mark this struct as having been generated.
3707 if (!ObjCSynthesizedStructs.insert(CDecl))
3708 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003709}
3710
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003711static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3712 ObjCIvarDecl *IvarDecl, std::string &Result) {
3713 Result += "OBJC_IVAR_$_";
3714 Result += IDecl->getName();
3715 Result += "$";
3716 Result += IvarDecl->getName();
3717}
3718
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003719/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3720/// have been referenced in an ivar access expression.
3721void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3722 std::string &Result) {
3723 // write out ivar offset symbols which have been referenced in an ivar
3724 // access expression.
3725 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3726 if (Ivars.empty())
3727 return;
3728 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3729 e = Ivars.end(); i != e; i++) {
3730 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003731 Result += "\n";
3732 if (LangOpts.MicrosoftExt)
3733 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003734 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003735 if (LangOpts.MicrosoftExt &&
3736 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003737 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3738 Result += "__declspec(dllimport) ";
3739
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003740 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003741 WriteInternalIvarName(CDecl, IvarDecl, Result);
3742 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003743 }
3744}
3745
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003746//===----------------------------------------------------------------------===//
3747// Meta Data Emission
3748//===----------------------------------------------------------------------===//
3749
3750
3751/// RewriteImplementations - This routine rewrites all method implementations
3752/// and emits meta-data.
3753
3754void RewriteModernObjC::RewriteImplementations() {
3755 int ClsDefCount = ClassImplementation.size();
3756 int CatDefCount = CategoryImplementation.size();
3757
3758 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003759 for (int i = 0; i < ClsDefCount; i++) {
3760 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3761 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3762 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003763 assert(false &&
3764 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003765 RewriteImplementationDecl(OIMP);
3766 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003767
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003768 for (int i = 0; i < CatDefCount; i++) {
3769 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3770 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3771 if (CDecl->isImplicitInterfaceDecl())
3772 assert(false &&
3773 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003774 RewriteImplementationDecl(CIMP);
3775 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003776}
3777
3778void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3779 const std::string &Name,
3780 ValueDecl *VD, bool def) {
3781 assert(BlockByRefDeclNo.count(VD) &&
3782 "RewriteByRefString: ByRef decl missing");
3783 if (def)
3784 ResultStr += "struct ";
3785 ResultStr += "__Block_byref_" + Name +
3786 "_" + utostr(BlockByRefDeclNo[VD]) ;
3787}
3788
3789static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3790 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3791 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3792 return false;
3793}
3794
3795std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3796 StringRef funcName,
3797 std::string Tag) {
3798 const FunctionType *AFT = CE->getFunctionType();
3799 QualType RT = AFT->getResultType();
3800 std::string StructRef = "struct " + Tag;
3801 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003802 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003803
3804 BlockDecl *BD = CE->getBlockDecl();
3805
3806 if (isa<FunctionNoProtoType>(AFT)) {
3807 // No user-supplied arguments. Still need to pass in a pointer to the
3808 // block (to reference imported block decl refs).
3809 S += "(" + StructRef + " *__cself)";
3810 } else if (BD->param_empty()) {
3811 S += "(" + StructRef + " *__cself)";
3812 } else {
3813 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3814 assert(FT && "SynthesizeBlockFunc: No function proto");
3815 S += '(';
3816 // first add the implicit argument.
3817 S += StructRef + " *__cself, ";
3818 std::string ParamStr;
3819 for (BlockDecl::param_iterator AI = BD->param_begin(),
3820 E = BD->param_end(); AI != E; ++AI) {
3821 if (AI != BD->param_begin()) S += ", ";
3822 ParamStr = (*AI)->getNameAsString();
3823 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003824 (void)convertBlockPointerToFunctionPointer(QT);
3825 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003826 S += ParamStr;
3827 }
3828 if (FT->isVariadic()) {
3829 if (!BD->param_empty()) S += ", ";
3830 S += "...";
3831 }
3832 S += ')';
3833 }
3834 S += " {\n";
3835
3836 // Create local declarations to avoid rewriting all closure decl ref exprs.
3837 // First, emit a declaration for all "by ref" decls.
3838 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3839 E = BlockByRefDecls.end(); I != E; ++I) {
3840 S += " ";
3841 std::string Name = (*I)->getNameAsString();
3842 std::string TypeString;
3843 RewriteByRefString(TypeString, Name, (*I));
3844 TypeString += " *";
3845 Name = TypeString + Name;
3846 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3847 }
3848 // Next, emit a declaration for all "by copy" declarations.
3849 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3850 E = BlockByCopyDecls.end(); I != E; ++I) {
3851 S += " ";
3852 // Handle nested closure invocation. For example:
3853 //
3854 // void (^myImportedClosure)(void);
3855 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3856 //
3857 // void (^anotherClosure)(void);
3858 // anotherClosure = ^(void) {
3859 // myImportedClosure(); // import and invoke the closure
3860 // };
3861 //
3862 if (isTopLevelBlockPointerType((*I)->getType())) {
3863 RewriteBlockPointerTypeVariable(S, (*I));
3864 S += " = (";
3865 RewriteBlockPointerType(S, (*I)->getType());
3866 S += ")";
3867 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3868 }
3869 else {
3870 std::string Name = (*I)->getNameAsString();
3871 QualType QT = (*I)->getType();
3872 if (HasLocalVariableExternalStorage(*I))
3873 QT = Context->getPointerType(QT);
3874 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3875 S += Name + " = __cself->" +
3876 (*I)->getNameAsString() + "; // bound by copy\n";
3877 }
3878 }
3879 std::string RewrittenStr = RewrittenBlockExprs[CE];
3880 const char *cstr = RewrittenStr.c_str();
3881 while (*cstr++ != '{') ;
3882 S += cstr;
3883 S += "\n";
3884 return S;
3885}
3886
3887std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3888 StringRef funcName,
3889 std::string Tag) {
3890 std::string StructRef = "struct " + Tag;
3891 std::string S = "static void __";
3892
3893 S += funcName;
3894 S += "_block_copy_" + utostr(i);
3895 S += "(" + StructRef;
3896 S += "*dst, " + StructRef;
3897 S += "*src) {";
3898 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3899 E = ImportedBlockDecls.end(); I != E; ++I) {
3900 ValueDecl *VD = (*I);
3901 S += "_Block_object_assign((void*)&dst->";
3902 S += (*I)->getNameAsString();
3903 S += ", (void*)src->";
3904 S += (*I)->getNameAsString();
3905 if (BlockByRefDeclsPtrSet.count((*I)))
3906 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3907 else if (VD->getType()->isBlockPointerType())
3908 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3909 else
3910 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3911 }
3912 S += "}\n";
3913
3914 S += "\nstatic void __";
3915 S += funcName;
3916 S += "_block_dispose_" + utostr(i);
3917 S += "(" + StructRef;
3918 S += "*src) {";
3919 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3920 E = ImportedBlockDecls.end(); I != E; ++I) {
3921 ValueDecl *VD = (*I);
3922 S += "_Block_object_dispose((void*)src->";
3923 S += (*I)->getNameAsString();
3924 if (BlockByRefDeclsPtrSet.count((*I)))
3925 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3926 else if (VD->getType()->isBlockPointerType())
3927 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3928 else
3929 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3930 }
3931 S += "}\n";
3932 return S;
3933}
3934
3935std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3936 std::string Desc) {
3937 std::string S = "\nstruct " + Tag;
3938 std::string Constructor = " " + Tag;
3939
3940 S += " {\n struct __block_impl impl;\n";
3941 S += " struct " + Desc;
3942 S += "* Desc;\n";
3943
3944 Constructor += "(void *fp, "; // Invoke function pointer.
3945 Constructor += "struct " + Desc; // Descriptor pointer.
3946 Constructor += " *desc";
3947
3948 if (BlockDeclRefs.size()) {
3949 // Output all "by copy" declarations.
3950 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3951 E = BlockByCopyDecls.end(); I != E; ++I) {
3952 S += " ";
3953 std::string FieldName = (*I)->getNameAsString();
3954 std::string ArgName = "_" + FieldName;
3955 // Handle nested closure invocation. For example:
3956 //
3957 // void (^myImportedBlock)(void);
3958 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3959 //
3960 // void (^anotherBlock)(void);
3961 // anotherBlock = ^(void) {
3962 // myImportedBlock(); // import and invoke the closure
3963 // };
3964 //
3965 if (isTopLevelBlockPointerType((*I)->getType())) {
3966 S += "struct __block_impl *";
3967 Constructor += ", void *" + ArgName;
3968 } else {
3969 QualType QT = (*I)->getType();
3970 if (HasLocalVariableExternalStorage(*I))
3971 QT = Context->getPointerType(QT);
3972 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3973 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3974 Constructor += ", " + ArgName;
3975 }
3976 S += FieldName + ";\n";
3977 }
3978 // Output all "by ref" declarations.
3979 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3980 E = BlockByRefDecls.end(); I != E; ++I) {
3981 S += " ";
3982 std::string FieldName = (*I)->getNameAsString();
3983 std::string ArgName = "_" + FieldName;
3984 {
3985 std::string TypeString;
3986 RewriteByRefString(TypeString, FieldName, (*I));
3987 TypeString += " *";
3988 FieldName = TypeString + FieldName;
3989 ArgName = TypeString + ArgName;
3990 Constructor += ", " + ArgName;
3991 }
3992 S += FieldName + "; // by ref\n";
3993 }
3994 // Finish writing the constructor.
3995 Constructor += ", int flags=0)";
3996 // Initialize all "by copy" arguments.
3997 bool firsTime = true;
3998 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3999 E = BlockByCopyDecls.end(); I != E; ++I) {
4000 std::string Name = (*I)->getNameAsString();
4001 if (firsTime) {
4002 Constructor += " : ";
4003 firsTime = false;
4004 }
4005 else
4006 Constructor += ", ";
4007 if (isTopLevelBlockPointerType((*I)->getType()))
4008 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4009 else
4010 Constructor += Name + "(_" + Name + ")";
4011 }
4012 // Initialize all "by ref" arguments.
4013 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4014 E = BlockByRefDecls.end(); I != E; ++I) {
4015 std::string Name = (*I)->getNameAsString();
4016 if (firsTime) {
4017 Constructor += " : ";
4018 firsTime = false;
4019 }
4020 else
4021 Constructor += ", ";
4022 Constructor += Name + "(_" + Name + "->__forwarding)";
4023 }
4024
4025 Constructor += " {\n";
4026 if (GlobalVarDecl)
4027 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4028 else
4029 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4030 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4031
4032 Constructor += " Desc = desc;\n";
4033 } else {
4034 // Finish writing the constructor.
4035 Constructor += ", int flags=0) {\n";
4036 if (GlobalVarDecl)
4037 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4038 else
4039 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4040 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4041 Constructor += " Desc = desc;\n";
4042 }
4043 Constructor += " ";
4044 Constructor += "}\n";
4045 S += Constructor;
4046 S += "};\n";
4047 return S;
4048}
4049
4050std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4051 std::string ImplTag, int i,
4052 StringRef FunName,
4053 unsigned hasCopy) {
4054 std::string S = "\nstatic struct " + DescTag;
4055
4056 S += " {\n unsigned long reserved;\n";
4057 S += " unsigned long Block_size;\n";
4058 if (hasCopy) {
4059 S += " void (*copy)(struct ";
4060 S += ImplTag; S += "*, struct ";
4061 S += ImplTag; S += "*);\n";
4062
4063 S += " void (*dispose)(struct ";
4064 S += ImplTag; S += "*);\n";
4065 }
4066 S += "} ";
4067
4068 S += DescTag + "_DATA = { 0, sizeof(struct ";
4069 S += ImplTag + ")";
4070 if (hasCopy) {
4071 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4072 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4073 }
4074 S += "};\n";
4075 return S;
4076}
4077
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004078/// getFunctionSourceLocation - returns start location of a function
4079/// definition. Complication arises when function has declared as
4080/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004081static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4082 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004083 if (FD->isExternC() && !FD->isMain()) {
4084 const DeclContext *DC = FD->getDeclContext();
4085 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4086 // if it is extern "C" {...}, return function decl's own location.
4087 if (!LSD->getRBraceLoc().isValid())
4088 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004089 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004090 if (FD->getStorageClassAsWritten() != SC_None)
4091 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004092 return FD->getTypeSpecStartLoc();
4093}
4094
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004095void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4096 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004097 bool RewriteSC = (GlobalVarDecl &&
4098 !Blocks.empty() &&
4099 GlobalVarDecl->getStorageClass() == SC_Static &&
4100 GlobalVarDecl->getType().getCVRQualifiers());
4101 if (RewriteSC) {
4102 std::string SC(" void __");
4103 SC += GlobalVarDecl->getNameAsString();
4104 SC += "() {}";
4105 InsertText(FunLocStart, SC);
4106 }
4107
4108 // Insert closures that were part of the function.
4109 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4110 CollectBlockDeclRefInfo(Blocks[i]);
4111 // Need to copy-in the inner copied-in variables not actually used in this
4112 // block.
4113 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004114 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004115 ValueDecl *VD = Exp->getDecl();
4116 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004117 if (!VD->hasAttr<BlocksAttr>()) {
4118 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4119 BlockByCopyDeclsPtrSet.insert(VD);
4120 BlockByCopyDecls.push_back(VD);
4121 }
4122 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004123 }
John McCallf4b88a42012-03-10 09:33:50 +00004124
4125 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004126 BlockByRefDeclsPtrSet.insert(VD);
4127 BlockByRefDecls.push_back(VD);
4128 }
John McCallf4b88a42012-03-10 09:33:50 +00004129
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004130 // imported objects in the inner blocks not used in the outer
4131 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004132 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004133 VD->getType()->isBlockPointerType())
4134 ImportedBlockDecls.insert(VD);
4135 }
4136
4137 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4138 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4139
4140 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4141
4142 InsertText(FunLocStart, CI);
4143
4144 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4145
4146 InsertText(FunLocStart, CF);
4147
4148 if (ImportedBlockDecls.size()) {
4149 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4150 InsertText(FunLocStart, HF);
4151 }
4152 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4153 ImportedBlockDecls.size() > 0);
4154 InsertText(FunLocStart, BD);
4155
4156 BlockDeclRefs.clear();
4157 BlockByRefDecls.clear();
4158 BlockByRefDeclsPtrSet.clear();
4159 BlockByCopyDecls.clear();
4160 BlockByCopyDeclsPtrSet.clear();
4161 ImportedBlockDecls.clear();
4162 }
4163 if (RewriteSC) {
4164 // Must insert any 'const/volatile/static here. Since it has been
4165 // removed as result of rewriting of block literals.
4166 std::string SC;
4167 if (GlobalVarDecl->getStorageClass() == SC_Static)
4168 SC = "static ";
4169 if (GlobalVarDecl->getType().isConstQualified())
4170 SC += "const ";
4171 if (GlobalVarDecl->getType().isVolatileQualified())
4172 SC += "volatile ";
4173 if (GlobalVarDecl->getType().isRestrictQualified())
4174 SC += "restrict ";
4175 InsertText(FunLocStart, SC);
4176 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004177 if (GlobalConstructionExp) {
4178 // extra fancy dance for global literal expression.
4179
4180 // Always the latest block expression on the block stack.
4181 std::string Tag = "__";
4182 Tag += FunName;
4183 Tag += "_block_impl_";
4184 Tag += utostr(Blocks.size()-1);
4185 std::string globalBuf = "static ";
4186 globalBuf += Tag; globalBuf += " ";
4187 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004188
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004189 llvm::raw_string_ostream constructorExprBuf(SStr);
4190 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4191 PrintingPolicy(LangOpts));
4192 globalBuf += constructorExprBuf.str();
4193 globalBuf += ";\n";
4194 InsertText(FunLocStart, globalBuf);
4195 GlobalConstructionExp = 0;
4196 }
4197
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004198 Blocks.clear();
4199 InnerDeclRefsCount.clear();
4200 InnerDeclRefs.clear();
4201 RewrittenBlockExprs.clear();
4202}
4203
4204void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004205 SourceLocation FunLocStart =
4206 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4207 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004208 StringRef FuncName = FD->getName();
4209
4210 SynthesizeBlockLiterals(FunLocStart, FuncName);
4211}
4212
4213static void BuildUniqueMethodName(std::string &Name,
4214 ObjCMethodDecl *MD) {
4215 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4216 Name = IFace->getName();
4217 Name += "__" + MD->getSelector().getAsString();
4218 // Convert colons to underscores.
4219 std::string::size_type loc = 0;
4220 while ((loc = Name.find(":", loc)) != std::string::npos)
4221 Name.replace(loc, 1, "_");
4222}
4223
4224void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4225 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4226 //SourceLocation FunLocStart = MD->getLocStart();
4227 SourceLocation FunLocStart = MD->getLocStart();
4228 std::string FuncName;
4229 BuildUniqueMethodName(FuncName, MD);
4230 SynthesizeBlockLiterals(FunLocStart, FuncName);
4231}
4232
4233void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4234 for (Stmt::child_range CI = S->children(); CI; ++CI)
4235 if (*CI) {
4236 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4237 GetBlockDeclRefExprs(CBE->getBody());
4238 else
4239 GetBlockDeclRefExprs(*CI);
4240 }
4241 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004242 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4243 if (DRE->refersToEnclosingLocal()) {
4244 // FIXME: Handle enums.
4245 if (!isa<FunctionDecl>(DRE->getDecl()))
4246 BlockDeclRefs.push_back(DRE);
4247 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4248 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004249 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004250 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004251
4252 return;
4253}
4254
4255void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004256 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004257 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4258 for (Stmt::child_range CI = S->children(); CI; ++CI)
4259 if (*CI) {
4260 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4261 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4262 GetInnerBlockDeclRefExprs(CBE->getBody(),
4263 InnerBlockDeclRefs,
4264 InnerContexts);
4265 }
4266 else
4267 GetInnerBlockDeclRefExprs(*CI,
4268 InnerBlockDeclRefs,
4269 InnerContexts);
4270
4271 }
4272 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004273 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4274 if (DRE->refersToEnclosingLocal()) {
4275 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4276 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4277 InnerBlockDeclRefs.push_back(DRE);
4278 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4279 if (Var->isFunctionOrMethodVarDecl())
4280 ImportedLocalExternalDecls.insert(Var);
4281 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004282 }
4283
4284 return;
4285}
4286
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004287/// convertObjCTypeToCStyleType - This routine converts such objc types
4288/// as qualified objects, and blocks to their closest c/c++ types that
4289/// it can. It returns true if input type was modified.
4290bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4291 QualType oldT = T;
4292 convertBlockPointerToFunctionPointer(T);
4293 if (T->isFunctionPointerType()) {
4294 QualType PointeeTy;
4295 if (const PointerType* PT = T->getAs<PointerType>()) {
4296 PointeeTy = PT->getPointeeType();
4297 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4298 T = convertFunctionTypeOfBlocks(FT);
4299 T = Context->getPointerType(T);
4300 }
4301 }
4302 }
4303
4304 convertToUnqualifiedObjCType(T);
4305 return T != oldT;
4306}
4307
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004308/// convertFunctionTypeOfBlocks - This routine converts a function type
4309/// whose result type may be a block pointer or whose argument type(s)
4310/// might be block pointers to an equivalent function type replacing
4311/// all block pointers to function pointers.
4312QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4313 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4314 // FTP will be null for closures that don't take arguments.
4315 // Generate a funky cast.
4316 SmallVector<QualType, 8> ArgTypes;
4317 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004318 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004319
4320 if (FTP) {
4321 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4322 E = FTP->arg_type_end(); I && (I != E); ++I) {
4323 QualType t = *I;
4324 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004325 if (convertObjCTypeToCStyleType(t))
4326 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004327 ArgTypes.push_back(t);
4328 }
4329 }
4330 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004331 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004332 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4333 else FuncType = QualType(FT, 0);
4334 return FuncType;
4335}
4336
4337Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4338 // Navigate to relevant type information.
4339 const BlockPointerType *CPT = 0;
4340
4341 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4342 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004343 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4344 CPT = MExpr->getType()->getAs<BlockPointerType>();
4345 }
4346 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4347 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4348 }
4349 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4350 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4351 else if (const ConditionalOperator *CEXPR =
4352 dyn_cast<ConditionalOperator>(BlockExp)) {
4353 Expr *LHSExp = CEXPR->getLHS();
4354 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4355 Expr *RHSExp = CEXPR->getRHS();
4356 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4357 Expr *CONDExp = CEXPR->getCond();
4358 ConditionalOperator *CondExpr =
4359 new (Context) ConditionalOperator(CONDExp,
4360 SourceLocation(), cast<Expr>(LHSStmt),
4361 SourceLocation(), cast<Expr>(RHSStmt),
4362 Exp->getType(), VK_RValue, OK_Ordinary);
4363 return CondExpr;
4364 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4365 CPT = IRE->getType()->getAs<BlockPointerType>();
4366 } else if (const PseudoObjectExpr *POE
4367 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4368 CPT = POE->getType()->castAs<BlockPointerType>();
4369 } else {
4370 assert(1 && "RewriteBlockClass: Bad type");
4371 }
4372 assert(CPT && "RewriteBlockClass: Bad type");
4373 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4374 assert(FT && "RewriteBlockClass: Bad type");
4375 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4376 // FTP will be null for closures that don't take arguments.
4377
4378 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4379 SourceLocation(), SourceLocation(),
4380 &Context->Idents.get("__block_impl"));
4381 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4382
4383 // Generate a funky cast.
4384 SmallVector<QualType, 8> ArgTypes;
4385
4386 // Push the block argument type.
4387 ArgTypes.push_back(PtrBlock);
4388 if (FTP) {
4389 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4390 E = FTP->arg_type_end(); I && (I != E); ++I) {
4391 QualType t = *I;
4392 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4393 if (!convertBlockPointerToFunctionPointer(t))
4394 convertToUnqualifiedObjCType(t);
4395 ArgTypes.push_back(t);
4396 }
4397 }
4398 // Now do the pointer to function cast.
4399 QualType PtrToFuncCastType
4400 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4401
4402 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4403
4404 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4405 CK_BitCast,
4406 const_cast<Expr*>(BlockExp));
4407 // Don't forget the parens to enforce the proper binding.
4408 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4409 BlkCast);
4410 //PE->dump();
4411
4412 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4413 SourceLocation(),
4414 &Context->Idents.get("FuncPtr"),
4415 Context->VoidPtrTy, 0,
4416 /*BitWidth=*/0, /*Mutable=*/true,
4417 /*HasInit=*/false);
4418 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4419 FD->getType(), VK_LValue,
4420 OK_Ordinary);
4421
4422
4423 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4424 CK_BitCast, ME);
4425 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4426
4427 SmallVector<Expr*, 8> BlkExprs;
4428 // Add the implicit argument.
4429 BlkExprs.push_back(BlkCast);
4430 // Add the user arguments.
4431 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4432 E = Exp->arg_end(); I != E; ++I) {
4433 BlkExprs.push_back(*I);
4434 }
4435 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4436 BlkExprs.size(),
4437 Exp->getType(), VK_RValue,
4438 SourceLocation());
4439 return CE;
4440}
4441
4442// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004443// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004444// For example:
4445//
4446// int main() {
4447// __block Foo *f;
4448// __block int i;
4449//
4450// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004451// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004452// i = 77;
4453// };
4454//}
John McCallf4b88a42012-03-10 09:33:50 +00004455Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004456 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4457 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004458 ValueDecl *VD = DeclRefExp->getDecl();
4459 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004460
4461 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4462 SourceLocation(),
4463 &Context->Idents.get("__forwarding"),
4464 Context->VoidPtrTy, 0,
4465 /*BitWidth=*/0, /*Mutable=*/true,
4466 /*HasInit=*/false);
4467 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4468 FD, SourceLocation(),
4469 FD->getType(), VK_LValue,
4470 OK_Ordinary);
4471
4472 StringRef Name = VD->getName();
4473 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4474 &Context->Idents.get(Name),
4475 Context->VoidPtrTy, 0,
4476 /*BitWidth=*/0, /*Mutable=*/true,
4477 /*HasInit=*/false);
4478 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4479 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4480
4481
4482
4483 // Need parens to enforce precedence.
4484 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4485 DeclRefExp->getExprLoc(),
4486 ME);
4487 ReplaceStmt(DeclRefExp, PE);
4488 return PE;
4489}
4490
4491// Rewrites the imported local variable V with external storage
4492// (static, extern, etc.) as *V
4493//
4494Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4495 ValueDecl *VD = DRE->getDecl();
4496 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4497 if (!ImportedLocalExternalDecls.count(Var))
4498 return DRE;
4499 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4500 VK_LValue, OK_Ordinary,
4501 DRE->getLocation());
4502 // Need parens to enforce precedence.
4503 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4504 Exp);
4505 ReplaceStmt(DRE, PE);
4506 return PE;
4507}
4508
4509void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4510 SourceLocation LocStart = CE->getLParenLoc();
4511 SourceLocation LocEnd = CE->getRParenLoc();
4512
4513 // Need to avoid trying to rewrite synthesized casts.
4514 if (LocStart.isInvalid())
4515 return;
4516 // Need to avoid trying to rewrite casts contained in macros.
4517 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4518 return;
4519
4520 const char *startBuf = SM->getCharacterData(LocStart);
4521 const char *endBuf = SM->getCharacterData(LocEnd);
4522 QualType QT = CE->getType();
4523 const Type* TypePtr = QT->getAs<Type>();
4524 if (isa<TypeOfExprType>(TypePtr)) {
4525 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4526 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4527 std::string TypeAsString = "(";
4528 RewriteBlockPointerType(TypeAsString, QT);
4529 TypeAsString += ")";
4530 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4531 return;
4532 }
4533 // advance the location to startArgList.
4534 const char *argPtr = startBuf;
4535
4536 while (*argPtr++ && (argPtr < endBuf)) {
4537 switch (*argPtr) {
4538 case '^':
4539 // Replace the '^' with '*'.
4540 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4541 ReplaceText(LocStart, 1, "*");
4542 break;
4543 }
4544 }
4545 return;
4546}
4547
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004548void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4549 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004550 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4551 CastKind != CK_AnyPointerToBlockPointerCast)
4552 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004553
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004554 QualType QT = IC->getType();
4555 (void)convertBlockPointerToFunctionPointer(QT);
4556 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4557 std::string Str = "(";
4558 Str += TypeString;
4559 Str += ")";
4560 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4561
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004562 return;
4563}
4564
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004565void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4566 SourceLocation DeclLoc = FD->getLocation();
4567 unsigned parenCount = 0;
4568
4569 // We have 1 or more arguments that have closure pointers.
4570 const char *startBuf = SM->getCharacterData(DeclLoc);
4571 const char *startArgList = strchr(startBuf, '(');
4572
4573 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4574
4575 parenCount++;
4576 // advance the location to startArgList.
4577 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4578 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4579
4580 const char *argPtr = startArgList;
4581
4582 while (*argPtr++ && parenCount) {
4583 switch (*argPtr) {
4584 case '^':
4585 // Replace the '^' with '*'.
4586 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4587 ReplaceText(DeclLoc, 1, "*");
4588 break;
4589 case '(':
4590 parenCount++;
4591 break;
4592 case ')':
4593 parenCount--;
4594 break;
4595 }
4596 }
4597 return;
4598}
4599
4600bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4601 const FunctionProtoType *FTP;
4602 const PointerType *PT = QT->getAs<PointerType>();
4603 if (PT) {
4604 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4605 } else {
4606 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4607 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4608 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4609 }
4610 if (FTP) {
4611 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4612 E = FTP->arg_type_end(); I != E; ++I)
4613 if (isTopLevelBlockPointerType(*I))
4614 return true;
4615 }
4616 return false;
4617}
4618
4619bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4620 const FunctionProtoType *FTP;
4621 const PointerType *PT = QT->getAs<PointerType>();
4622 if (PT) {
4623 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4624 } else {
4625 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4626 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4627 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4628 }
4629 if (FTP) {
4630 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4631 E = FTP->arg_type_end(); I != E; ++I) {
4632 if ((*I)->isObjCQualifiedIdType())
4633 return true;
4634 if ((*I)->isObjCObjectPointerType() &&
4635 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4636 return true;
4637 }
4638
4639 }
4640 return false;
4641}
4642
4643void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4644 const char *&RParen) {
4645 const char *argPtr = strchr(Name, '(');
4646 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4647
4648 LParen = argPtr; // output the start.
4649 argPtr++; // skip past the left paren.
4650 unsigned parenCount = 1;
4651
4652 while (*argPtr && parenCount) {
4653 switch (*argPtr) {
4654 case '(': parenCount++; break;
4655 case ')': parenCount--; break;
4656 default: break;
4657 }
4658 if (parenCount) argPtr++;
4659 }
4660 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4661 RParen = argPtr; // output the end
4662}
4663
4664void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4665 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4666 RewriteBlockPointerFunctionArgs(FD);
4667 return;
4668 }
4669 // Handle Variables and Typedefs.
4670 SourceLocation DeclLoc = ND->getLocation();
4671 QualType DeclT;
4672 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4673 DeclT = VD->getType();
4674 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4675 DeclT = TDD->getUnderlyingType();
4676 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4677 DeclT = FD->getType();
4678 else
4679 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4680
4681 const char *startBuf = SM->getCharacterData(DeclLoc);
4682 const char *endBuf = startBuf;
4683 // scan backward (from the decl location) for the end of the previous decl.
4684 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4685 startBuf--;
4686 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4687 std::string buf;
4688 unsigned OrigLength=0;
4689 // *startBuf != '^' if we are dealing with a pointer to function that
4690 // may take block argument types (which will be handled below).
4691 if (*startBuf == '^') {
4692 // Replace the '^' with '*', computing a negative offset.
4693 buf = '*';
4694 startBuf++;
4695 OrigLength++;
4696 }
4697 while (*startBuf != ')') {
4698 buf += *startBuf;
4699 startBuf++;
4700 OrigLength++;
4701 }
4702 buf += ')';
4703 OrigLength++;
4704
4705 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4706 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4707 // Replace the '^' with '*' for arguments.
4708 // Replace id<P> with id/*<>*/
4709 DeclLoc = ND->getLocation();
4710 startBuf = SM->getCharacterData(DeclLoc);
4711 const char *argListBegin, *argListEnd;
4712 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4713 while (argListBegin < argListEnd) {
4714 if (*argListBegin == '^')
4715 buf += '*';
4716 else if (*argListBegin == '<') {
4717 buf += "/*";
4718 buf += *argListBegin++;
4719 OrigLength++;;
4720 while (*argListBegin != '>') {
4721 buf += *argListBegin++;
4722 OrigLength++;
4723 }
4724 buf += *argListBegin;
4725 buf += "*/";
4726 }
4727 else
4728 buf += *argListBegin;
4729 argListBegin++;
4730 OrigLength++;
4731 }
4732 buf += ')';
4733 OrigLength++;
4734 }
4735 ReplaceText(Start, OrigLength, buf);
4736
4737 return;
4738}
4739
4740
4741/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4742/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4743/// struct Block_byref_id_object *src) {
4744/// _Block_object_assign (&_dest->object, _src->object,
4745/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4746/// [|BLOCK_FIELD_IS_WEAK]) // object
4747/// _Block_object_assign(&_dest->object, _src->object,
4748/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4749/// [|BLOCK_FIELD_IS_WEAK]) // block
4750/// }
4751/// And:
4752/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4753/// _Block_object_dispose(_src->object,
4754/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4755/// [|BLOCK_FIELD_IS_WEAK]) // object
4756/// _Block_object_dispose(_src->object,
4757/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4758/// [|BLOCK_FIELD_IS_WEAK]) // block
4759/// }
4760
4761std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4762 int flag) {
4763 std::string S;
4764 if (CopyDestroyCache.count(flag))
4765 return S;
4766 CopyDestroyCache.insert(flag);
4767 S = "static void __Block_byref_id_object_copy_";
4768 S += utostr(flag);
4769 S += "(void *dst, void *src) {\n";
4770
4771 // offset into the object pointer is computed as:
4772 // void * + void* + int + int + void* + void *
4773 unsigned IntSize =
4774 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4775 unsigned VoidPtrSize =
4776 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4777
4778 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4779 S += " _Block_object_assign((char*)dst + ";
4780 S += utostr(offset);
4781 S += ", *(void * *) ((char*)src + ";
4782 S += utostr(offset);
4783 S += "), ";
4784 S += utostr(flag);
4785 S += ");\n}\n";
4786
4787 S += "static void __Block_byref_id_object_dispose_";
4788 S += utostr(flag);
4789 S += "(void *src) {\n";
4790 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4791 S += utostr(offset);
4792 S += "), ";
4793 S += utostr(flag);
4794 S += ");\n}\n";
4795 return S;
4796}
4797
4798/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4799/// the declaration into:
4800/// struct __Block_byref_ND {
4801/// void *__isa; // NULL for everything except __weak pointers
4802/// struct __Block_byref_ND *__forwarding;
4803/// int32_t __flags;
4804/// int32_t __size;
4805/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4806/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4807/// typex ND;
4808/// };
4809///
4810/// It then replaces declaration of ND variable with:
4811/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4812/// __size=sizeof(struct __Block_byref_ND),
4813/// ND=initializer-if-any};
4814///
4815///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004816void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4817 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004818 int flag = 0;
4819 int isa = 0;
4820 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4821 if (DeclLoc.isInvalid())
4822 // If type location is missing, it is because of missing type (a warning).
4823 // Use variable's location which is good for this case.
4824 DeclLoc = ND->getLocation();
4825 const char *startBuf = SM->getCharacterData(DeclLoc);
4826 SourceLocation X = ND->getLocEnd();
4827 X = SM->getExpansionLoc(X);
4828 const char *endBuf = SM->getCharacterData(X);
4829 std::string Name(ND->getNameAsString());
4830 std::string ByrefType;
4831 RewriteByRefString(ByrefType, Name, ND, true);
4832 ByrefType += " {\n";
4833 ByrefType += " void *__isa;\n";
4834 RewriteByRefString(ByrefType, Name, ND);
4835 ByrefType += " *__forwarding;\n";
4836 ByrefType += " int __flags;\n";
4837 ByrefType += " int __size;\n";
4838 // Add void *__Block_byref_id_object_copy;
4839 // void *__Block_byref_id_object_dispose; if needed.
4840 QualType Ty = ND->getType();
4841 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4842 if (HasCopyAndDispose) {
4843 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4844 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4845 }
4846
4847 QualType T = Ty;
4848 (void)convertBlockPointerToFunctionPointer(T);
4849 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4850
4851 ByrefType += " " + Name + ";\n";
4852 ByrefType += "};\n";
4853 // Insert this type in global scope. It is needed by helper function.
4854 SourceLocation FunLocStart;
4855 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004856 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004857 else {
4858 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4859 FunLocStart = CurMethodDef->getLocStart();
4860 }
4861 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004862
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004863 if (Ty.isObjCGCWeak()) {
4864 flag |= BLOCK_FIELD_IS_WEAK;
4865 isa = 1;
4866 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004867 if (HasCopyAndDispose) {
4868 flag = BLOCK_BYREF_CALLER;
4869 QualType Ty = ND->getType();
4870 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4871 if (Ty->isBlockPointerType())
4872 flag |= BLOCK_FIELD_IS_BLOCK;
4873 else
4874 flag |= BLOCK_FIELD_IS_OBJECT;
4875 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4876 if (!HF.empty())
4877 InsertText(FunLocStart, HF);
4878 }
4879
4880 // struct __Block_byref_ND ND =
4881 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4882 // initializer-if-any};
4883 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004884 // FIXME. rewriter does not support __block c++ objects which
4885 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00004886 if (hasInit)
4887 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
4888 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
4889 if (CXXDecl && CXXDecl->isDefaultConstructor())
4890 hasInit = false;
4891 }
4892
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004893 unsigned flags = 0;
4894 if (HasCopyAndDispose)
4895 flags |= BLOCK_HAS_COPY_DISPOSE;
4896 Name = ND->getNameAsString();
4897 ByrefType.clear();
4898 RewriteByRefString(ByrefType, Name, ND);
4899 std::string ForwardingCastType("(");
4900 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004901 ByrefType += " " + Name + " = {(void*)";
4902 ByrefType += utostr(isa);
4903 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4904 ByrefType += utostr(flags);
4905 ByrefType += ", ";
4906 ByrefType += "sizeof(";
4907 RewriteByRefString(ByrefType, Name, ND);
4908 ByrefType += ")";
4909 if (HasCopyAndDispose) {
4910 ByrefType += ", __Block_byref_id_object_copy_";
4911 ByrefType += utostr(flag);
4912 ByrefType += ", __Block_byref_id_object_dispose_";
4913 ByrefType += utostr(flag);
4914 }
4915
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004916 if (!firstDecl) {
4917 // In multiple __block declarations, and for all but 1st declaration,
4918 // find location of the separating comma. This would be start location
4919 // where new text is to be inserted.
4920 DeclLoc = ND->getLocation();
4921 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
4922 const char *commaBuf = startDeclBuf;
4923 while (*commaBuf != ',')
4924 commaBuf--;
4925 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
4926 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
4927 startBuf = commaBuf;
4928 }
4929
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004930 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004931 ByrefType += "};\n";
4932 unsigned nameSize = Name.size();
4933 // for block or function pointer declaration. Name is aleady
4934 // part of the declaration.
4935 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4936 nameSize = 1;
4937 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4938 }
4939 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004940 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004941 SourceLocation startLoc;
4942 Expr *E = ND->getInit();
4943 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4944 startLoc = ECE->getLParenLoc();
4945 else
4946 startLoc = E->getLocStart();
4947 startLoc = SM->getExpansionLoc(startLoc);
4948 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004949 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004950
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004951 const char separator = lastDecl ? ';' : ',';
4952 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4953 const char *separatorBuf = strchr(startInitializerBuf, separator);
4954 assert((*separatorBuf == separator) &&
4955 "RewriteByRefVar: can't find ';' or ','");
4956 SourceLocation separatorLoc =
4957 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
4958
4959 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004960 }
4961 return;
4962}
4963
4964void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4965 // Add initializers for any closure decl refs.
4966 GetBlockDeclRefExprs(Exp->getBody());
4967 if (BlockDeclRefs.size()) {
4968 // Unique all "by copy" declarations.
4969 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004970 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004971 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4972 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4973 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4974 }
4975 }
4976 // Unique all "by ref" declarations.
4977 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004978 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004979 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4980 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4981 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4982 }
4983 }
4984 // Find any imported blocks...they will need special attention.
4985 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004986 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004987 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4988 BlockDeclRefs[i]->getType()->isBlockPointerType())
4989 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4990 }
4991}
4992
4993FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4994 IdentifierInfo *ID = &Context->Idents.get(name);
4995 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4996 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4997 SourceLocation(), ID, FType, 0, SC_Extern,
4998 SC_None, false, false);
4999}
5000
5001Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005002 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005003
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005004 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005005
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005006 Blocks.push_back(Exp);
5007
5008 CollectBlockDeclRefInfo(Exp);
5009
5010 // Add inner imported variables now used in current block.
5011 int countOfInnerDecls = 0;
5012 if (!InnerBlockDeclRefs.empty()) {
5013 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005014 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005015 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005016 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005017 // We need to save the copied-in variables in nested
5018 // blocks because it is needed at the end for some of the API generations.
5019 // See SynthesizeBlockLiterals routine.
5020 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5021 BlockDeclRefs.push_back(Exp);
5022 BlockByCopyDeclsPtrSet.insert(VD);
5023 BlockByCopyDecls.push_back(VD);
5024 }
John McCallf4b88a42012-03-10 09:33:50 +00005025 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005026 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5027 BlockDeclRefs.push_back(Exp);
5028 BlockByRefDeclsPtrSet.insert(VD);
5029 BlockByRefDecls.push_back(VD);
5030 }
5031 }
5032 // Find any imported blocks...they will need special attention.
5033 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005034 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005035 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5036 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5037 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5038 }
5039 InnerDeclRefsCount.push_back(countOfInnerDecls);
5040
5041 std::string FuncName;
5042
5043 if (CurFunctionDef)
5044 FuncName = CurFunctionDef->getNameAsString();
5045 else if (CurMethodDef)
5046 BuildUniqueMethodName(FuncName, CurMethodDef);
5047 else if (GlobalVarDecl)
5048 FuncName = std::string(GlobalVarDecl->getNameAsString());
5049
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005050 bool GlobalBlockExpr =
5051 block->getDeclContext()->getRedeclContext()->isFileContext();
5052
5053 if (GlobalBlockExpr && !GlobalVarDecl) {
5054 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5055 GlobalBlockExpr = false;
5056 }
5057
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005058 std::string BlockNumber = utostr(Blocks.size()-1);
5059
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005060 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5061
5062 // Get a pointer to the function type so we can cast appropriately.
5063 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5064 QualType FType = Context->getPointerType(BFT);
5065
5066 FunctionDecl *FD;
5067 Expr *NewRep;
5068
5069 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005070 std::string Tag;
5071
5072 if (GlobalBlockExpr)
5073 Tag = "__global_";
5074 else
5075 Tag = "__";
5076 Tag += FuncName + "_block_impl_" + BlockNumber;
5077
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005078 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005079 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005080 SourceLocation());
5081
5082 SmallVector<Expr*, 4> InitExprs;
5083
5084 // Initialize the block function.
5085 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005086 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5087 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005088 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5089 CK_BitCast, Arg);
5090 InitExprs.push_back(castExpr);
5091
5092 // Initialize the block descriptor.
5093 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5094
5095 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5096 SourceLocation(), SourceLocation(),
5097 &Context->Idents.get(DescData.c_str()),
5098 Context->VoidPtrTy, 0,
5099 SC_Static, SC_None);
5100 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005101 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005102 Context->VoidPtrTy,
5103 VK_LValue,
5104 SourceLocation()),
5105 UO_AddrOf,
5106 Context->getPointerType(Context->VoidPtrTy),
5107 VK_RValue, OK_Ordinary,
5108 SourceLocation());
5109 InitExprs.push_back(DescRefExpr);
5110
5111 // Add initializers for any closure decl refs.
5112 if (BlockDeclRefs.size()) {
5113 Expr *Exp;
5114 // Output all "by copy" declarations.
5115 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5116 E = BlockByCopyDecls.end(); I != E; ++I) {
5117 if (isObjCType((*I)->getType())) {
5118 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5119 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005120 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5121 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005122 if (HasLocalVariableExternalStorage(*I)) {
5123 QualType QT = (*I)->getType();
5124 QT = Context->getPointerType(QT);
5125 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5126 OK_Ordinary, SourceLocation());
5127 }
5128 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5129 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005130 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5131 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005132 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5133 CK_BitCast, Arg);
5134 } else {
5135 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005136 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5137 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005138 if (HasLocalVariableExternalStorage(*I)) {
5139 QualType QT = (*I)->getType();
5140 QT = Context->getPointerType(QT);
5141 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5142 OK_Ordinary, SourceLocation());
5143 }
5144
5145 }
5146 InitExprs.push_back(Exp);
5147 }
5148 // Output all "by ref" declarations.
5149 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5150 E = BlockByRefDecls.end(); I != E; ++I) {
5151 ValueDecl *ND = (*I);
5152 std::string Name(ND->getNameAsString());
5153 std::string RecName;
5154 RewriteByRefString(RecName, Name, ND, true);
5155 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5156 + sizeof("struct"));
5157 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5158 SourceLocation(), SourceLocation(),
5159 II);
5160 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5161 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5162
5163 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005164 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005165 SourceLocation());
5166 bool isNestedCapturedVar = false;
5167 if (block)
5168 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5169 ce = block->capture_end(); ci != ce; ++ci) {
5170 const VarDecl *variable = ci->getVariable();
5171 if (variable == ND && ci->isNested()) {
5172 assert (ci->isByRef() &&
5173 "SynthBlockInitExpr - captured block variable is not byref");
5174 isNestedCapturedVar = true;
5175 break;
5176 }
5177 }
5178 // captured nested byref variable has its address passed. Do not take
5179 // its address again.
5180 if (!isNestedCapturedVar)
5181 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5182 Context->getPointerType(Exp->getType()),
5183 VK_RValue, OK_Ordinary, SourceLocation());
5184 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5185 InitExprs.push_back(Exp);
5186 }
5187 }
5188 if (ImportedBlockDecls.size()) {
5189 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5190 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5191 unsigned IntSize =
5192 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5193 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5194 Context->IntTy, SourceLocation());
5195 InitExprs.push_back(FlagExp);
5196 }
5197 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5198 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005199
5200 if (GlobalBlockExpr) {
5201 assert (GlobalConstructionExp == 0 &&
5202 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5203 GlobalConstructionExp = NewRep;
5204 NewRep = DRE;
5205 }
5206
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005207 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5208 Context->getPointerType(NewRep->getType()),
5209 VK_RValue, OK_Ordinary, SourceLocation());
5210 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5211 NewRep);
5212 BlockDeclRefs.clear();
5213 BlockByRefDecls.clear();
5214 BlockByRefDeclsPtrSet.clear();
5215 BlockByCopyDecls.clear();
5216 BlockByCopyDeclsPtrSet.clear();
5217 ImportedBlockDecls.clear();
5218 return NewRep;
5219}
5220
5221bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5222 if (const ObjCForCollectionStmt * CS =
5223 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5224 return CS->getElement() == DS;
5225 return false;
5226}
5227
5228//===----------------------------------------------------------------------===//
5229// Function Body / Expression rewriting
5230//===----------------------------------------------------------------------===//
5231
5232Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5233 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5234 isa<DoStmt>(S) || isa<ForStmt>(S))
5235 Stmts.push_back(S);
5236 else if (isa<ObjCForCollectionStmt>(S)) {
5237 Stmts.push_back(S);
5238 ObjCBcLabelNo.push_back(++BcLabelCount);
5239 }
5240
5241 // Pseudo-object operations and ivar references need special
5242 // treatment because we're going to recursively rewrite them.
5243 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5244 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5245 return RewritePropertyOrImplicitSetter(PseudoOp);
5246 } else {
5247 return RewritePropertyOrImplicitGetter(PseudoOp);
5248 }
5249 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5250 return RewriteObjCIvarRefExpr(IvarRefExpr);
5251 }
5252
5253 SourceRange OrigStmtRange = S->getSourceRange();
5254
5255 // Perform a bottom up rewrite of all children.
5256 for (Stmt::child_range CI = S->children(); CI; ++CI)
5257 if (*CI) {
5258 Stmt *childStmt = (*CI);
5259 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5260 if (newStmt) {
5261 *CI = newStmt;
5262 }
5263 }
5264
5265 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005266 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005267 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5268 InnerContexts.insert(BE->getBlockDecl());
5269 ImportedLocalExternalDecls.clear();
5270 GetInnerBlockDeclRefExprs(BE->getBody(),
5271 InnerBlockDeclRefs, InnerContexts);
5272 // Rewrite the block body in place.
5273 Stmt *SaveCurrentBody = CurrentBody;
5274 CurrentBody = BE->getBody();
5275 PropParentMap = 0;
5276 // block literal on rhs of a property-dot-sytax assignment
5277 // must be replaced by its synthesize ast so getRewrittenText
5278 // works as expected. In this case, what actually ends up on RHS
5279 // is the blockTranscribed which is the helper function for the
5280 // block literal; as in: self.c = ^() {[ace ARR];};
5281 bool saveDisableReplaceStmt = DisableReplaceStmt;
5282 DisableReplaceStmt = false;
5283 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5284 DisableReplaceStmt = saveDisableReplaceStmt;
5285 CurrentBody = SaveCurrentBody;
5286 PropParentMap = 0;
5287 ImportedLocalExternalDecls.clear();
5288 // Now we snarf the rewritten text and stash it away for later use.
5289 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5290 RewrittenBlockExprs[BE] = Str;
5291
5292 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5293
5294 //blockTranscribed->dump();
5295 ReplaceStmt(S, blockTranscribed);
5296 return blockTranscribed;
5297 }
5298 // Handle specific things.
5299 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5300 return RewriteAtEncode(AtEncode);
5301
5302 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5303 return RewriteAtSelector(AtSelector);
5304
5305 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5306 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005307
5308 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5309 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005310
Patrick Beardeb382ec2012-04-19 00:25:12 +00005311 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5312 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005313
5314 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5315 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005316
5317 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5318 dyn_cast<ObjCDictionaryLiteral>(S))
5319 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005320
5321 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5322#if 0
5323 // Before we rewrite it, put the original message expression in a comment.
5324 SourceLocation startLoc = MessExpr->getLocStart();
5325 SourceLocation endLoc = MessExpr->getLocEnd();
5326
5327 const char *startBuf = SM->getCharacterData(startLoc);
5328 const char *endBuf = SM->getCharacterData(endLoc);
5329
5330 std::string messString;
5331 messString += "// ";
5332 messString.append(startBuf, endBuf-startBuf+1);
5333 messString += "\n";
5334
5335 // FIXME: Missing definition of
5336 // InsertText(clang::SourceLocation, char const*, unsigned int).
5337 // InsertText(startLoc, messString.c_str(), messString.size());
5338 // Tried this, but it didn't work either...
5339 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5340#endif
5341 return RewriteMessageExpr(MessExpr);
5342 }
5343
5344 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5345 return RewriteObjCTryStmt(StmtTry);
5346
5347 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5348 return RewriteObjCSynchronizedStmt(StmtTry);
5349
5350 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5351 return RewriteObjCThrowStmt(StmtThrow);
5352
5353 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5354 return RewriteObjCProtocolExpr(ProtocolExp);
5355
5356 if (ObjCForCollectionStmt *StmtForCollection =
5357 dyn_cast<ObjCForCollectionStmt>(S))
5358 return RewriteObjCForCollectionStmt(StmtForCollection,
5359 OrigStmtRange.getEnd());
5360 if (BreakStmt *StmtBreakStmt =
5361 dyn_cast<BreakStmt>(S))
5362 return RewriteBreakStmt(StmtBreakStmt);
5363 if (ContinueStmt *StmtContinueStmt =
5364 dyn_cast<ContinueStmt>(S))
5365 return RewriteContinueStmt(StmtContinueStmt);
5366
5367 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5368 // and cast exprs.
5369 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5370 // FIXME: What we're doing here is modifying the type-specifier that
5371 // precedes the first Decl. In the future the DeclGroup should have
5372 // a separate type-specifier that we can rewrite.
5373 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5374 // the context of an ObjCForCollectionStmt. For example:
5375 // NSArray *someArray;
5376 // for (id <FooProtocol> index in someArray) ;
5377 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5378 // and it depends on the original text locations/positions.
5379 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5380 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5381
5382 // Blocks rewrite rules.
5383 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5384 DI != DE; ++DI) {
5385 Decl *SD = *DI;
5386 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5387 if (isTopLevelBlockPointerType(ND->getType()))
5388 RewriteBlockPointerDecl(ND);
5389 else if (ND->getType()->isFunctionPointerType())
5390 CheckFunctionPointerDecl(ND->getType(), ND);
5391 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5392 if (VD->hasAttr<BlocksAttr>()) {
5393 static unsigned uniqueByrefDeclCount = 0;
5394 assert(!BlockByRefDeclNo.count(ND) &&
5395 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5396 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005397 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005398 }
5399 else
5400 RewriteTypeOfDecl(VD);
5401 }
5402 }
5403 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5404 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5405 RewriteBlockPointerDecl(TD);
5406 else if (TD->getUnderlyingType()->isFunctionPointerType())
5407 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5408 }
5409 }
5410 }
5411
5412 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5413 RewriteObjCQualifiedInterfaceTypes(CE);
5414
5415 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5416 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5417 assert(!Stmts.empty() && "Statement stack is empty");
5418 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5419 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5420 && "Statement stack mismatch");
5421 Stmts.pop_back();
5422 }
5423 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005424 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5425 ValueDecl *VD = DRE->getDecl();
5426 if (VD->hasAttr<BlocksAttr>())
5427 return RewriteBlockDeclRefExpr(DRE);
5428 if (HasLocalVariableExternalStorage(VD))
5429 return RewriteLocalVariableExternalStorage(DRE);
5430 }
5431
5432 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5433 if (CE->getCallee()->getType()->isBlockPointerType()) {
5434 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5435 ReplaceStmt(S, BlockCall);
5436 return BlockCall;
5437 }
5438 }
5439 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5440 RewriteCastExpr(CE);
5441 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005442 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5443 RewriteImplicitCastObjCExpr(ICE);
5444 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005445#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005446
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005447 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5448 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5449 ICE->getSubExpr(),
5450 SourceLocation());
5451 // Get the new text.
5452 std::string SStr;
5453 llvm::raw_string_ostream Buf(SStr);
5454 Replacement->printPretty(Buf, *Context);
5455 const std::string &Str = Buf.str();
5456
5457 printf("CAST = %s\n", &Str[0]);
5458 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5459 delete S;
5460 return Replacement;
5461 }
5462#endif
5463 // Return this stmt unmodified.
5464 return S;
5465}
5466
5467void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5468 for (RecordDecl::field_iterator i = RD->field_begin(),
5469 e = RD->field_end(); i != e; ++i) {
David Blaikie262bc182012-04-30 02:36:29 +00005470 FieldDecl *FD = &*i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005471 if (isTopLevelBlockPointerType(FD->getType()))
5472 RewriteBlockPointerDecl(FD);
5473 if (FD->getType()->isObjCQualifiedIdType() ||
5474 FD->getType()->isObjCQualifiedInterfaceType())
5475 RewriteObjCQualifiedInterfaceTypes(FD);
5476 }
5477}
5478
5479/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5480/// main file of the input.
5481void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5482 switch (D->getKind()) {
5483 case Decl::Function: {
5484 FunctionDecl *FD = cast<FunctionDecl>(D);
5485 if (FD->isOverloadedOperator())
5486 return;
5487
5488 // Since function prototypes don't have ParmDecl's, we check the function
5489 // prototype. This enables us to rewrite function declarations and
5490 // definitions using the same code.
5491 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5492
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005493 if (!FD->isThisDeclarationADefinition())
5494 break;
5495
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005496 // FIXME: If this should support Obj-C++, support CXXTryStmt
5497 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5498 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005499 CurrentBody = Body;
5500 Body =
5501 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5502 FD->setBody(Body);
5503 CurrentBody = 0;
5504 if (PropParentMap) {
5505 delete PropParentMap;
5506 PropParentMap = 0;
5507 }
5508 // This synthesizes and inserts the block "impl" struct, invoke function,
5509 // and any copy/dispose helper functions.
5510 InsertBlockLiteralsWithinFunction(FD);
5511 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005512 }
5513 break;
5514 }
5515 case Decl::ObjCMethod: {
5516 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5517 if (CompoundStmt *Body = MD->getCompoundBody()) {
5518 CurMethodDef = MD;
5519 CurrentBody = Body;
5520 Body =
5521 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5522 MD->setBody(Body);
5523 CurrentBody = 0;
5524 if (PropParentMap) {
5525 delete PropParentMap;
5526 PropParentMap = 0;
5527 }
5528 InsertBlockLiteralsWithinMethod(MD);
5529 CurMethodDef = 0;
5530 }
5531 break;
5532 }
5533 case Decl::ObjCImplementation: {
5534 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5535 ClassImplementation.push_back(CI);
5536 break;
5537 }
5538 case Decl::ObjCCategoryImpl: {
5539 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5540 CategoryImplementation.push_back(CI);
5541 break;
5542 }
5543 case Decl::Var: {
5544 VarDecl *VD = cast<VarDecl>(D);
5545 RewriteObjCQualifiedInterfaceTypes(VD);
5546 if (isTopLevelBlockPointerType(VD->getType()))
5547 RewriteBlockPointerDecl(VD);
5548 else if (VD->getType()->isFunctionPointerType()) {
5549 CheckFunctionPointerDecl(VD->getType(), VD);
5550 if (VD->getInit()) {
5551 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5552 RewriteCastExpr(CE);
5553 }
5554 }
5555 } else if (VD->getType()->isRecordType()) {
5556 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5557 if (RD->isCompleteDefinition())
5558 RewriteRecordBody(RD);
5559 }
5560 if (VD->getInit()) {
5561 GlobalVarDecl = VD;
5562 CurrentBody = VD->getInit();
5563 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5564 CurrentBody = 0;
5565 if (PropParentMap) {
5566 delete PropParentMap;
5567 PropParentMap = 0;
5568 }
5569 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5570 GlobalVarDecl = 0;
5571
5572 // This is needed for blocks.
5573 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5574 RewriteCastExpr(CE);
5575 }
5576 }
5577 break;
5578 }
5579 case Decl::TypeAlias:
5580 case Decl::Typedef: {
5581 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5582 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5583 RewriteBlockPointerDecl(TD);
5584 else if (TD->getUnderlyingType()->isFunctionPointerType())
5585 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5586 }
5587 break;
5588 }
5589 case Decl::CXXRecord:
5590 case Decl::Record: {
5591 RecordDecl *RD = cast<RecordDecl>(D);
5592 if (RD->isCompleteDefinition())
5593 RewriteRecordBody(RD);
5594 break;
5595 }
5596 default:
5597 break;
5598 }
5599 // Nothing yet.
5600}
5601
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005602/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5603/// protocol reference symbols in the for of:
5604/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5605static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5606 ObjCProtocolDecl *PDecl,
5607 std::string &Result) {
5608 // Also output .objc_protorefs$B section and its meta-data.
5609 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00005610 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005611 Result += "struct _protocol_t *";
5612 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5613 Result += PDecl->getNameAsString();
5614 Result += " = &";
5615 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5616 Result += ";\n";
5617}
5618
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005619void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5620 if (Diags.hasErrorOccurred())
5621 return;
5622
5623 RewriteInclude();
5624
5625 // Here's a great place to add any extra declarations that may be needed.
5626 // Write out meta data for each @protocol(<expr>).
5627 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005628 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005629 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005630 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5631 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005632
5633 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005634 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5635 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5636 // Write struct declaration for the class matching its ivar declarations.
5637 // Note that for modern abi, this is postponed until the end of TU
5638 // because class extensions and the implementation might declare their own
5639 // private ivars.
5640 RewriteInterfaceDecl(CDecl);
5641 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005642
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005643 if (ClassImplementation.size() || CategoryImplementation.size())
5644 RewriteImplementations();
5645
5646 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5647 // we are done.
5648 if (const RewriteBuffer *RewriteBuf =
5649 Rewrite.getRewriteBufferFor(MainFileID)) {
5650 //printf("Changed:\n");
5651 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5652 } else {
5653 llvm::errs() << "No changes\n";
5654 }
5655
5656 if (ClassImplementation.size() || CategoryImplementation.size() ||
5657 ProtocolExprDecls.size()) {
5658 // Rewrite Objective-c meta data*
5659 std::string ResultStr;
5660 RewriteMetaDataIntoBuffer(ResultStr);
5661 // Emit metadata.
5662 *OutFile << ResultStr;
5663 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005664 // Emit ImageInfo;
5665 {
5666 std::string ResultStr;
5667 WriteImageInfo(ResultStr);
5668 *OutFile << ResultStr;
5669 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005670 OutFile->flush();
5671}
5672
5673void RewriteModernObjC::Initialize(ASTContext &context) {
5674 InitializeCommon(context);
5675
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005676 Preamble += "#ifndef __OBJC2__\n";
5677 Preamble += "#define __OBJC2__\n";
5678 Preamble += "#endif\n";
5679
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005680 // declaring objc_selector outside the parameter list removes a silly
5681 // scope related warning...
5682 if (IsHeader)
5683 Preamble = "#pragma once\n";
5684 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005685 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5686 Preamble += "\n\tstruct objc_object *superClass; ";
5687 // Add a constructor for creating temporary objects.
5688 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5689 Preamble += ": object(o), superClass(s) {} ";
5690 Preamble += "\n};\n";
5691
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005692 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005693 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005694 // These are currently generated.
5695 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005696 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005697 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005698 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5699 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005700 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005701 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005702 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5703 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005704 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005705
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005706 // These need be generated for performance. Currently they are not,
5707 // using API calls instead.
5708 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5709 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5710 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5711
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005712 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005713 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5714 Preamble += "typedef struct objc_object Protocol;\n";
5715 Preamble += "#define _REWRITER_typedef_Protocol\n";
5716 Preamble += "#endif\n";
5717 if (LangOpts.MicrosoftExt) {
5718 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5719 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005720 }
5721 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005722 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005723
5724 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5725 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5726 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5727 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5728 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5729
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005730 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5731 Preamble += "(const char *);\n";
5732 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5733 Preamble += "(struct objc_class *);\n";
5734 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5735 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005736 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005737 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005738 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5739 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005740 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5741 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5742 Preamble += "struct __objcFastEnumerationState {\n\t";
5743 Preamble += "unsigned long state;\n\t";
5744 Preamble += "void **itemsPtr;\n\t";
5745 Preamble += "unsigned long *mutationsPtr;\n\t";
5746 Preamble += "unsigned long extra[5];\n};\n";
5747 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5748 Preamble += "#define __FASTENUMERATIONSTATE\n";
5749 Preamble += "#endif\n";
5750 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5751 Preamble += "struct __NSConstantStringImpl {\n";
5752 Preamble += " int *isa;\n";
5753 Preamble += " int flags;\n";
5754 Preamble += " char *str;\n";
5755 Preamble += " long length;\n";
5756 Preamble += "};\n";
5757 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5758 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5759 Preamble += "#else\n";
5760 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5761 Preamble += "#endif\n";
5762 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5763 Preamble += "#endif\n";
5764 // Blocks preamble.
5765 Preamble += "#ifndef BLOCK_IMPL\n";
5766 Preamble += "#define BLOCK_IMPL\n";
5767 Preamble += "struct __block_impl {\n";
5768 Preamble += " void *isa;\n";
5769 Preamble += " int Flags;\n";
5770 Preamble += " int Reserved;\n";
5771 Preamble += " void *FuncPtr;\n";
5772 Preamble += "};\n";
5773 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5774 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5775 Preamble += "extern \"C\" __declspec(dllexport) "
5776 "void _Block_object_assign(void *, const void *, const int);\n";
5777 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5778 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5779 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5780 Preamble += "#else\n";
5781 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5782 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5783 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5784 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5785 Preamble += "#endif\n";
5786 Preamble += "#endif\n";
5787 if (LangOpts.MicrosoftExt) {
5788 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5789 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5790 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5791 Preamble += "#define __attribute__(X)\n";
5792 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005793 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005794 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005795 Preamble += "#endif\n";
5796 Preamble += "#ifndef __block\n";
5797 Preamble += "#define __block\n";
5798 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005799 }
5800 else {
5801 Preamble += "#define __block\n";
5802 Preamble += "#define __weak\n";
5803 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005804
5805 // Declarations required for modern objective-c array and dictionary literals.
5806 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005807 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005808 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005809 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005810 Preamble += "\tva_list marker;\n";
5811 Preamble += "\tva_start(marker, count);\n";
5812 Preamble += "\tarr = new void *[count];\n";
5813 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5814 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5815 Preamble += "\tva_end( marker );\n";
5816 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00005817 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005818 Preamble += "\tdelete[] arr;\n";
5819 Preamble += " }\n";
5820 Preamble += "};\n";
5821
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005822 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5823 // as this avoids warning in any 64bit/32bit compilation model.
5824 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5825}
5826
5827/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5828/// ivar offset.
5829void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5830 std::string &Result) {
5831 if (ivar->isBitField()) {
5832 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5833 // place all bitfields at offset 0.
5834 Result += "0";
5835 } else {
5836 Result += "__OFFSETOFIVAR__(struct ";
5837 Result += ivar->getContainingInterface()->getNameAsString();
5838 if (LangOpts.MicrosoftExt)
5839 Result += "_IMPL";
5840 Result += ", ";
5841 Result += ivar->getNameAsString();
5842 Result += ")";
5843 }
5844}
5845
5846/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5847/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005848/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005849/// char *attributes;
5850/// }
5851
5852/// struct _prop_list_t {
5853/// uint32_t entsize; // sizeof(struct _prop_t)
5854/// uint32_t count_of_properties;
5855/// struct _prop_t prop_list[count_of_properties];
5856/// }
5857
5858/// struct _protocol_t;
5859
5860/// struct _protocol_list_t {
5861/// long protocol_count; // Note, this is 32/64 bit
5862/// struct _protocol_t * protocol_list[protocol_count];
5863/// }
5864
5865/// struct _objc_method {
5866/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005867/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005868/// char *_imp;
5869/// }
5870
5871/// struct _method_list_t {
5872/// uint32_t entsize; // sizeof(struct _objc_method)
5873/// uint32_t method_count;
5874/// struct _objc_method method_list[method_count];
5875/// }
5876
5877/// struct _protocol_t {
5878/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005879/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005880/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005881/// const struct method_list_t *instance_methods;
5882/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005883/// const struct method_list_t *optionalInstanceMethods;
5884/// const struct method_list_t *optionalClassMethods;
5885/// const struct _prop_list_t * properties;
5886/// const uint32_t size; // sizeof(struct _protocol_t)
5887/// const uint32_t flags; // = 0
5888/// const char ** extendedMethodTypes;
5889/// }
5890
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005891/// struct _ivar_t {
5892/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005893/// const char *name;
5894/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005895/// uint32_t alignment;
5896/// uint32_t size;
5897/// }
5898
5899/// struct _ivar_list_t {
5900/// uint32 entsize; // sizeof(struct _ivar_t)
5901/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005902/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005903/// }
5904
5905/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005906/// uint32_t flags;
5907/// uint32_t instanceStart;
5908/// uint32_t instanceSize;
5909/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005910/// const uint8_t *ivarLayout;
5911/// const char *name;
5912/// const struct _method_list_t *baseMethods;
5913/// const struct _protocol_list_t *baseProtocols;
5914/// const struct _ivar_list_t *ivars;
5915/// const uint8_t *weakIvarLayout;
5916/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005917/// }
5918
5919/// struct _class_t {
5920/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005921/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005922/// void *cache;
5923/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005924/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005925/// }
5926
5927/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005928/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005929/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005930/// const struct _method_list_t *instance_methods;
5931/// const struct _method_list_t *class_methods;
5932/// const struct _protocol_list_t *protocols;
5933/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005934/// }
5935
5936/// MessageRefTy - LLVM for:
5937/// struct _message_ref_t {
5938/// IMP messenger;
5939/// SEL name;
5940/// };
5941
5942/// SuperMessageRefTy - LLVM for:
5943/// struct _super_message_ref_t {
5944/// SUPER_IMP messenger;
5945/// SEL name;
5946/// };
5947
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005948static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005949 static bool meta_data_declared = false;
5950 if (meta_data_declared)
5951 return;
5952
5953 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005954 Result += "\tconst char *name;\n";
5955 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005956 Result += "};\n";
5957
5958 Result += "\nstruct _protocol_t;\n";
5959
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005960 Result += "\nstruct _objc_method {\n";
5961 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005962 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005963 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005964 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005965
5966 Result += "\nstruct _protocol_t {\n";
5967 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005968 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005969 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005970 Result += "\tconst struct method_list_t *instance_methods;\n";
5971 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005972 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5973 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5974 Result += "\tconst struct _prop_list_t * properties;\n";
5975 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5976 Result += "\tconst unsigned int flags; // = 0\n";
5977 Result += "\tconst char ** extendedMethodTypes;\n";
5978 Result += "};\n";
5979
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005980 Result += "\nstruct _ivar_t {\n";
5981 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005982 Result += "\tconst char *name;\n";
5983 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005984 Result += "\tunsigned int alignment;\n";
5985 Result += "\tunsigned int size;\n";
5986 Result += "};\n";
5987
5988 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005989 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005990 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005991 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005992 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5993 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005994 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005995 Result += "\tconst unsigned char *ivarLayout;\n";
5996 Result += "\tconst char *name;\n";
5997 Result += "\tconst struct _method_list_t *baseMethods;\n";
5998 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5999 Result += "\tconst struct _ivar_list_t *ivars;\n";
6000 Result += "\tconst unsigned char *weakIvarLayout;\n";
6001 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006002 Result += "};\n";
6003
6004 Result += "\nstruct _class_t {\n";
6005 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006006 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006007 Result += "\tvoid *cache;\n";
6008 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006009 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006010 Result += "};\n";
6011
6012 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006013 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006014 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006015 Result += "\tconst struct _method_list_t *instance_methods;\n";
6016 Result += "\tconst struct _method_list_t *class_methods;\n";
6017 Result += "\tconst struct _protocol_list_t *protocols;\n";
6018 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006019 Result += "};\n";
6020
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006021 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006022 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006023 meta_data_declared = true;
6024}
6025
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006026static void Write_protocol_list_t_TypeDecl(std::string &Result,
6027 long super_protocol_count) {
6028 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6029 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6030 Result += "\tstruct _protocol_t *super_protocols[";
6031 Result += utostr(super_protocol_count); Result += "];\n";
6032 Result += "}";
6033}
6034
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006035static void Write_method_list_t_TypeDecl(std::string &Result,
6036 unsigned int method_count) {
6037 Result += "struct /*_method_list_t*/"; Result += " {\n";
6038 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6039 Result += "\tunsigned int method_count;\n";
6040 Result += "\tstruct _objc_method method_list[";
6041 Result += utostr(method_count); Result += "];\n";
6042 Result += "}";
6043}
6044
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006045static void Write__prop_list_t_TypeDecl(std::string &Result,
6046 unsigned int property_count) {
6047 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6048 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6049 Result += "\tunsigned int count_of_properties;\n";
6050 Result += "\tstruct _prop_t prop_list[";
6051 Result += utostr(property_count); Result += "];\n";
6052 Result += "}";
6053}
6054
Fariborz Jahanianae932952012-02-10 20:47:10 +00006055static void Write__ivar_list_t_TypeDecl(std::string &Result,
6056 unsigned int ivar_count) {
6057 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6058 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6059 Result += "\tunsigned int count;\n";
6060 Result += "\tstruct _ivar_t ivar_list[";
6061 Result += utostr(ivar_count); Result += "];\n";
6062 Result += "}";
6063}
6064
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006065static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6066 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6067 StringRef VarName,
6068 StringRef ProtocolName) {
6069 if (SuperProtocols.size() > 0) {
6070 Result += "\nstatic ";
6071 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6072 Result += " "; Result += VarName;
6073 Result += ProtocolName;
6074 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6075 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6076 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6077 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6078 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6079 Result += SuperPD->getNameAsString();
6080 if (i == e-1)
6081 Result += "\n};\n";
6082 else
6083 Result += ",\n";
6084 }
6085 }
6086}
6087
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006088static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6089 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006090 ArrayRef<ObjCMethodDecl *> Methods,
6091 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006092 StringRef TopLevelDeclName,
6093 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006094 if (Methods.size() > 0) {
6095 Result += "\nstatic ";
6096 Write_method_list_t_TypeDecl(Result, Methods.size());
6097 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006098 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006099 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6100 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6101 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6102 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6103 ObjCMethodDecl *MD = Methods[i];
6104 if (i == 0)
6105 Result += "\t{{(struct objc_selector *)\"";
6106 else
6107 Result += "\t{(struct objc_selector *)\"";
6108 Result += (MD)->getSelector().getAsString(); Result += "\"";
6109 Result += ", ";
6110 std::string MethodTypeString;
6111 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6112 Result += "\""; Result += MethodTypeString; Result += "\"";
6113 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006114 if (!MethodImpl)
6115 Result += "0";
6116 else {
6117 Result += "(void *)";
6118 Result += RewriteObj.MethodInternalNames[MD];
6119 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006120 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006121 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006122 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006123 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006124 }
6125 Result += "};\n";
6126 }
6127}
6128
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006129static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006130 ASTContext *Context, std::string &Result,
6131 ArrayRef<ObjCPropertyDecl *> Properties,
6132 const Decl *Container,
6133 StringRef VarName,
6134 StringRef ProtocolName) {
6135 if (Properties.size() > 0) {
6136 Result += "\nstatic ";
6137 Write__prop_list_t_TypeDecl(Result, Properties.size());
6138 Result += " "; Result += VarName;
6139 Result += ProtocolName;
6140 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6141 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6142 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6143 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6144 ObjCPropertyDecl *PropDecl = Properties[i];
6145 if (i == 0)
6146 Result += "\t{{\"";
6147 else
6148 Result += "\t{\"";
6149 Result += PropDecl->getName(); Result += "\",";
6150 std::string PropertyTypeString, QuotePropertyTypeString;
6151 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6152 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6153 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6154 if (i == e-1)
6155 Result += "}}\n";
6156 else
6157 Result += "},\n";
6158 }
6159 Result += "};\n";
6160 }
6161}
6162
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006163// Metadata flags
6164enum MetaDataDlags {
6165 CLS = 0x0,
6166 CLS_META = 0x1,
6167 CLS_ROOT = 0x2,
6168 OBJC2_CLS_HIDDEN = 0x10,
6169 CLS_EXCEPTION = 0x20,
6170
6171 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6172 CLS_HAS_IVAR_RELEASER = 0x40,
6173 /// class was compiled with -fobjc-arr
6174 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6175};
6176
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006177static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6178 unsigned int flags,
6179 const std::string &InstanceStart,
6180 const std::string &InstanceSize,
6181 ArrayRef<ObjCMethodDecl *>baseMethods,
6182 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6183 ArrayRef<ObjCIvarDecl *>ivars,
6184 ArrayRef<ObjCPropertyDecl *>Properties,
6185 StringRef VarName,
6186 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006187 Result += "\nstatic struct _class_ro_t ";
6188 Result += VarName; Result += ClassName;
6189 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6190 Result += "\t";
6191 Result += llvm::utostr(flags); Result += ", ";
6192 Result += InstanceStart; Result += ", ";
6193 Result += InstanceSize; Result += ", \n";
6194 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006195 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6196 if (Triple.getArch() == llvm::Triple::x86_64)
6197 // uint32_t const reserved; // only when building for 64bit targets
6198 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006199 // const uint8_t * const ivarLayout;
6200 Result += "0, \n\t";
6201 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006202 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006203 if (baseMethods.size() > 0) {
6204 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006205 if (metaclass)
6206 Result += "_OBJC_$_CLASS_METHODS_";
6207 else
6208 Result += "_OBJC_$_INSTANCE_METHODS_";
6209 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006210 Result += ",\n\t";
6211 }
6212 else
6213 Result += "0, \n\t";
6214
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006215 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006216 Result += "(const struct _objc_protocol_list *)&";
6217 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6218 Result += ",\n\t";
6219 }
6220 else
6221 Result += "0, \n\t";
6222
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006223 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006224 Result += "(const struct _ivar_list_t *)&";
6225 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6226 Result += ",\n\t";
6227 }
6228 else
6229 Result += "0, \n\t";
6230
6231 // weakIvarLayout
6232 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006233 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006234 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006235 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006236 Result += ",\n";
6237 }
6238 else
6239 Result += "0, \n";
6240
6241 Result += "};\n";
6242}
6243
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006244static void Write_class_t(ASTContext *Context, std::string &Result,
6245 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006246 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6247 bool rootClass = (!CDecl->getSuperClass());
6248 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006249
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006250 if (!rootClass) {
6251 // Find the Root class
6252 RootClass = CDecl->getSuperClass();
6253 while (RootClass->getSuperClass()) {
6254 RootClass = RootClass->getSuperClass();
6255 }
6256 }
6257
6258 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006259 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006260 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006261 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006262 if (CDecl->getImplementation())
6263 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006264 else
6265 Result += "__declspec(dllimport) ";
6266
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006267 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006268 Result += CDecl->getNameAsString();
6269 Result += ";\n";
6270 }
6271 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006272 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006273 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006274 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006275 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006276 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006277 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006278 else
6279 Result += "__declspec(dllimport) ";
6280
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006281 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006282 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006283 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006284 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006285
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006286 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006287 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006288 if (RootClass->getImplementation())
6289 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006290 else
6291 Result += "__declspec(dllimport) ";
6292
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006293 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006294 Result += VarName;
6295 Result += RootClass->getNameAsString();
6296 Result += ";\n";
6297 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006298 }
6299
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006300 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6301 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006302 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6303 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006304 if (metaclass) {
6305 if (!rootClass) {
6306 Result += "0, // &"; Result += VarName;
6307 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006308 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006309 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006310 Result += CDecl->getSuperClass()->getNameAsString();
6311 Result += ",\n\t";
6312 }
6313 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006314 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006315 Result += CDecl->getNameAsString();
6316 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006317 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006318 Result += ",\n\t";
6319 }
6320 }
6321 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006322 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006323 Result += CDecl->getNameAsString();
6324 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006325 if (!rootClass) {
6326 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006327 Result += CDecl->getSuperClass()->getNameAsString();
6328 Result += ",\n\t";
6329 }
6330 else
6331 Result += "0,\n\t";
6332 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006333 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6334 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6335 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006336 Result += "&_OBJC_METACLASS_RO_$_";
6337 else
6338 Result += "&_OBJC_CLASS_RO_$_";
6339 Result += CDecl->getNameAsString();
6340 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006341
6342 // Add static function to initialize some of the meta-data fields.
6343 // avoid doing it twice.
6344 if (metaclass)
6345 return;
6346
6347 const ObjCInterfaceDecl *SuperClass =
6348 rootClass ? CDecl : CDecl->getSuperClass();
6349
6350 Result += "static void OBJC_CLASS_SETUP_$_";
6351 Result += CDecl->getNameAsString();
6352 Result += "(void ) {\n";
6353 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6354 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006355 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006356
6357 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006358 Result += ".superclass = ";
6359 if (rootClass)
6360 Result += "&OBJC_CLASS_$_";
6361 else
6362 Result += "&OBJC_METACLASS_$_";
6363
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006364 Result += SuperClass->getNameAsString(); Result += ";\n";
6365
6366 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6367 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6368
6369 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6370 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6371 Result += CDecl->getNameAsString(); Result += ";\n";
6372
6373 if (!rootClass) {
6374 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6375 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6376 Result += SuperClass->getNameAsString(); Result += ";\n";
6377 }
6378
6379 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6380 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6381 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006382}
6383
Fariborz Jahanian61186122012-02-17 18:40:41 +00006384static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6385 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006386 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006387 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006388 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6389 ArrayRef<ObjCMethodDecl *> ClassMethods,
6390 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6391 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006392 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006393 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006394 // must declare an extern class object in case this class is not implemented
6395 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006396 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006397 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006398 if (ClassDecl->getImplementation())
6399 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006400 else
6401 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006402
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006403 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006404 Result += "OBJC_CLASS_$_"; Result += ClassName;
6405 Result += ";\n";
6406
Fariborz Jahanian61186122012-02-17 18:40:41 +00006407 Result += "\nstatic struct _category_t ";
6408 Result += "_OBJC_$_CATEGORY_";
6409 Result += ClassName; Result += "_$_"; Result += CatName;
6410 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6411 Result += "{\n";
6412 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006413 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006414 Result += ",\n";
6415 if (InstanceMethods.size() > 0) {
6416 Result += "\t(const struct _method_list_t *)&";
6417 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6418 Result += ClassName; Result += "_$_"; Result += CatName;
6419 Result += ",\n";
6420 }
6421 else
6422 Result += "\t0,\n";
6423
6424 if (ClassMethods.size() > 0) {
6425 Result += "\t(const struct _method_list_t *)&";
6426 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6427 Result += ClassName; Result += "_$_"; Result += CatName;
6428 Result += ",\n";
6429 }
6430 else
6431 Result += "\t0,\n";
6432
6433 if (RefedProtocols.size() > 0) {
6434 Result += "\t(const struct _protocol_list_t *)&";
6435 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6436 Result += ClassName; Result += "_$_"; Result += CatName;
6437 Result += ",\n";
6438 }
6439 else
6440 Result += "\t0,\n";
6441
6442 if (ClassProperties.size() > 0) {
6443 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6444 Result += ClassName; Result += "_$_"; Result += CatName;
6445 Result += ",\n";
6446 }
6447 else
6448 Result += "\t0,\n";
6449
6450 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006451
6452 // Add static function to initialize the class pointer in the category structure.
6453 Result += "static void OBJC_CATEGORY_SETUP_$_";
6454 Result += ClassDecl->getNameAsString();
6455 Result += "_$_";
6456 Result += CatName;
6457 Result += "(void ) {\n";
6458 Result += "\t_OBJC_$_CATEGORY_";
6459 Result += ClassDecl->getNameAsString();
6460 Result += "_$_";
6461 Result += CatName;
6462 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6463 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006464}
6465
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006466static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6467 ASTContext *Context, std::string &Result,
6468 ArrayRef<ObjCMethodDecl *> Methods,
6469 StringRef VarName,
6470 StringRef ProtocolName) {
6471 if (Methods.size() == 0)
6472 return;
6473
6474 Result += "\nstatic const char *";
6475 Result += VarName; Result += ProtocolName;
6476 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6477 Result += "{\n";
6478 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6479 ObjCMethodDecl *MD = Methods[i];
6480 std::string MethodTypeString, QuoteMethodTypeString;
6481 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6482 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6483 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6484 if (i == e-1)
6485 Result += "\n};\n";
6486 else {
6487 Result += ",\n";
6488 }
6489 }
6490}
6491
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006492static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6493 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006494 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006495 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006496 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006497 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6498 // this is what happens:
6499 /**
6500 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6501 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6502 Class->getVisibility() == HiddenVisibility)
6503 Visibility shoud be: HiddenVisibility;
6504 else
6505 Visibility shoud be: DefaultVisibility;
6506 */
6507
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006508 Result += "\n";
6509 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6510 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006511 if (Context->getLangOpts().MicrosoftExt)
6512 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6513
6514 if (!Context->getLangOpts().MicrosoftExt ||
6515 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006516 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006517 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006518 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006519 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006520 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006521 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6522 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006523 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6524 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006525 }
6526}
6527
Fariborz Jahanianae932952012-02-10 20:47:10 +00006528static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6529 ASTContext *Context, std::string &Result,
6530 ArrayRef<ObjCIvarDecl *> Ivars,
6531 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006532 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006533 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006534 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006535
Fariborz Jahanianae932952012-02-10 20:47:10 +00006536 Result += "\nstatic ";
6537 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6538 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006539 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006540 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6541 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6542 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6543 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6544 ObjCIvarDecl *IvarDecl = Ivars[i];
6545 if (i == 0)
6546 Result += "\t{{";
6547 else
6548 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006549 Result += "(unsigned long int *)&";
6550 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006551 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006552
6553 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6554 std::string IvarTypeString, QuoteIvarTypeString;
6555 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6556 IvarDecl);
6557 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6558 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6559
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006560 // FIXME. this alignment represents the host alignment and need be changed to
6561 // represent the target alignment.
6562 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6563 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006564 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006565 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6566 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006567 if (i == e-1)
6568 Result += "}}\n";
6569 else
6570 Result += "},\n";
6571 }
6572 Result += "};\n";
6573 }
6574}
6575
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006576/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006577void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6578 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006579
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006580 // Do not synthesize the protocol more than once.
6581 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6582 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006583 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006584
6585 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6586 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006587 // Must write out all protocol definitions in current qualifier list,
6588 // and in their nested qualifiers before writing out current definition.
6589 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6590 E = PDecl->protocol_end(); I != E; ++I)
6591 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006592
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006593 // Construct method lists.
6594 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6595 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6596 for (ObjCProtocolDecl::instmeth_iterator
6597 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6598 I != E; ++I) {
6599 ObjCMethodDecl *MD = *I;
6600 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6601 OptInstanceMethods.push_back(MD);
6602 } else {
6603 InstanceMethods.push_back(MD);
6604 }
6605 }
6606
6607 for (ObjCProtocolDecl::classmeth_iterator
6608 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6609 I != E; ++I) {
6610 ObjCMethodDecl *MD = *I;
6611 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6612 OptClassMethods.push_back(MD);
6613 } else {
6614 ClassMethods.push_back(MD);
6615 }
6616 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006617 std::vector<ObjCMethodDecl *> AllMethods;
6618 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6619 AllMethods.push_back(InstanceMethods[i]);
6620 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6621 AllMethods.push_back(ClassMethods[i]);
6622 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6623 AllMethods.push_back(OptInstanceMethods[i]);
6624 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6625 AllMethods.push_back(OptClassMethods[i]);
6626
6627 Write__extendedMethodTypes_initializer(*this, Context, Result,
6628 AllMethods,
6629 "_OBJC_PROTOCOL_METHOD_TYPES_",
6630 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006631 // Protocol's super protocol list
6632 std::vector<ObjCProtocolDecl *> SuperProtocols;
6633 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6634 E = PDecl->protocol_end(); I != E; ++I)
6635 SuperProtocols.push_back(*I);
6636
6637 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6638 "_OBJC_PROTOCOL_REFS_",
6639 PDecl->getNameAsString());
6640
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006641 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006642 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006643 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006644
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006645 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006646 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006647 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006648
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006649 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006650 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006651 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006652
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006653 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006654 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006655 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006656
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006657 // Protocol's property metadata.
6658 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6659 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6660 E = PDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006661 ProtocolProperties.push_back(&*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006662
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006663 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006664 /* Container */0,
6665 "_OBJC_PROTOCOL_PROPERTIES_",
6666 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006667
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006668 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006669 Result += "\n";
6670 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006671 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006672 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006673 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006674 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6675 Result += "\t0,\n"; // id is; is null
6676 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006677 if (SuperProtocols.size() > 0) {
6678 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6679 Result += PDecl->getNameAsString(); Result += ",\n";
6680 }
6681 else
6682 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006683 if (InstanceMethods.size() > 0) {
6684 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6685 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006686 }
6687 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006688 Result += "\t0,\n";
6689
6690 if (ClassMethods.size() > 0) {
6691 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6692 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006693 }
6694 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006695 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006696
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006697 if (OptInstanceMethods.size() > 0) {
6698 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6699 Result += PDecl->getNameAsString(); Result += ",\n";
6700 }
6701 else
6702 Result += "\t0,\n";
6703
6704 if (OptClassMethods.size() > 0) {
6705 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6706 Result += PDecl->getNameAsString(); Result += ",\n";
6707 }
6708 else
6709 Result += "\t0,\n";
6710
6711 if (ProtocolProperties.size() > 0) {
6712 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6713 Result += PDecl->getNameAsString(); Result += ",\n";
6714 }
6715 else
6716 Result += "\t0,\n";
6717
6718 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6719 Result += "\t0,\n";
6720
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006721 if (AllMethods.size() > 0) {
6722 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6723 Result += PDecl->getNameAsString();
6724 Result += "\n};\n";
6725 }
6726 else
6727 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006728
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006729 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006730 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006731 Result += "struct _protocol_t *";
6732 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6733 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6734 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006735
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006736 // Mark this protocol as having been generated.
6737 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6738 llvm_unreachable("protocol already synthesized");
6739
6740}
6741
6742void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6743 const ObjCList<ObjCProtocolDecl> &Protocols,
6744 StringRef prefix, StringRef ClassName,
6745 std::string &Result) {
6746 if (Protocols.empty()) return;
6747
6748 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006749 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006750
6751 // Output the top lovel protocol meta-data for the class.
6752 /* struct _objc_protocol_list {
6753 struct _objc_protocol_list *next;
6754 int protocol_count;
6755 struct _objc_protocol *class_protocols[];
6756 }
6757 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006758 Result += "\n";
6759 if (LangOpts.MicrosoftExt)
6760 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6761 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006762 Result += "\tstruct _objc_protocol_list *next;\n";
6763 Result += "\tint protocol_count;\n";
6764 Result += "\tstruct _objc_protocol *class_protocols[";
6765 Result += utostr(Protocols.size());
6766 Result += "];\n} _OBJC_";
6767 Result += prefix;
6768 Result += "_PROTOCOLS_";
6769 Result += ClassName;
6770 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6771 "{\n\t0, ";
6772 Result += utostr(Protocols.size());
6773 Result += "\n";
6774
6775 Result += "\t,{&_OBJC_PROTOCOL_";
6776 Result += Protocols[0]->getNameAsString();
6777 Result += " \n";
6778
6779 for (unsigned i = 1; i != Protocols.size(); i++) {
6780 Result += "\t ,&_OBJC_PROTOCOL_";
6781 Result += Protocols[i]->getNameAsString();
6782 Result += "\n";
6783 }
6784 Result += "\t }\n};\n";
6785}
6786
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006787/// hasObjCExceptionAttribute - Return true if this class or any super
6788/// class has the __objc_exception__ attribute.
6789/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6790static bool hasObjCExceptionAttribute(ASTContext &Context,
6791 const ObjCInterfaceDecl *OID) {
6792 if (OID->hasAttr<ObjCExceptionAttr>())
6793 return true;
6794 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6795 return hasObjCExceptionAttribute(Context, Super);
6796 return false;
6797}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006798
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006799void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6800 std::string &Result) {
6801 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6802
6803 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006804 if (CDecl->isImplicitInterfaceDecl())
6805 assert(false &&
6806 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006807
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006808 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006809 SmallVector<ObjCIvarDecl *, 8> IVars;
6810
6811 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6812 IVD; IVD = IVD->getNextIvar()) {
6813 // Ignore unnamed bit-fields.
6814 if (!IVD->getDeclName())
6815 continue;
6816 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006817 }
6818
Fariborz Jahanianae932952012-02-10 20:47:10 +00006819 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006820 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006821 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006822
6823 // Build _objc_method_list for class's instance methods if needed
6824 SmallVector<ObjCMethodDecl *, 32>
6825 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6826
6827 // If any of our property implementations have associated getters or
6828 // setters, produce metadata for them as well.
6829 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6830 PropEnd = IDecl->propimpl_end();
6831 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00006832 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006833 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006834 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006835 continue;
David Blaikie262bc182012-04-30 02:36:29 +00006836 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006837 if (!PD)
6838 continue;
6839 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6840 if (!Getter->isDefined())
6841 InstanceMethods.push_back(Getter);
6842 if (PD->isReadOnly())
6843 continue;
6844 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6845 if (!Setter->isDefined())
6846 InstanceMethods.push_back(Setter);
6847 }
6848
6849 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6850 "_OBJC_$_INSTANCE_METHODS_",
6851 IDecl->getNameAsString(), true);
6852
6853 SmallVector<ObjCMethodDecl *, 32>
6854 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6855
6856 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6857 "_OBJC_$_CLASS_METHODS_",
6858 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006859
6860 // Protocols referenced in class declaration?
6861 // Protocol's super protocol list
6862 std::vector<ObjCProtocolDecl *> RefedProtocols;
6863 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6864 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6865 E = Protocols.end();
6866 I != E; ++I) {
6867 RefedProtocols.push_back(*I);
6868 // Must write out all protocol definitions in current qualifier list,
6869 // and in their nested qualifiers before writing out current definition.
6870 RewriteObjCProtocolMetaData(*I, Result);
6871 }
6872
6873 Write_protocol_list_initializer(Context, Result,
6874 RefedProtocols,
6875 "_OBJC_CLASS_PROTOCOLS_$_",
6876 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006877
6878 // Protocol's property metadata.
6879 std::vector<ObjCPropertyDecl *> ClassProperties;
6880 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6881 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00006882 ClassProperties.push_back(&*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006883
6884 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006885 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006886 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006887 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006888
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006889
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006890 // Data for initializing _class_ro_t metaclass meta-data
6891 uint32_t flags = CLS_META;
6892 std::string InstanceSize;
6893 std::string InstanceStart;
6894
6895
6896 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6897 if (classIsHidden)
6898 flags |= OBJC2_CLS_HIDDEN;
6899
6900 if (!CDecl->getSuperClass())
6901 // class is root
6902 flags |= CLS_ROOT;
6903 InstanceSize = "sizeof(struct _class_t)";
6904 InstanceStart = InstanceSize;
6905 Write__class_ro_t_initializer(Context, Result, flags,
6906 InstanceStart, InstanceSize,
6907 ClassMethods,
6908 0,
6909 0,
6910 0,
6911 "_OBJC_METACLASS_RO_$_",
6912 CDecl->getNameAsString());
6913
6914
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006915 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006916 flags = CLS;
6917 if (classIsHidden)
6918 flags |= OBJC2_CLS_HIDDEN;
6919
6920 if (hasObjCExceptionAttribute(*Context, CDecl))
6921 flags |= CLS_EXCEPTION;
6922
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006923 if (!CDecl->getSuperClass())
6924 // class is root
6925 flags |= CLS_ROOT;
6926
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006927 InstanceSize.clear();
6928 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006929 if (!ObjCSynthesizedStructs.count(CDecl)) {
6930 InstanceSize = "0";
6931 InstanceStart = "0";
6932 }
6933 else {
6934 InstanceSize = "sizeof(struct ";
6935 InstanceSize += CDecl->getNameAsString();
6936 InstanceSize += "_IMPL)";
6937
6938 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6939 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006940 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006941 }
6942 else
6943 InstanceStart = InstanceSize;
6944 }
6945 Write__class_ro_t_initializer(Context, Result, flags,
6946 InstanceStart, InstanceSize,
6947 InstanceMethods,
6948 RefedProtocols,
6949 IVars,
6950 ClassProperties,
6951 "_OBJC_CLASS_RO_$_",
6952 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006953
6954 Write_class_t(Context, Result,
6955 "OBJC_METACLASS_$_",
6956 CDecl, /*metaclass*/true);
6957
6958 Write_class_t(Context, Result,
6959 "OBJC_CLASS_$_",
6960 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006961
6962 if (ImplementationIsNonLazy(IDecl))
6963 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006964
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006965}
6966
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006967void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6968 int ClsDefCount = ClassImplementation.size();
6969 if (!ClsDefCount)
6970 return;
6971 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6972 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6973 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6974 for (int i = 0; i < ClsDefCount; i++) {
6975 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6976 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6977 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6978 Result += CDecl->getName(); Result += ",\n";
6979 }
6980 Result += "};\n";
6981}
6982
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006983void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6984 int ClsDefCount = ClassImplementation.size();
6985 int CatDefCount = CategoryImplementation.size();
6986
6987 // For each implemented class, write out all its meta data.
6988 for (int i = 0; i < ClsDefCount; i++)
6989 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6990
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006991 RewriteClassSetupInitHook(Result);
6992
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006993 // For each implemented category, write out all its meta data.
6994 for (int i = 0; i < CatDefCount; i++)
6995 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6996
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006997 RewriteCategorySetupInitHook(Result);
6998
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006999 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007000 if (LangOpts.MicrosoftExt)
7001 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007002 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7003 Result += llvm::utostr(ClsDefCount); Result += "]";
7004 Result +=
7005 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7006 "regular,no_dead_strip\")))= {\n";
7007 for (int i = 0; i < ClsDefCount; i++) {
7008 Result += "\t&OBJC_CLASS_$_";
7009 Result += ClassImplementation[i]->getNameAsString();
7010 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007011 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007012 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007013
7014 if (!DefinedNonLazyClasses.empty()) {
7015 if (LangOpts.MicrosoftExt)
7016 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7017 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7018 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7019 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7020 Result += ",\n";
7021 }
7022 Result += "};\n";
7023 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007024 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007025
7026 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007027 if (LangOpts.MicrosoftExt)
7028 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007029 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7030 Result += llvm::utostr(CatDefCount); Result += "]";
7031 Result +=
7032 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7033 "regular,no_dead_strip\")))= {\n";
7034 for (int i = 0; i < CatDefCount; i++) {
7035 Result += "\t&_OBJC_$_CATEGORY_";
7036 Result +=
7037 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7038 Result += "_$_";
7039 Result += CategoryImplementation[i]->getNameAsString();
7040 Result += ",\n";
7041 }
7042 Result += "};\n";
7043 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007044
7045 if (!DefinedNonLazyCategories.empty()) {
7046 if (LangOpts.MicrosoftExt)
7047 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7048 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7049 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7050 Result += "\t&_OBJC_$_CATEGORY_";
7051 Result +=
7052 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7053 Result += "_$_";
7054 Result += DefinedNonLazyCategories[i]->getNameAsString();
7055 Result += ",\n";
7056 }
7057 Result += "};\n";
7058 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007059}
7060
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007061void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7062 if (LangOpts.MicrosoftExt)
7063 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7064
7065 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7066 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007067 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007068}
7069
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007070/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7071/// implementation.
7072void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7073 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007074 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007075 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7076 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007077 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007078 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7079 CDecl = CDecl->getNextClassCategory())
7080 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7081 break;
7082
7083 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007084 FullCategoryName += "_$_";
7085 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007086
7087 // Build _objc_method_list for class's instance methods if needed
7088 SmallVector<ObjCMethodDecl *, 32>
7089 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7090
7091 // If any of our property implementations have associated getters or
7092 // setters, produce metadata for them as well.
7093 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7094 PropEnd = IDecl->propimpl_end();
7095 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007096 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007097 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007098 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007099 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007100 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007101 if (!PD)
7102 continue;
7103 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7104 InstanceMethods.push_back(Getter);
7105 if (PD->isReadOnly())
7106 continue;
7107 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7108 InstanceMethods.push_back(Setter);
7109 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007110
Fariborz Jahanian61186122012-02-17 18:40:41 +00007111 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7112 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7113 FullCategoryName, true);
7114
7115 SmallVector<ObjCMethodDecl *, 32>
7116 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7117
7118 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7119 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7120 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007121
7122 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007123 // Protocol's super protocol list
7124 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007125 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7126 E = CDecl->protocol_end();
7127
7128 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007129 RefedProtocols.push_back(*I);
7130 // Must write out all protocol definitions in current qualifier list,
7131 // and in their nested qualifiers before writing out current definition.
7132 RewriteObjCProtocolMetaData(*I, Result);
7133 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007134
Fariborz Jahanian61186122012-02-17 18:40:41 +00007135 Write_protocol_list_initializer(Context, Result,
7136 RefedProtocols,
7137 "_OBJC_CATEGORY_PROTOCOLS_$_",
7138 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007139
Fariborz Jahanian61186122012-02-17 18:40:41 +00007140 // Protocol's property metadata.
7141 std::vector<ObjCPropertyDecl *> ClassProperties;
7142 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7143 E = CDecl->prop_end(); I != E; ++I)
David Blaikie262bc182012-04-30 02:36:29 +00007144 ClassProperties.push_back(&*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007145
Fariborz Jahanian61186122012-02-17 18:40:41 +00007146 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7147 /* Container */0,
7148 "_OBJC_$_PROP_LIST_",
7149 FullCategoryName);
7150
7151 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007152 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007153 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007154 InstanceMethods,
7155 ClassMethods,
7156 RefedProtocols,
7157 ClassProperties);
7158
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007159 // Determine if this category is also "non-lazy".
7160 if (ImplementationIsNonLazy(IDecl))
7161 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007162
7163}
7164
7165void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7166 int CatDefCount = CategoryImplementation.size();
7167 if (!CatDefCount)
7168 return;
7169 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7170 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7171 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7172 for (int i = 0; i < CatDefCount; i++) {
7173 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7174 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7175 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7176 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7177 Result += ClassDecl->getName();
7178 Result += "_$_";
7179 Result += CatDecl->getName();
7180 Result += ",\n";
7181 }
7182 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007183}
7184
7185// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7186/// class methods.
7187template<typename MethodIterator>
7188void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7189 MethodIterator MethodEnd,
7190 bool IsInstanceMethod,
7191 StringRef prefix,
7192 StringRef ClassName,
7193 std::string &Result) {
7194 if (MethodBegin == MethodEnd) return;
7195
7196 if (!objc_impl_method) {
7197 /* struct _objc_method {
7198 SEL _cmd;
7199 char *method_types;
7200 void *_imp;
7201 }
7202 */
7203 Result += "\nstruct _objc_method {\n";
7204 Result += "\tSEL _cmd;\n";
7205 Result += "\tchar *method_types;\n";
7206 Result += "\tvoid *_imp;\n";
7207 Result += "};\n";
7208
7209 objc_impl_method = true;
7210 }
7211
7212 // Build _objc_method_list for class's methods if needed
7213
7214 /* struct {
7215 struct _objc_method_list *next_method;
7216 int method_count;
7217 struct _objc_method method_list[];
7218 }
7219 */
7220 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007221 Result += "\n";
7222 if (LangOpts.MicrosoftExt) {
7223 if (IsInstanceMethod)
7224 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7225 else
7226 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7227 }
7228 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007229 Result += "\tstruct _objc_method_list *next_method;\n";
7230 Result += "\tint method_count;\n";
7231 Result += "\tstruct _objc_method method_list[";
7232 Result += utostr(NumMethods);
7233 Result += "];\n} _OBJC_";
7234 Result += prefix;
7235 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7236 Result += "_METHODS_";
7237 Result += ClassName;
7238 Result += " __attribute__ ((used, section (\"__OBJC, __";
7239 Result += IsInstanceMethod ? "inst" : "cls";
7240 Result += "_meth\")))= ";
7241 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7242
7243 Result += "\t,{{(SEL)\"";
7244 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7245 std::string MethodTypeString;
7246 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7247 Result += "\", \"";
7248 Result += MethodTypeString;
7249 Result += "\", (void *)";
7250 Result += MethodInternalNames[*MethodBegin];
7251 Result += "}\n";
7252 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7253 Result += "\t ,{(SEL)\"";
7254 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7255 std::string MethodTypeString;
7256 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7257 Result += "\", \"";
7258 Result += MethodTypeString;
7259 Result += "\", (void *)";
7260 Result += MethodInternalNames[*MethodBegin];
7261 Result += "}\n";
7262 }
7263 Result += "\t }\n};\n";
7264}
7265
7266Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7267 SourceRange OldRange = IV->getSourceRange();
7268 Expr *BaseExpr = IV->getBase();
7269
7270 // Rewrite the base, but without actually doing replaces.
7271 {
7272 DisableReplaceStmtScope S(*this);
7273 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7274 IV->setBase(BaseExpr);
7275 }
7276
7277 ObjCIvarDecl *D = IV->getDecl();
7278
7279 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007280
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007281 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7282 const ObjCInterfaceType *iFaceDecl =
7283 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7284 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7285 // lookup which class implements the instance variable.
7286 ObjCInterfaceDecl *clsDeclared = 0;
7287 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7288 clsDeclared);
7289 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7290
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007291 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007292 std::string IvarOffsetName;
7293 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7294
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007295 ReferencedIvars[clsDeclared].insert(D);
7296
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007297 // cast offset to "char *".
7298 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7299 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007300 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007301 BaseExpr);
7302 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7303 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7304 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007305 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7306 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007307 SourceLocation());
7308 BinaryOperator *addExpr =
7309 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7310 Context->getPointerType(Context->CharTy),
7311 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007312 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007313 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7314 SourceLocation(),
7315 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007316 QualType IvarT = D->getType();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007317
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007318 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007319 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007320 RD = RD->getDefinition();
7321 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007322 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007323 ObjCContainerDecl *CDecl =
7324 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7325 // ivar in class extensions requires special treatment.
7326 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7327 CDecl = CatDecl->getClassInterface();
7328 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007329 RecName += "_IMPL";
7330 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7331 SourceLocation(), SourceLocation(),
7332 &Context->Idents.get(RecName.c_str()));
7333 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7334 unsigned UnsignedIntSize =
7335 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7336 Expr *Zero = IntegerLiteral::Create(*Context,
7337 llvm::APInt(UnsignedIntSize, 0),
7338 Context->UnsignedIntTy, SourceLocation());
7339 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7340 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7341 Zero);
7342 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7343 SourceLocation(),
7344 &Context->Idents.get(D->getNameAsString()),
7345 IvarT, 0,
7346 /*BitWidth=*/0, /*Mutable=*/true,
7347 /*HasInit=*/false);
7348 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7349 FD->getType(), VK_LValue,
7350 OK_Ordinary);
7351 IvarT = Context->getDecltypeType(ME, ME->getType());
7352 }
7353 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007354 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007355 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007356
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007357 castExpr = NoTypeInfoCStyleCastExpr(Context,
7358 castT,
7359 CK_BitCast,
7360 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007361
7362
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007363 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007364 VK_LValue, OK_Ordinary,
7365 SourceLocation());
7366 PE = new (Context) ParenExpr(OldRange.getBegin(),
7367 OldRange.getEnd(),
7368 Exp);
7369
7370 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007371 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007372
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007373 ReplaceStmtWithRange(IV, Replacement, OldRange);
7374 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007375}