blob: 9cefa5ed2d76581240715fdfad79d1cfcac578a7 [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 Jahanian15f87772012-02-28 22:45:07 +0000112 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
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);
349
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000350 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
351
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000352 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
353 std::string &Result);
354
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000355 virtual void Initialize(ASTContext &context);
356
357 // Misc. AST transformation routines. Somtimes they end up calling
358 // rewriting routines on the new ASTs.
359 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
360 Expr **args, unsigned nargs,
361 SourceLocation StartLoc=SourceLocation(),
362 SourceLocation EndLoc=SourceLocation());
363
364 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
365 SourceLocation StartLoc=SourceLocation(),
366 SourceLocation EndLoc=SourceLocation());
367
368 void SynthCountByEnumWithState(std::string &buf);
369 void SynthMsgSendFunctionDecl();
370 void SynthMsgSendSuperFunctionDecl();
371 void SynthMsgSendStretFunctionDecl();
372 void SynthMsgSendFpretFunctionDecl();
373 void SynthMsgSendSuperStretFunctionDecl();
374 void SynthGetClassFunctionDecl();
375 void SynthGetMetaClassFunctionDecl();
376 void SynthGetSuperClassFunctionDecl();
377 void SynthSelGetUidFunctionDecl();
378 void SynthSuperContructorFunctionDecl();
379
380 // Rewriting metadata
381 template<typename MethodIterator>
382 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
383 MethodIterator MethodEnd,
384 bool IsInstanceMethod,
385 StringRef prefix,
386 StringRef ClassName,
387 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000388 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
389 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000390 virtual void RewriteObjCProtocolListMetaData(
391 const ObjCList<ObjCProtocolDecl> &Prots,
392 StringRef prefix, StringRef ClassName, std::string &Result);
393 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
394 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000395 virtual void RewriteClassSetupInitHook(std::string &Result);
396
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000397 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000398 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000399 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
400 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000401 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000402
403 // Rewriting ivar
404 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
405 std::string &Result);
406 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
407
408
409 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
410 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
411 StringRef funcName, std::string Tag);
412 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
413 StringRef funcName, std::string Tag);
414 std::string SynthesizeBlockImpl(BlockExpr *CE,
415 std::string Tag, std::string Desc);
416 std::string SynthesizeBlockDescriptor(std::string DescTag,
417 std::string ImplTag,
418 int i, StringRef funcName,
419 unsigned hasCopy);
420 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
421 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
422 StringRef FunName);
423 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
424 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000425 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000426
427 // Misc. helper routines.
428 QualType getProtocolType();
429 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000430 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
431 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
432 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
433
434 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
435 void CollectBlockDeclRefInfo(BlockExpr *Exp);
436 void GetBlockDeclRefExprs(Stmt *S);
437 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000438 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000439 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
440
441 // We avoid calling Type::isBlockPointerType(), since it operates on the
442 // canonical type. We only care if the top-level type is a closure pointer.
443 bool isTopLevelBlockPointerType(QualType T) {
444 return isa<BlockPointerType>(T);
445 }
446
447 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
448 /// to a function pointer type and upon success, returns true; false
449 /// otherwise.
450 bool convertBlockPointerToFunctionPointer(QualType &T) {
451 if (isTopLevelBlockPointerType(T)) {
452 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
453 T = Context->getPointerType(BPT->getPointeeType());
454 return true;
455 }
456 return false;
457 }
458
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000459 bool convertObjCTypeToCStyleType(QualType &T);
460
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461 bool needToScanForQualifiers(QualType T);
462 QualType getSuperStructType();
463 QualType getConstantStringStructType();
464 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
465 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
466
467 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000468 if (T->isObjCQualifiedIdType()) {
469 bool isConst = T.isConstQualified();
470 T = isConst ? Context->getObjCIdType().withConst()
471 : Context->getObjCIdType();
472 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000473 else if (T->isObjCQualifiedClassType())
474 T = Context->getObjCClassType();
475 else if (T->isObjCObjectPointerType() &&
476 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
477 if (const ObjCObjectPointerType * OBJPT =
478 T->getAsObjCInterfacePointerType()) {
479 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
480 T = QualType(IFaceT, 0);
481 T = Context->getPointerType(T);
482 }
483 }
484 }
485
486 // FIXME: This predicate seems like it would be useful to add to ASTContext.
487 bool isObjCType(QualType T) {
488 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
489 return false;
490
491 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
492
493 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
494 OCT == Context->getCanonicalType(Context->getObjCClassType()))
495 return true;
496
497 if (const PointerType *PT = OCT->getAs<PointerType>()) {
498 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
499 PT->getPointeeType()->isObjCQualifiedIdType())
500 return true;
501 }
502 return false;
503 }
504 bool PointerTypeTakesAnyBlockArguments(QualType QT);
505 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
506 void GetExtentOfArgList(const char *Name, const char *&LParen,
507 const char *&RParen);
508
509 void QuoteDoublequotes(std::string &From, std::string &To) {
510 for (unsigned i = 0; i < From.length(); i++) {
511 if (From[i] == '"')
512 To += "\\\"";
513 else
514 To += From[i];
515 }
516 }
517
518 QualType getSimpleFunctionType(QualType result,
519 const QualType *args,
520 unsigned numArgs,
521 bool variadic = false) {
522 if (result == Context->getObjCInstanceType())
523 result = Context->getObjCIdType();
524 FunctionProtoType::ExtProtoInfo fpi;
525 fpi.Variadic = variadic;
526 return Context->getFunctionType(result, args, numArgs, fpi);
527 }
528
529 // Helper function: create a CStyleCastExpr with trivial type source info.
530 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
531 CastKind Kind, Expr *E) {
532 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
533 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
534 SourceLocation(), SourceLocation());
535 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000536
537 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
538 IdentifierInfo* II = &Context->Idents.get("load");
539 Selector LoadSel = Context->Selectors.getSelector(0, &II);
540 return OD->getClassMethod(LoadSel) != 0;
541 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000542 };
543
544}
545
546void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
547 NamedDecl *D) {
548 if (const FunctionProtoType *fproto
549 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
550 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
551 E = fproto->arg_type_end(); I && (I != E); ++I)
552 if (isTopLevelBlockPointerType(*I)) {
553 // All the args are checked/rewritten. Don't call twice!
554 RewriteBlockPointerDecl(D);
555 break;
556 }
557 }
558}
559
560void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
561 const PointerType *PT = funcType->getAs<PointerType>();
562 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
563 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
564}
565
566static bool IsHeaderFile(const std::string &Filename) {
567 std::string::size_type DotPos = Filename.rfind('.');
568
569 if (DotPos == std::string::npos) {
570 // no file extension
571 return false;
572 }
573
574 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
575 // C header: .h
576 // C++ header: .hh or .H;
577 return Ext == "h" || Ext == "hh" || Ext == "H";
578}
579
580RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
581 DiagnosticsEngine &D, const LangOptions &LOpts,
582 bool silenceMacroWarn)
583 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
584 SilenceRewriteMacroWarning(silenceMacroWarn) {
585 IsHeader = IsHeaderFile(inFile);
586 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
587 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000588 // FIXME. This should be an error. But if block is not called, it is OK. And it
589 // may break including some headers.
590 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
591 "rewriting block literal declared in global scope is not implemented");
592
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000593 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
594 DiagnosticsEngine::Warning,
595 "rewriter doesn't support user-specified control flow semantics "
596 "for @try/@finally (code may not execute properly)");
597}
598
599ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
600 raw_ostream* OS,
601 DiagnosticsEngine &Diags,
602 const LangOptions &LOpts,
603 bool SilenceRewriteMacroWarning) {
604 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
605}
606
607void RewriteModernObjC::InitializeCommon(ASTContext &context) {
608 Context = &context;
609 SM = &Context->getSourceManager();
610 TUDecl = Context->getTranslationUnitDecl();
611 MsgSendFunctionDecl = 0;
612 MsgSendSuperFunctionDecl = 0;
613 MsgSendStretFunctionDecl = 0;
614 MsgSendSuperStretFunctionDecl = 0;
615 MsgSendFpretFunctionDecl = 0;
616 GetClassFunctionDecl = 0;
617 GetMetaClassFunctionDecl = 0;
618 GetSuperClassFunctionDecl = 0;
619 SelGetUidFunctionDecl = 0;
620 CFStringFunctionDecl = 0;
621 ConstantStringClassReference = 0;
622 NSStringRecord = 0;
623 CurMethodDef = 0;
624 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000625 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000626 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000627 SuperStructDecl = 0;
628 ProtocolTypeDecl = 0;
629 ConstantStringDecl = 0;
630 BcLabelCount = 0;
631 SuperContructorFunctionDecl = 0;
632 NumObjCStringLiterals = 0;
633 PropParentMap = 0;
634 CurrentBody = 0;
635 DisableReplaceStmt = false;
636 objc_impl_method = false;
637
638 // Get the ID and start/end of the main file.
639 MainFileID = SM->getMainFileID();
640 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
641 MainFileStart = MainBuf->getBufferStart();
642 MainFileEnd = MainBuf->getBufferEnd();
643
David Blaikie4e4d0842012-03-11 07:00:24 +0000644 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000645}
646
647//===----------------------------------------------------------------------===//
648// Top Level Driver Code
649//===----------------------------------------------------------------------===//
650
651void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
652 if (Diags.hasErrorOccurred())
653 return;
654
655 // Two cases: either the decl could be in the main file, or it could be in a
656 // #included file. If the former, rewrite it now. If the later, check to see
657 // if we rewrote the #include/#import.
658 SourceLocation Loc = D->getLocation();
659 Loc = SM->getExpansionLoc(Loc);
660
661 // If this is for a builtin, ignore it.
662 if (Loc.isInvalid()) return;
663
664 // Look for built-in declarations that we need to refer during the rewrite.
665 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
666 RewriteFunctionDecl(FD);
667 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
668 // declared in <Foundation/NSString.h>
669 if (FVD->getName() == "_NSConstantStringClassReference") {
670 ConstantStringClassReference = FVD;
671 return;
672 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000673 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
674 RewriteCategoryDecl(CD);
675 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
676 if (PD->isThisDeclarationADefinition())
677 RewriteProtocolDecl(PD);
678 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000679 // FIXME. This will not work in all situations and leaving it out
680 // is harmless.
681 // RewriteLinkageSpec(LSD);
682
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000683 // Recurse into linkage specifications
684 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
685 DIEnd = LSD->decls_end();
686 DI != DIEnd; ) {
687 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
688 if (!IFace->isThisDeclarationADefinition()) {
689 SmallVector<Decl *, 8> DG;
690 SourceLocation StartLoc = IFace->getLocStart();
691 do {
692 if (isa<ObjCInterfaceDecl>(*DI) &&
693 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
694 StartLoc == (*DI)->getLocStart())
695 DG.push_back(*DI);
696 else
697 break;
698
699 ++DI;
700 } while (DI != DIEnd);
701 RewriteForwardClassDecl(DG);
702 continue;
703 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000704 else {
705 // Keep track of all interface declarations seen.
706 ObjCInterfacesSeen.push_back(IFace);
707 ++DI;
708 continue;
709 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000710 }
711
712 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
713 if (!Proto->isThisDeclarationADefinition()) {
714 SmallVector<Decl *, 8> DG;
715 SourceLocation StartLoc = Proto->getLocStart();
716 do {
717 if (isa<ObjCProtocolDecl>(*DI) &&
718 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
719 StartLoc == (*DI)->getLocStart())
720 DG.push_back(*DI);
721 else
722 break;
723
724 ++DI;
725 } while (DI != DIEnd);
726 RewriteForwardProtocolDecl(DG);
727 continue;
728 }
729 }
730
731 HandleTopLevelSingleDecl(*DI);
732 ++DI;
733 }
734 }
735 // If we have a decl in the main file, see if we should rewrite it.
736 if (SM->isFromMainFile(Loc))
737 return HandleDeclInMainFile(D);
738}
739
740//===----------------------------------------------------------------------===//
741// Syntactic (non-AST) Rewriting Code
742//===----------------------------------------------------------------------===//
743
744void RewriteModernObjC::RewriteInclude() {
745 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
746 StringRef MainBuf = SM->getBufferData(MainFileID);
747 const char *MainBufStart = MainBuf.begin();
748 const char *MainBufEnd = MainBuf.end();
749 size_t ImportLen = strlen("import");
750
751 // Loop over the whole file, looking for includes.
752 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
753 if (*BufPtr == '#') {
754 if (++BufPtr == MainBufEnd)
755 return;
756 while (*BufPtr == ' ' || *BufPtr == '\t')
757 if (++BufPtr == MainBufEnd)
758 return;
759 if (!strncmp(BufPtr, "import", ImportLen)) {
760 // replace import with include
761 SourceLocation ImportLoc =
762 LocStart.getLocWithOffset(BufPtr-MainBufStart);
763 ReplaceText(ImportLoc, ImportLen, "include");
764 BufPtr += ImportLen;
765 }
766 }
767 }
768}
769
770static std::string getIvarAccessString(ObjCIvarDecl *OID) {
771 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
772 std::string S;
773 S = "((struct ";
774 S += ClassDecl->getIdentifier()->getName();
775 S += "_IMPL *)self)->";
776 S += OID->getName();
777 return S;
778}
779
780void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
781 ObjCImplementationDecl *IMD,
782 ObjCCategoryImplDecl *CID) {
783 static bool objcGetPropertyDefined = false;
784 static bool objcSetPropertyDefined = false;
785 SourceLocation startLoc = PID->getLocStart();
786 InsertText(startLoc, "// ");
787 const char *startBuf = SM->getCharacterData(startLoc);
788 assert((*startBuf == '@') && "bogus @synthesize location");
789 const char *semiBuf = strchr(startBuf, ';');
790 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
791 SourceLocation onePastSemiLoc =
792 startLoc.getLocWithOffset(semiBuf-startBuf+1);
793
794 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
795 return; // FIXME: is this correct?
796
797 // Generate the 'getter' function.
798 ObjCPropertyDecl *PD = PID->getPropertyDecl();
799 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
800
801 if (!OID)
802 return;
803 unsigned Attributes = PD->getPropertyAttributes();
804 if (!PD->getGetterMethodDecl()->isDefined()) {
805 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
806 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
807 ObjCPropertyDecl::OBJC_PR_copy));
808 std::string Getr;
809 if (GenGetProperty && !objcGetPropertyDefined) {
810 objcGetPropertyDefined = true;
811 // FIXME. Is this attribute correct in all cases?
812 Getr = "\nextern \"C\" __declspec(dllimport) "
813 "id objc_getProperty(id, SEL, long, bool);\n";
814 }
815 RewriteObjCMethodDecl(OID->getContainingInterface(),
816 PD->getGetterMethodDecl(), Getr);
817 Getr += "{ ";
818 // Synthesize an explicit cast to gain access to the ivar.
819 // See objc-act.c:objc_synthesize_new_getter() for details.
820 if (GenGetProperty) {
821 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
822 Getr += "typedef ";
823 const FunctionType *FPRetType = 0;
824 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
825 FPRetType);
826 Getr += " _TYPE";
827 if (FPRetType) {
828 Getr += ")"; // close the precedence "scope" for "*".
829
830 // Now, emit the argument types (if any).
831 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
832 Getr += "(";
833 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
834 if (i) Getr += ", ";
835 std::string ParamStr = FT->getArgType(i).getAsString(
836 Context->getPrintingPolicy());
837 Getr += ParamStr;
838 }
839 if (FT->isVariadic()) {
840 if (FT->getNumArgs()) Getr += ", ";
841 Getr += "...";
842 }
843 Getr += ")";
844 } else
845 Getr += "()";
846 }
847 Getr += ";\n";
848 Getr += "return (_TYPE)";
849 Getr += "objc_getProperty(self, _cmd, ";
850 RewriteIvarOffsetComputation(OID, Getr);
851 Getr += ", 1)";
852 }
853 else
854 Getr += "return " + getIvarAccessString(OID);
855 Getr += "; }";
856 InsertText(onePastSemiLoc, Getr);
857 }
858
859 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
860 return;
861
862 // Generate the 'setter' function.
863 std::string Setr;
864 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
865 ObjCPropertyDecl::OBJC_PR_copy);
866 if (GenSetProperty && !objcSetPropertyDefined) {
867 objcSetPropertyDefined = true;
868 // FIXME. Is this attribute correct in all cases?
869 Setr = "\nextern \"C\" __declspec(dllimport) "
870 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
871 }
872
873 RewriteObjCMethodDecl(OID->getContainingInterface(),
874 PD->getSetterMethodDecl(), Setr);
875 Setr += "{ ";
876 // Synthesize an explicit cast to initialize the ivar.
877 // See objc-act.c:objc_synthesize_new_setter() for details.
878 if (GenSetProperty) {
879 Setr += "objc_setProperty (self, _cmd, ";
880 RewriteIvarOffsetComputation(OID, Setr);
881 Setr += ", (id)";
882 Setr += PD->getName();
883 Setr += ", ";
884 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
885 Setr += "0, ";
886 else
887 Setr += "1, ";
888 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
889 Setr += "1)";
890 else
891 Setr += "0)";
892 }
893 else {
894 Setr += getIvarAccessString(OID) + " = ";
895 Setr += PD->getName();
896 }
897 Setr += "; }";
898 InsertText(onePastSemiLoc, Setr);
899}
900
901static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
902 std::string &typedefString) {
903 typedefString += "#ifndef _REWRITER_typedef_";
904 typedefString += ForwardDecl->getNameAsString();
905 typedefString += "\n";
906 typedefString += "#define _REWRITER_typedef_";
907 typedefString += ForwardDecl->getNameAsString();
908 typedefString += "\n";
909 typedefString += "typedef struct objc_object ";
910 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000911 // typedef struct { } _objc_exc_Classname;
912 typedefString += ";\ntypedef struct {} _objc_exc_";
913 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000914 typedefString += ";\n#endif\n";
915}
916
917void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
918 const std::string &typedefString) {
919 SourceLocation startLoc = ClassDecl->getLocStart();
920 const char *startBuf = SM->getCharacterData(startLoc);
921 const char *semiPtr = strchr(startBuf, ';');
922 // Replace the @class with typedefs corresponding to the classes.
923 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
924}
925
926void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
927 std::string typedefString;
928 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
929 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
930 if (I == D.begin()) {
931 // Translate to typedef's that forward reference structs with the same name
932 // as the class. As a convenience, we include the original declaration
933 // as a comment.
934 typedefString += "// @class ";
935 typedefString += ForwardDecl->getNameAsString();
936 typedefString += ";\n";
937 }
938 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
939 }
940 DeclGroupRef::iterator I = D.begin();
941 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
942}
943
944void RewriteModernObjC::RewriteForwardClassDecl(
945 const llvm::SmallVector<Decl*, 8> &D) {
946 std::string typedefString;
947 for (unsigned i = 0; i < D.size(); i++) {
948 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
949 if (i == 0) {
950 typedefString += "// @class ";
951 typedefString += ForwardDecl->getNameAsString();
952 typedefString += ";\n";
953 }
954 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
955 }
956 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
957}
958
959void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
960 // When method is a synthesized one, such as a getter/setter there is
961 // nothing to rewrite.
962 if (Method->isImplicit())
963 return;
964 SourceLocation LocStart = Method->getLocStart();
965 SourceLocation LocEnd = Method->getLocEnd();
966
967 if (SM->getExpansionLineNumber(LocEnd) >
968 SM->getExpansionLineNumber(LocStart)) {
969 InsertText(LocStart, "#if 0\n");
970 ReplaceText(LocEnd, 1, ";\n#endif\n");
971 } else {
972 InsertText(LocStart, "// ");
973 }
974}
975
976void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
977 SourceLocation Loc = prop->getAtLoc();
978
979 ReplaceText(Loc, 0, "// ");
980 // FIXME: handle properties that are declared across multiple lines.
981}
982
983void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
984 SourceLocation LocStart = CatDecl->getLocStart();
985
986 // FIXME: handle category headers that are declared across multiple lines.
987 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000988 if (CatDecl->getIvarLBraceLoc().isValid())
989 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000990 for (ObjCCategoryDecl::ivar_iterator
991 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
992 ObjCIvarDecl *Ivar = (*I);
993 SourceLocation LocStart = Ivar->getLocStart();
994 ReplaceText(LocStart, 0, "// ");
995 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000996 if (CatDecl->getIvarRBraceLoc().isValid())
997 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
998
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000999 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1000 E = CatDecl->prop_end(); I != E; ++I)
1001 RewriteProperty(*I);
1002
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)
1035 RewriteProperty(*I);
1036
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) {
1223 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001224 if (IMD->getIvarLBraceLoc().isValid())
1225 InsertText(IMD->getIvarLBraceLoc(), "// ");
1226 for (ObjCImplementationDecl::ivar_iterator
1227 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1228 ObjCIvarDecl *Ivar = (*I);
1229 SourceLocation LocStart = Ivar->getLocStart();
1230 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001231 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001232 if (IMD->getIvarRBraceLoc().isValid())
1233 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001234 }
1235 else
1236 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001237
1238 for (ObjCCategoryImplDecl::instmeth_iterator
1239 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1240 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1241 I != E; ++I) {
1242 std::string ResultStr;
1243 ObjCMethodDecl *OMD = *I;
1244 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1245 SourceLocation LocStart = OMD->getLocStart();
1246 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1247
1248 const char *startBuf = SM->getCharacterData(LocStart);
1249 const char *endBuf = SM->getCharacterData(LocEnd);
1250 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1251 }
1252
1253 for (ObjCCategoryImplDecl::classmeth_iterator
1254 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1255 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1256 I != E; ++I) {
1257 std::string ResultStr;
1258 ObjCMethodDecl *OMD = *I;
1259 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1260 SourceLocation LocStart = OMD->getLocStart();
1261 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1262
1263 const char *startBuf = SM->getCharacterData(LocStart);
1264 const char *endBuf = SM->getCharacterData(LocEnd);
1265 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1266 }
1267 for (ObjCCategoryImplDecl::propimpl_iterator
1268 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1269 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1270 I != E; ++I) {
1271 RewritePropertyImplDecl(*I, IMD, CID);
1272 }
1273
1274 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1275}
1276
1277void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001278 // Do not synthesize more than once.
1279 if (ObjCSynthesizedStructs.count(ClassDecl))
1280 return;
1281 // Make sure super class's are written before current class is written.
1282 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1283 while (SuperClass) {
1284 RewriteInterfaceDecl(SuperClass);
1285 SuperClass = SuperClass->getSuperClass();
1286 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001287 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001288 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001289 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001290 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001291 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1292
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001293 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001294 // Mark this typedef as having been written into its c++ equivalent.
1295 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001296
1297 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001298 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001299 RewriteProperty(*I);
1300 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001301 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001302 I != E; ++I)
1303 RewriteMethodDeclaration(*I);
1304 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001305 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001306 I != E; ++I)
1307 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001308
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001309 // Lastly, comment out the @end.
1310 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1311 "/* @end */");
1312 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001313}
1314
1315Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1316 SourceRange OldRange = PseudoOp->getSourceRange();
1317
1318 // We just magically know some things about the structure of this
1319 // expression.
1320 ObjCMessageExpr *OldMsg =
1321 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1322 PseudoOp->getNumSemanticExprs() - 1));
1323
1324 // Because the rewriter doesn't allow us to rewrite rewritten code,
1325 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001326 Expr *Base;
1327 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001328 {
1329 DisableReplaceStmtScope S(*this);
1330
1331 // Rebuild the base expression if we have one.
1332 Base = 0;
1333 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1334 Base = OldMsg->getInstanceReceiver();
1335 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1336 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1337 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001338
1339 unsigned numArgs = OldMsg->getNumArgs();
1340 for (unsigned i = 0; i < numArgs; i++) {
1341 Expr *Arg = OldMsg->getArg(i);
1342 if (isa<OpaqueValueExpr>(Arg))
1343 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1344 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1345 Args.push_back(Arg);
1346 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001347 }
1348
1349 // TODO: avoid this copy.
1350 SmallVector<SourceLocation, 1> SelLocs;
1351 OldMsg->getSelectorLocs(SelLocs);
1352
1353 ObjCMessageExpr *NewMsg = 0;
1354 switch (OldMsg->getReceiverKind()) {
1355 case ObjCMessageExpr::Class:
1356 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1357 OldMsg->getValueKind(),
1358 OldMsg->getLeftLoc(),
1359 OldMsg->getClassReceiverTypeInfo(),
1360 OldMsg->getSelector(),
1361 SelLocs,
1362 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001363 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001364 OldMsg->getRightLoc(),
1365 OldMsg->isImplicit());
1366 break;
1367
1368 case ObjCMessageExpr::Instance:
1369 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1370 OldMsg->getValueKind(),
1371 OldMsg->getLeftLoc(),
1372 Base,
1373 OldMsg->getSelector(),
1374 SelLocs,
1375 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001376 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001377 OldMsg->getRightLoc(),
1378 OldMsg->isImplicit());
1379 break;
1380
1381 case ObjCMessageExpr::SuperClass:
1382 case ObjCMessageExpr::SuperInstance:
1383 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1384 OldMsg->getValueKind(),
1385 OldMsg->getLeftLoc(),
1386 OldMsg->getSuperLoc(),
1387 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1388 OldMsg->getSuperType(),
1389 OldMsg->getSelector(),
1390 SelLocs,
1391 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001392 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001393 OldMsg->getRightLoc(),
1394 OldMsg->isImplicit());
1395 break;
1396 }
1397
1398 Stmt *Replacement = SynthMessageExpr(NewMsg);
1399 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1400 return Replacement;
1401}
1402
1403Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1404 SourceRange OldRange = PseudoOp->getSourceRange();
1405
1406 // We just magically know some things about the structure of this
1407 // expression.
1408 ObjCMessageExpr *OldMsg =
1409 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1410
1411 // Because the rewriter doesn't allow us to rewrite rewritten code,
1412 // we need to suppress rewriting the sub-statements.
1413 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001414 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001415 {
1416 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001417 // Rebuild the base expression if we have one.
1418 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1419 Base = OldMsg->getInstanceReceiver();
1420 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1421 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1422 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001423 unsigned numArgs = OldMsg->getNumArgs();
1424 for (unsigned i = 0; i < numArgs; i++) {
1425 Expr *Arg = OldMsg->getArg(i);
1426 if (isa<OpaqueValueExpr>(Arg))
1427 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1428 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1429 Args.push_back(Arg);
1430 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001431 }
1432
1433 // Intentionally empty.
1434 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001435
1436 ObjCMessageExpr *NewMsg = 0;
1437 switch (OldMsg->getReceiverKind()) {
1438 case ObjCMessageExpr::Class:
1439 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1440 OldMsg->getValueKind(),
1441 OldMsg->getLeftLoc(),
1442 OldMsg->getClassReceiverTypeInfo(),
1443 OldMsg->getSelector(),
1444 SelLocs,
1445 OldMsg->getMethodDecl(),
1446 Args,
1447 OldMsg->getRightLoc(),
1448 OldMsg->isImplicit());
1449 break;
1450
1451 case ObjCMessageExpr::Instance:
1452 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1453 OldMsg->getValueKind(),
1454 OldMsg->getLeftLoc(),
1455 Base,
1456 OldMsg->getSelector(),
1457 SelLocs,
1458 OldMsg->getMethodDecl(),
1459 Args,
1460 OldMsg->getRightLoc(),
1461 OldMsg->isImplicit());
1462 break;
1463
1464 case ObjCMessageExpr::SuperClass:
1465 case ObjCMessageExpr::SuperInstance:
1466 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1467 OldMsg->getValueKind(),
1468 OldMsg->getLeftLoc(),
1469 OldMsg->getSuperLoc(),
1470 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1471 OldMsg->getSuperType(),
1472 OldMsg->getSelector(),
1473 SelLocs,
1474 OldMsg->getMethodDecl(),
1475 Args,
1476 OldMsg->getRightLoc(),
1477 OldMsg->isImplicit());
1478 break;
1479 }
1480
1481 Stmt *Replacement = SynthMessageExpr(NewMsg);
1482 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1483 return Replacement;
1484}
1485
1486/// SynthCountByEnumWithState - To print:
1487/// ((unsigned int (*)
1488/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1489/// (void *)objc_msgSend)((id)l_collection,
1490/// sel_registerName(
1491/// "countByEnumeratingWithState:objects:count:"),
1492/// &enumState,
1493/// (id *)__rw_items, (unsigned int)16)
1494///
1495void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1496 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1497 "id *, unsigned int))(void *)objc_msgSend)";
1498 buf += "\n\t\t";
1499 buf += "((id)l_collection,\n\t\t";
1500 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1501 buf += "\n\t\t";
1502 buf += "&enumState, "
1503 "(id *)__rw_items, (unsigned int)16)";
1504}
1505
1506/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1507/// statement to exit to its outer synthesized loop.
1508///
1509Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1510 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1511 return S;
1512 // replace break with goto __break_label
1513 std::string buf;
1514
1515 SourceLocation startLoc = S->getLocStart();
1516 buf = "goto __break_label_";
1517 buf += utostr(ObjCBcLabelNo.back());
1518 ReplaceText(startLoc, strlen("break"), buf);
1519
1520 return 0;
1521}
1522
1523/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1524/// statement to continue with its inner synthesized loop.
1525///
1526Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1527 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1528 return S;
1529 // replace continue with goto __continue_label
1530 std::string buf;
1531
1532 SourceLocation startLoc = S->getLocStart();
1533 buf = "goto __continue_label_";
1534 buf += utostr(ObjCBcLabelNo.back());
1535 ReplaceText(startLoc, strlen("continue"), buf);
1536
1537 return 0;
1538}
1539
1540/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1541/// It rewrites:
1542/// for ( type elem in collection) { stmts; }
1543
1544/// Into:
1545/// {
1546/// type elem;
1547/// struct __objcFastEnumerationState enumState = { 0 };
1548/// id __rw_items[16];
1549/// id l_collection = (id)collection;
1550/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1551/// objects:__rw_items count:16];
1552/// if (limit) {
1553/// unsigned long startMutations = *enumState.mutationsPtr;
1554/// do {
1555/// unsigned long counter = 0;
1556/// do {
1557/// if (startMutations != *enumState.mutationsPtr)
1558/// objc_enumerationMutation(l_collection);
1559/// elem = (type)enumState.itemsPtr[counter++];
1560/// stmts;
1561/// __continue_label: ;
1562/// } while (counter < limit);
1563/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1564/// objects:__rw_items count:16]);
1565/// elem = nil;
1566/// __break_label: ;
1567/// }
1568/// else
1569/// elem = nil;
1570/// }
1571///
1572Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1573 SourceLocation OrigEnd) {
1574 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1575 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1576 "ObjCForCollectionStmt Statement stack mismatch");
1577 assert(!ObjCBcLabelNo.empty() &&
1578 "ObjCForCollectionStmt - Label No stack empty");
1579
1580 SourceLocation startLoc = S->getLocStart();
1581 const char *startBuf = SM->getCharacterData(startLoc);
1582 StringRef elementName;
1583 std::string elementTypeAsString;
1584 std::string buf;
1585 buf = "\n{\n\t";
1586 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1587 // type elem;
1588 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1589 QualType ElementType = cast<ValueDecl>(D)->getType();
1590 if (ElementType->isObjCQualifiedIdType() ||
1591 ElementType->isObjCQualifiedInterfaceType())
1592 // Simply use 'id' for all qualified types.
1593 elementTypeAsString = "id";
1594 else
1595 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1596 buf += elementTypeAsString;
1597 buf += " ";
1598 elementName = D->getName();
1599 buf += elementName;
1600 buf += ";\n\t";
1601 }
1602 else {
1603 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1604 elementName = DR->getDecl()->getName();
1605 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1606 if (VD->getType()->isObjCQualifiedIdType() ||
1607 VD->getType()->isObjCQualifiedInterfaceType())
1608 // Simply use 'id' for all qualified types.
1609 elementTypeAsString = "id";
1610 else
1611 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1612 }
1613
1614 // struct __objcFastEnumerationState enumState = { 0 };
1615 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1616 // id __rw_items[16];
1617 buf += "id __rw_items[16];\n\t";
1618 // id l_collection = (id)
1619 buf += "id l_collection = (id)";
1620 // Find start location of 'collection' the hard way!
1621 const char *startCollectionBuf = startBuf;
1622 startCollectionBuf += 3; // skip 'for'
1623 startCollectionBuf = strchr(startCollectionBuf, '(');
1624 startCollectionBuf++; // skip '('
1625 // find 'in' and skip it.
1626 while (*startCollectionBuf != ' ' ||
1627 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1628 (*(startCollectionBuf+3) != ' ' &&
1629 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1630 startCollectionBuf++;
1631 startCollectionBuf += 3;
1632
1633 // Replace: "for (type element in" with string constructed thus far.
1634 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1635 // Replace ')' in for '(' type elem in collection ')' with ';'
1636 SourceLocation rightParenLoc = S->getRParenLoc();
1637 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1638 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1639 buf = ";\n\t";
1640
1641 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1642 // objects:__rw_items count:16];
1643 // which is synthesized into:
1644 // unsigned int limit =
1645 // ((unsigned int (*)
1646 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1647 // (void *)objc_msgSend)((id)l_collection,
1648 // sel_registerName(
1649 // "countByEnumeratingWithState:objects:count:"),
1650 // (struct __objcFastEnumerationState *)&state,
1651 // (id *)__rw_items, (unsigned int)16);
1652 buf += "unsigned long limit =\n\t\t";
1653 SynthCountByEnumWithState(buf);
1654 buf += ";\n\t";
1655 /// if (limit) {
1656 /// unsigned long startMutations = *enumState.mutationsPtr;
1657 /// do {
1658 /// unsigned long counter = 0;
1659 /// do {
1660 /// if (startMutations != *enumState.mutationsPtr)
1661 /// objc_enumerationMutation(l_collection);
1662 /// elem = (type)enumState.itemsPtr[counter++];
1663 buf += "if (limit) {\n\t";
1664 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1665 buf += "do {\n\t\t";
1666 buf += "unsigned long counter = 0;\n\t\t";
1667 buf += "do {\n\t\t\t";
1668 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1669 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1670 buf += elementName;
1671 buf += " = (";
1672 buf += elementTypeAsString;
1673 buf += ")enumState.itemsPtr[counter++];";
1674 // Replace ')' in for '(' type elem in collection ')' with all of these.
1675 ReplaceText(lparenLoc, 1, buf);
1676
1677 /// __continue_label: ;
1678 /// } while (counter < limit);
1679 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1680 /// objects:__rw_items count:16]);
1681 /// elem = nil;
1682 /// __break_label: ;
1683 /// }
1684 /// else
1685 /// elem = nil;
1686 /// }
1687 ///
1688 buf = ";\n\t";
1689 buf += "__continue_label_";
1690 buf += utostr(ObjCBcLabelNo.back());
1691 buf += ": ;";
1692 buf += "\n\t\t";
1693 buf += "} while (counter < limit);\n\t";
1694 buf += "} while (limit = ";
1695 SynthCountByEnumWithState(buf);
1696 buf += ");\n\t";
1697 buf += elementName;
1698 buf += " = ((";
1699 buf += elementTypeAsString;
1700 buf += ")0);\n\t";
1701 buf += "__break_label_";
1702 buf += utostr(ObjCBcLabelNo.back());
1703 buf += ": ;\n\t";
1704 buf += "}\n\t";
1705 buf += "else\n\t\t";
1706 buf += elementName;
1707 buf += " = ((";
1708 buf += elementTypeAsString;
1709 buf += ")0);\n\t";
1710 buf += "}\n";
1711
1712 // Insert all these *after* the statement body.
1713 // FIXME: If this should support Obj-C++, support CXXTryStmt
1714 if (isa<CompoundStmt>(S->getBody())) {
1715 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1716 InsertText(endBodyLoc, buf);
1717 } else {
1718 /* Need to treat single statements specially. For example:
1719 *
1720 * for (A *a in b) if (stuff()) break;
1721 * for (A *a in b) xxxyy;
1722 *
1723 * The following code simply scans ahead to the semi to find the actual end.
1724 */
1725 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1726 const char *semiBuf = strchr(stmtBuf, ';');
1727 assert(semiBuf && "Can't find ';'");
1728 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1729 InsertText(endBodyLoc, buf);
1730 }
1731 Stmts.pop_back();
1732 ObjCBcLabelNo.pop_back();
1733 return 0;
1734}
1735
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001736static void Write_RethrowObject(std::string &buf) {
1737 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1738 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1739 buf += "\tid rethrow;\n";
1740 buf += "\t} _fin_force_rethow(_rethrow);";
1741}
1742
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001743/// RewriteObjCSynchronizedStmt -
1744/// This routine rewrites @synchronized(expr) stmt;
1745/// into:
1746/// objc_sync_enter(expr);
1747/// @try stmt @finally { objc_sync_exit(expr); }
1748///
1749Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1750 // Get the start location and compute the semi location.
1751 SourceLocation startLoc = S->getLocStart();
1752 const char *startBuf = SM->getCharacterData(startLoc);
1753
1754 assert((*startBuf == '@') && "bogus @synchronized location");
1755
1756 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001757 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001758
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001759 const char *lparenBuf = startBuf;
1760 while (*lparenBuf != '(') lparenBuf++;
1761 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001762
1763 buf = "; objc_sync_enter(_sync_obj);\n";
1764 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1765 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1766 buf += "\n\tid sync_exit;";
1767 buf += "\n\t} _sync_exit(_sync_obj);\n";
1768
1769 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1770 // the sync expression is typically a message expression that's already
1771 // been rewritten! (which implies the SourceLocation's are invalid).
1772 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1773 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1774 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1775 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1776
1777 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1778 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1779 assert (*LBraceLocBuf == '{');
1780 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001781
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001782 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001783 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1784 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001785
1786 buf = "} catch (id e) {_rethrow = e;}\n";
1787 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001788 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001789 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001790
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001791 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001792
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001793 return 0;
1794}
1795
1796void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1797{
1798 // Perform a bottom up traversal of all children.
1799 for (Stmt::child_range CI = S->children(); CI; ++CI)
1800 if (*CI)
1801 WarnAboutReturnGotoStmts(*CI);
1802
1803 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1804 Diags.Report(Context->getFullLoc(S->getLocStart()),
1805 TryFinallyContainsReturnDiag);
1806 }
1807 return;
1808}
1809
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001810Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001811 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001812 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001813 std::string buf;
1814
1815 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001816 if (noCatch)
1817 buf = "{ id volatile _rethrow = 0;\n";
1818 else {
1819 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1820 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001821 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001822 // Get the start location and compute the semi location.
1823 SourceLocation startLoc = S->getLocStart();
1824 const char *startBuf = SM->getCharacterData(startLoc);
1825
1826 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001827 if (finalStmt)
1828 ReplaceText(startLoc, 1, buf);
1829 else
1830 // @try -> try
1831 ReplaceText(startLoc, 1, "");
1832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001833 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1834 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001835 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001836
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001837 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001838 bool AtRemoved = false;
1839 if (catchDecl) {
1840 QualType t = catchDecl->getType();
1841 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1842 // Should be a pointer to a class.
1843 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1844 if (IDecl) {
1845 std::string Result;
1846 startBuf = SM->getCharacterData(startLoc);
1847 assert((*startBuf == '@') && "bogus @catch location");
1848 SourceLocation rParenLoc = Catch->getRParenLoc();
1849 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1850
1851 // _objc_exc_Foo *_e as argument to catch.
1852 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1853 Result += " *_"; Result += catchDecl->getNameAsString();
1854 Result += ")";
1855 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1856 // Foo *e = (Foo *)_e;
1857 Result.clear();
1858 Result = "{ ";
1859 Result += IDecl->getNameAsString();
1860 Result += " *"; Result += catchDecl->getNameAsString();
1861 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1862 Result += "_"; Result += catchDecl->getNameAsString();
1863
1864 Result += "; ";
1865 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1866 ReplaceText(lBraceLoc, 1, Result);
1867 AtRemoved = true;
1868 }
1869 }
1870 }
1871 if (!AtRemoved)
1872 // @catch -> catch
1873 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001874
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001875 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001876 if (finalStmt) {
1877 buf.clear();
1878 if (noCatch)
1879 buf = "catch (id e) {_rethrow = e;}\n";
1880 else
1881 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1882
1883 SourceLocation startFinalLoc = finalStmt->getLocStart();
1884 ReplaceText(startFinalLoc, 8, buf);
1885 Stmt *body = finalStmt->getFinallyBody();
1886 SourceLocation startFinalBodyLoc = body->getLocStart();
1887 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001888 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001889 ReplaceText(startFinalBodyLoc, 1, buf);
1890
1891 SourceLocation endFinalBodyLoc = body->getLocEnd();
1892 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001893 // Now check for any return/continue/go statements within the @try.
1894 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001895 }
1896
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001897 return 0;
1898}
1899
1900// This can't be done with ReplaceStmt(S, ThrowExpr), since
1901// the throw expression is typically a message expression that's already
1902// been rewritten! (which implies the SourceLocation's are invalid).
1903Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1904 // Get the start location and compute the semi location.
1905 SourceLocation startLoc = S->getLocStart();
1906 const char *startBuf = SM->getCharacterData(startLoc);
1907
1908 assert((*startBuf == '@') && "bogus @throw location");
1909
1910 std::string buf;
1911 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1912 if (S->getThrowExpr())
1913 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001914 else
1915 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001916
1917 // handle "@ throw" correctly.
1918 const char *wBuf = strchr(startBuf, 'w');
1919 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1920 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1921
1922 const char *semiBuf = strchr(startBuf, ';');
1923 assert((*semiBuf == ';') && "@throw: can't find ';'");
1924 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001925 if (S->getThrowExpr())
1926 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001927 return 0;
1928}
1929
1930Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1931 // Create a new string expression.
1932 QualType StrType = Context->getPointerType(Context->CharTy);
1933 std::string StrEncoding;
1934 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1935 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1936 StringLiteral::Ascii, false,
1937 StrType, SourceLocation());
1938 ReplaceStmt(Exp, Replacement);
1939
1940 // Replace this subexpr in the parent.
1941 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1942 return Replacement;
1943}
1944
1945Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1946 if (!SelGetUidFunctionDecl)
1947 SynthSelGetUidFunctionDecl();
1948 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1949 // Create a call to sel_registerName("selName").
1950 SmallVector<Expr*, 8> SelExprs;
1951 QualType argType = Context->getPointerType(Context->CharTy);
1952 SelExprs.push_back(StringLiteral::Create(*Context,
1953 Exp->getSelector().getAsString(),
1954 StringLiteral::Ascii, false,
1955 argType, SourceLocation()));
1956 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1957 &SelExprs[0], SelExprs.size());
1958 ReplaceStmt(Exp, SelExp);
1959 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1960 return SelExp;
1961}
1962
1963CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1964 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1965 SourceLocation EndLoc) {
1966 // Get the type, we will need to reference it in a couple spots.
1967 QualType msgSendType = FD->getType();
1968
1969 // Create a reference to the objc_msgSend() declaration.
1970 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001971 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001972
1973 // Now, we cast the reference to a pointer to the objc_msgSend type.
1974 QualType pToFunc = Context->getPointerType(msgSendType);
1975 ImplicitCastExpr *ICE =
1976 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1977 DRE, 0, VK_RValue);
1978
1979 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1980
1981 CallExpr *Exp =
1982 new (Context) CallExpr(*Context, ICE, args, nargs,
1983 FT->getCallResultType(*Context),
1984 VK_RValue, EndLoc);
1985 return Exp;
1986}
1987
1988static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1989 const char *&startRef, const char *&endRef) {
1990 while (startBuf < endBuf) {
1991 if (*startBuf == '<')
1992 startRef = startBuf; // mark the start.
1993 if (*startBuf == '>') {
1994 if (startRef && *startRef == '<') {
1995 endRef = startBuf; // mark the end.
1996 return true;
1997 }
1998 return false;
1999 }
2000 startBuf++;
2001 }
2002 return false;
2003}
2004
2005static void scanToNextArgument(const char *&argRef) {
2006 int angle = 0;
2007 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2008 if (*argRef == '<')
2009 angle++;
2010 else if (*argRef == '>')
2011 angle--;
2012 argRef++;
2013 }
2014 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2015}
2016
2017bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2018 if (T->isObjCQualifiedIdType())
2019 return true;
2020 if (const PointerType *PT = T->getAs<PointerType>()) {
2021 if (PT->getPointeeType()->isObjCQualifiedIdType())
2022 return true;
2023 }
2024 if (T->isObjCObjectPointerType()) {
2025 T = T->getPointeeType();
2026 return T->isObjCQualifiedInterfaceType();
2027 }
2028 if (T->isArrayType()) {
2029 QualType ElemTy = Context->getBaseElementType(T);
2030 return needToScanForQualifiers(ElemTy);
2031 }
2032 return false;
2033}
2034
2035void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2036 QualType Type = E->getType();
2037 if (needToScanForQualifiers(Type)) {
2038 SourceLocation Loc, EndLoc;
2039
2040 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2041 Loc = ECE->getLParenLoc();
2042 EndLoc = ECE->getRParenLoc();
2043 } else {
2044 Loc = E->getLocStart();
2045 EndLoc = E->getLocEnd();
2046 }
2047 // This will defend against trying to rewrite synthesized expressions.
2048 if (Loc.isInvalid() || EndLoc.isInvalid())
2049 return;
2050
2051 const char *startBuf = SM->getCharacterData(Loc);
2052 const char *endBuf = SM->getCharacterData(EndLoc);
2053 const char *startRef = 0, *endRef = 0;
2054 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2055 // Get the locations of the startRef, endRef.
2056 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2057 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2058 // Comment out the protocol references.
2059 InsertText(LessLoc, "/*");
2060 InsertText(GreaterLoc, "*/");
2061 }
2062 }
2063}
2064
2065void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2066 SourceLocation Loc;
2067 QualType Type;
2068 const FunctionProtoType *proto = 0;
2069 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2070 Loc = VD->getLocation();
2071 Type = VD->getType();
2072 }
2073 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2074 Loc = FD->getLocation();
2075 // Check for ObjC 'id' and class types that have been adorned with protocol
2076 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2077 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2078 assert(funcType && "missing function type");
2079 proto = dyn_cast<FunctionProtoType>(funcType);
2080 if (!proto)
2081 return;
2082 Type = proto->getResultType();
2083 }
2084 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2085 Loc = FD->getLocation();
2086 Type = FD->getType();
2087 }
2088 else
2089 return;
2090
2091 if (needToScanForQualifiers(Type)) {
2092 // Since types are unique, we need to scan the buffer.
2093
2094 const char *endBuf = SM->getCharacterData(Loc);
2095 const char *startBuf = endBuf;
2096 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2097 startBuf--; // scan backward (from the decl location) for return type.
2098 const char *startRef = 0, *endRef = 0;
2099 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2100 // Get the locations of the startRef, endRef.
2101 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2102 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2103 // Comment out the protocol references.
2104 InsertText(LessLoc, "/*");
2105 InsertText(GreaterLoc, "*/");
2106 }
2107 }
2108 if (!proto)
2109 return; // most likely, was a variable
2110 // Now check arguments.
2111 const char *startBuf = SM->getCharacterData(Loc);
2112 const char *startFuncBuf = startBuf;
2113 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2114 if (needToScanForQualifiers(proto->getArgType(i))) {
2115 // Since types are unique, we need to scan the buffer.
2116
2117 const char *endBuf = startBuf;
2118 // scan forward (from the decl location) for argument types.
2119 scanToNextArgument(endBuf);
2120 const char *startRef = 0, *endRef = 0;
2121 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2122 // Get the locations of the startRef, endRef.
2123 SourceLocation LessLoc =
2124 Loc.getLocWithOffset(startRef-startFuncBuf);
2125 SourceLocation GreaterLoc =
2126 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2127 // Comment out the protocol references.
2128 InsertText(LessLoc, "/*");
2129 InsertText(GreaterLoc, "*/");
2130 }
2131 startBuf = ++endBuf;
2132 }
2133 else {
2134 // If the function name is derived from a macro expansion, then the
2135 // argument buffer will not follow the name. Need to speak with Chris.
2136 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2137 startBuf++; // scan forward (from the decl location) for argument types.
2138 startBuf++;
2139 }
2140 }
2141}
2142
2143void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2144 QualType QT = ND->getType();
2145 const Type* TypePtr = QT->getAs<Type>();
2146 if (!isa<TypeOfExprType>(TypePtr))
2147 return;
2148 while (isa<TypeOfExprType>(TypePtr)) {
2149 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2150 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2151 TypePtr = QT->getAs<Type>();
2152 }
2153 // FIXME. This will not work for multiple declarators; as in:
2154 // __typeof__(a) b,c,d;
2155 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2156 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2157 const char *startBuf = SM->getCharacterData(DeclLoc);
2158 if (ND->getInit()) {
2159 std::string Name(ND->getNameAsString());
2160 TypeAsString += " " + Name + " = ";
2161 Expr *E = ND->getInit();
2162 SourceLocation startLoc;
2163 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2164 startLoc = ECE->getLParenLoc();
2165 else
2166 startLoc = E->getLocStart();
2167 startLoc = SM->getExpansionLoc(startLoc);
2168 const char *endBuf = SM->getCharacterData(startLoc);
2169 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2170 }
2171 else {
2172 SourceLocation X = ND->getLocEnd();
2173 X = SM->getExpansionLoc(X);
2174 const char *endBuf = SM->getCharacterData(X);
2175 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2176 }
2177}
2178
2179// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2180void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2181 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2182 SmallVector<QualType, 16> ArgTys;
2183 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2184 QualType getFuncType =
2185 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2186 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2187 SourceLocation(),
2188 SourceLocation(),
2189 SelGetUidIdent, getFuncType, 0,
2190 SC_Extern,
2191 SC_None, false);
2192}
2193
2194void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2195 // declared in <objc/objc.h>
2196 if (FD->getIdentifier() &&
2197 FD->getName() == "sel_registerName") {
2198 SelGetUidFunctionDecl = FD;
2199 return;
2200 }
2201 RewriteObjCQualifiedInterfaceTypes(FD);
2202}
2203
2204void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2205 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2206 const char *argPtr = TypeString.c_str();
2207 if (!strchr(argPtr, '^')) {
2208 Str += TypeString;
2209 return;
2210 }
2211 while (*argPtr) {
2212 Str += (*argPtr == '^' ? '*' : *argPtr);
2213 argPtr++;
2214 }
2215}
2216
2217// FIXME. Consolidate this routine with RewriteBlockPointerType.
2218void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2219 ValueDecl *VD) {
2220 QualType Type = VD->getType();
2221 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2222 const char *argPtr = TypeString.c_str();
2223 int paren = 0;
2224 while (*argPtr) {
2225 switch (*argPtr) {
2226 case '(':
2227 Str += *argPtr;
2228 paren++;
2229 break;
2230 case ')':
2231 Str += *argPtr;
2232 paren--;
2233 break;
2234 case '^':
2235 Str += '*';
2236 if (paren == 1)
2237 Str += VD->getNameAsString();
2238 break;
2239 default:
2240 Str += *argPtr;
2241 break;
2242 }
2243 argPtr++;
2244 }
2245}
2246
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002247void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2248 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2249 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2250 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2251 if (!proto)
2252 return;
2253 QualType Type = proto->getResultType();
2254 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2255 FdStr += " ";
2256 FdStr += FD->getName();
2257 FdStr += "(";
2258 unsigned numArgs = proto->getNumArgs();
2259 for (unsigned i = 0; i < numArgs; i++) {
2260 QualType ArgType = proto->getArgType(i);
2261 RewriteBlockPointerType(FdStr, ArgType);
2262 if (i+1 < numArgs)
2263 FdStr += ", ";
2264 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002265 if (FD->isVariadic()) {
2266 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2267 }
2268 else
2269 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002270 InsertText(FunLocStart, FdStr);
2271}
2272
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002273// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002274void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2275 if (SuperContructorFunctionDecl)
2276 return;
2277 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2278 SmallVector<QualType, 16> ArgTys;
2279 QualType argT = Context->getObjCIdType();
2280 assert(!argT.isNull() && "Can't find 'id' type");
2281 ArgTys.push_back(argT);
2282 ArgTys.push_back(argT);
2283 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2284 &ArgTys[0], ArgTys.size());
2285 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2286 SourceLocation(),
2287 SourceLocation(),
2288 msgSendIdent, msgSendType, 0,
2289 SC_Extern,
2290 SC_None, false);
2291}
2292
2293// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2294void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2295 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2296 SmallVector<QualType, 16> ArgTys;
2297 QualType argT = Context->getObjCIdType();
2298 assert(!argT.isNull() && "Can't find 'id' type");
2299 ArgTys.push_back(argT);
2300 argT = Context->getObjCSelType();
2301 assert(!argT.isNull() && "Can't find 'SEL' type");
2302 ArgTys.push_back(argT);
2303 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2304 &ArgTys[0], ArgTys.size(),
2305 true /*isVariadic*/);
2306 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2307 SourceLocation(),
2308 SourceLocation(),
2309 msgSendIdent, msgSendType, 0,
2310 SC_Extern,
2311 SC_None, false);
2312}
2313
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002314// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002315void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2316 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002317 SmallVector<QualType, 2> ArgTys;
2318 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002319 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002320 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002321 true /*isVariadic*/);
2322 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2323 SourceLocation(),
2324 SourceLocation(),
2325 msgSendIdent, msgSendType, 0,
2326 SC_Extern,
2327 SC_None, false);
2328}
2329
2330// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2331void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2332 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2333 SmallVector<QualType, 16> ArgTys;
2334 QualType argT = Context->getObjCIdType();
2335 assert(!argT.isNull() && "Can't find 'id' type");
2336 ArgTys.push_back(argT);
2337 argT = Context->getObjCSelType();
2338 assert(!argT.isNull() && "Can't find 'SEL' type");
2339 ArgTys.push_back(argT);
2340 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2341 &ArgTys[0], ArgTys.size(),
2342 true /*isVariadic*/);
2343 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2344 SourceLocation(),
2345 SourceLocation(),
2346 msgSendIdent, msgSendType, 0,
2347 SC_Extern,
2348 SC_None, false);
2349}
2350
2351// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002352// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002353void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2354 IdentifierInfo *msgSendIdent =
2355 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002356 SmallVector<QualType, 2> ArgTys;
2357 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002358 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002359 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002360 true /*isVariadic*/);
2361 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2362 SourceLocation(),
2363 SourceLocation(),
2364 msgSendIdent, msgSendType, 0,
2365 SC_Extern,
2366 SC_None, false);
2367}
2368
2369// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2370void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2371 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2372 SmallVector<QualType, 16> ArgTys;
2373 QualType argT = Context->getObjCIdType();
2374 assert(!argT.isNull() && "Can't find 'id' type");
2375 ArgTys.push_back(argT);
2376 argT = Context->getObjCSelType();
2377 assert(!argT.isNull() && "Can't find 'SEL' type");
2378 ArgTys.push_back(argT);
2379 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2380 &ArgTys[0], ArgTys.size(),
2381 true /*isVariadic*/);
2382 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2383 SourceLocation(),
2384 SourceLocation(),
2385 msgSendIdent, msgSendType, 0,
2386 SC_Extern,
2387 SC_None, false);
2388}
2389
2390// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2391void RewriteModernObjC::SynthGetClassFunctionDecl() {
2392 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2393 SmallVector<QualType, 16> ArgTys;
2394 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2395 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2396 &ArgTys[0], ArgTys.size());
2397 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2398 SourceLocation(),
2399 SourceLocation(),
2400 getClassIdent, getClassType, 0,
2401 SC_Extern,
2402 SC_None, false);
2403}
2404
2405// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2406void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2407 IdentifierInfo *getSuperClassIdent =
2408 &Context->Idents.get("class_getSuperclass");
2409 SmallVector<QualType, 16> ArgTys;
2410 ArgTys.push_back(Context->getObjCClassType());
2411 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2412 &ArgTys[0], ArgTys.size());
2413 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2414 SourceLocation(),
2415 SourceLocation(),
2416 getSuperClassIdent,
2417 getClassType, 0,
2418 SC_Extern,
2419 SC_None,
2420 false);
2421}
2422
2423// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2424void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2425 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2426 SmallVector<QualType, 16> ArgTys;
2427 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2428 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2429 &ArgTys[0], ArgTys.size());
2430 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2431 SourceLocation(),
2432 SourceLocation(),
2433 getClassIdent, getClassType, 0,
2434 SC_Extern,
2435 SC_None, false);
2436}
2437
2438Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2439 QualType strType = getConstantStringStructType();
2440
2441 std::string S = "__NSConstantStringImpl_";
2442
2443 std::string tmpName = InFileName;
2444 unsigned i;
2445 for (i=0; i < tmpName.length(); i++) {
2446 char c = tmpName.at(i);
2447 // replace any non alphanumeric characters with '_'.
2448 if (!isalpha(c) && (c < '0' || c > '9'))
2449 tmpName[i] = '_';
2450 }
2451 S += tmpName;
2452 S += "_";
2453 S += utostr(NumObjCStringLiterals++);
2454
2455 Preamble += "static __NSConstantStringImpl " + S;
2456 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2457 Preamble += "0x000007c8,"; // utf8_str
2458 // The pretty printer for StringLiteral handles escape characters properly.
2459 std::string prettyBufS;
2460 llvm::raw_string_ostream prettyBuf(prettyBufS);
2461 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2462 PrintingPolicy(LangOpts));
2463 Preamble += prettyBuf.str();
2464 Preamble += ",";
2465 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2466
2467 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2468 SourceLocation(), &Context->Idents.get(S),
2469 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002470 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002471 SourceLocation());
2472 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2473 Context->getPointerType(DRE->getType()),
2474 VK_RValue, OK_Ordinary,
2475 SourceLocation());
2476 // cast to NSConstantString *
2477 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2478 CK_CPointerToObjCPointerCast, Unop);
2479 ReplaceStmt(Exp, cast);
2480 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2481 return cast;
2482}
2483
Fariborz Jahanian55947042012-03-27 20:17:30 +00002484Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2485 unsigned IntSize =
2486 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2487
2488 Expr *FlagExp = IntegerLiteral::Create(*Context,
2489 llvm::APInt(IntSize, Exp->getValue()),
2490 Context->IntTy, Exp->getLocation());
2491 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2492 CK_BitCast, FlagExp);
2493 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2494 cast);
2495 ReplaceStmt(Exp, PE);
2496 return PE;
2497}
2498
Patrick Beardeb382ec2012-04-19 00:25:12 +00002499Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002500 // synthesize declaration of helper functions needed in this routine.
2501 if (!SelGetUidFunctionDecl)
2502 SynthSelGetUidFunctionDecl();
2503 // use objc_msgSend() for all.
2504 if (!MsgSendFunctionDecl)
2505 SynthMsgSendFunctionDecl();
2506 if (!GetClassFunctionDecl)
2507 SynthGetClassFunctionDecl();
2508
2509 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2510 SourceLocation StartLoc = Exp->getLocStart();
2511 SourceLocation EndLoc = Exp->getLocEnd();
2512
2513 // Synthesize a call to objc_msgSend().
2514 SmallVector<Expr*, 4> MsgExprs;
2515 SmallVector<Expr*, 4> ClsExprs;
2516 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002517
Patrick Beardeb382ec2012-04-19 00:25:12 +00002518 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2519 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2520 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002521
Patrick Beardeb382ec2012-04-19 00:25:12 +00002522 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002523 ClsExprs.push_back(StringLiteral::Create(*Context,
2524 clsName->getName(),
2525 StringLiteral::Ascii, false,
2526 argType, SourceLocation()));
2527 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2528 &ClsExprs[0],
2529 ClsExprs.size(),
2530 StartLoc, EndLoc);
2531 MsgExprs.push_back(Cls);
2532
Patrick Beardeb382ec2012-04-19 00:25:12 +00002533 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002534 // it will be the 2nd argument.
2535 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002536 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002537 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002538 StringLiteral::Ascii, false,
2539 argType, SourceLocation()));
2540 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2541 &SelExprs[0], SelExprs.size(),
2542 StartLoc, EndLoc);
2543 MsgExprs.push_back(SelExp);
2544
Patrick Beardeb382ec2012-04-19 00:25:12 +00002545 // User provided sub-expression is the 3rd, and last, argument.
2546 Expr *subExpr = Exp->getSubExpr();
2547 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002548 QualType type = ICE->getType();
2549 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2550 CastKind CK = CK_BitCast;
2551 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2552 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002553 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002554 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002555 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002556
2557 SmallVector<QualType, 4> ArgTypes;
2558 ArgTypes.push_back(Context->getObjCIdType());
2559 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002560 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2561 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002562 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002563
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002564 QualType returnType = Exp->getType();
2565 // Get the type, we will need to reference it in a couple spots.
2566 QualType msgSendType = MsgSendFlavor->getType();
2567
2568 // Create a reference to the objc_msgSend() declaration.
2569 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2570 VK_LValue, SourceLocation());
2571
2572 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002573 Context->getPointerType(Context->VoidTy),
2574 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002575
2576 // Now do the "normal" pointer to function cast.
2577 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002578 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2579 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002580 castType = Context->getPointerType(castType);
2581 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2582 cast);
2583
2584 // Don't forget the parens to enforce the proper binding.
2585 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2586
2587 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2588 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2589 MsgExprs.size(),
2590 FT->getResultType(), VK_RValue,
2591 EndLoc);
2592 ReplaceStmt(Exp, CE);
2593 return CE;
2594}
2595
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002596Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2597 // synthesize declaration of helper functions needed in this routine.
2598 if (!SelGetUidFunctionDecl)
2599 SynthSelGetUidFunctionDecl();
2600 // use objc_msgSend() for all.
2601 if (!MsgSendFunctionDecl)
2602 SynthMsgSendFunctionDecl();
2603 if (!GetClassFunctionDecl)
2604 SynthGetClassFunctionDecl();
2605
2606 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2607 SourceLocation StartLoc = Exp->getLocStart();
2608 SourceLocation EndLoc = Exp->getLocEnd();
2609
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002610 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002611 QualType IntQT = Context->IntTy;
2612 QualType NSArrayFType =
2613 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002614 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002615 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2616 DeclRefExpr *NSArrayDRE =
2617 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2618 SourceLocation());
2619
2620 SmallVector<Expr*, 16> InitExprs;
2621 unsigned NumElements = Exp->getNumElements();
2622 unsigned UnsignedIntSize =
2623 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2624 Expr *count = IntegerLiteral::Create(*Context,
2625 llvm::APInt(UnsignedIntSize, NumElements),
2626 Context->UnsignedIntTy, SourceLocation());
2627 InitExprs.push_back(count);
2628 for (unsigned i = 0; i < NumElements; i++)
2629 InitExprs.push_back(Exp->getElement(i));
2630 Expr *NSArrayCallExpr =
2631 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2632 NSArrayFType, VK_LValue, SourceLocation());
2633
2634 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2635 SourceLocation(),
2636 &Context->Idents.get("arr"),
2637 Context->getPointerType(Context->VoidPtrTy), 0,
2638 /*BitWidth=*/0, /*Mutable=*/true,
2639 /*HasInit=*/false);
2640 MemberExpr *ArrayLiteralME =
2641 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2642 SourceLocation(),
2643 ARRFD->getType(), VK_LValue,
2644 OK_Ordinary);
2645 QualType ConstIdT = Context->getObjCIdType().withConst();
2646 CStyleCastExpr * ArrayLiteralObjects =
2647 NoTypeInfoCStyleCastExpr(Context,
2648 Context->getPointerType(ConstIdT),
2649 CK_BitCast,
2650 ArrayLiteralME);
2651
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002652 // Synthesize a call to objc_msgSend().
2653 SmallVector<Expr*, 32> MsgExprs;
2654 SmallVector<Expr*, 4> ClsExprs;
2655 QualType argType = Context->getPointerType(Context->CharTy);
2656 QualType expType = Exp->getType();
2657
2658 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2659 ObjCInterfaceDecl *Class =
2660 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2661
2662 IdentifierInfo *clsName = Class->getIdentifier();
2663 ClsExprs.push_back(StringLiteral::Create(*Context,
2664 clsName->getName(),
2665 StringLiteral::Ascii, false,
2666 argType, SourceLocation()));
2667 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2668 &ClsExprs[0],
2669 ClsExprs.size(),
2670 StartLoc, EndLoc);
2671 MsgExprs.push_back(Cls);
2672
2673 // Create a call to sel_registerName("arrayWithObjects:count:").
2674 // it will be the 2nd argument.
2675 SmallVector<Expr*, 4> SelExprs;
2676 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2677 SelExprs.push_back(StringLiteral::Create(*Context,
2678 ArrayMethod->getSelector().getAsString(),
2679 StringLiteral::Ascii, false,
2680 argType, SourceLocation()));
2681 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2682 &SelExprs[0], SelExprs.size(),
2683 StartLoc, EndLoc);
2684 MsgExprs.push_back(SelExp);
2685
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002686 // (const id [])objects
2687 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002688
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002689 // (NSUInteger)cnt
2690 Expr *cnt = IntegerLiteral::Create(*Context,
2691 llvm::APInt(UnsignedIntSize, NumElements),
2692 Context->UnsignedIntTy, SourceLocation());
2693 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002694
2695
2696 SmallVector<QualType, 4> ArgTypes;
2697 ArgTypes.push_back(Context->getObjCIdType());
2698 ArgTypes.push_back(Context->getObjCSelType());
2699 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2700 E = ArrayMethod->param_end(); PI != E; ++PI)
2701 ArgTypes.push_back((*PI)->getType());
2702
2703 QualType returnType = Exp->getType();
2704 // Get the type, we will need to reference it in a couple spots.
2705 QualType msgSendType = MsgSendFlavor->getType();
2706
2707 // Create a reference to the objc_msgSend() declaration.
2708 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2709 VK_LValue, SourceLocation());
2710
2711 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2712 Context->getPointerType(Context->VoidTy),
2713 CK_BitCast, DRE);
2714
2715 // Now do the "normal" pointer to function cast.
2716 QualType castType =
2717 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2718 ArrayMethod->isVariadic());
2719 castType = Context->getPointerType(castType);
2720 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2721 cast);
2722
2723 // Don't forget the parens to enforce the proper binding.
2724 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2725
2726 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2727 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2728 MsgExprs.size(),
2729 FT->getResultType(), VK_RValue,
2730 EndLoc);
2731 ReplaceStmt(Exp, CE);
2732 return CE;
2733}
2734
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002735Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2736 // synthesize declaration of helper functions needed in this routine.
2737 if (!SelGetUidFunctionDecl)
2738 SynthSelGetUidFunctionDecl();
2739 // use objc_msgSend() for all.
2740 if (!MsgSendFunctionDecl)
2741 SynthMsgSendFunctionDecl();
2742 if (!GetClassFunctionDecl)
2743 SynthGetClassFunctionDecl();
2744
2745 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2746 SourceLocation StartLoc = Exp->getLocStart();
2747 SourceLocation EndLoc = Exp->getLocEnd();
2748
2749 // Build the expression: __NSContainer_literal(int, ...).arr
2750 QualType IntQT = Context->IntTy;
2751 QualType NSDictFType =
2752 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2753 std::string NSDictFName("__NSContainer_literal");
2754 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2755 DeclRefExpr *NSDictDRE =
2756 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2757 SourceLocation());
2758
2759 SmallVector<Expr*, 16> KeyExprs;
2760 SmallVector<Expr*, 16> ValueExprs;
2761
2762 unsigned NumElements = Exp->getNumElements();
2763 unsigned UnsignedIntSize =
2764 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2765 Expr *count = IntegerLiteral::Create(*Context,
2766 llvm::APInt(UnsignedIntSize, NumElements),
2767 Context->UnsignedIntTy, SourceLocation());
2768 KeyExprs.push_back(count);
2769 ValueExprs.push_back(count);
2770 for (unsigned i = 0; i < NumElements; i++) {
2771 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2772 KeyExprs.push_back(Element.Key);
2773 ValueExprs.push_back(Element.Value);
2774 }
2775
2776 // (const id [])objects
2777 Expr *NSValueCallExpr =
2778 new (Context) CallExpr(*Context, NSDictDRE, &ValueExprs[0], ValueExprs.size(),
2779 NSDictFType, VK_LValue, SourceLocation());
2780
2781 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2782 SourceLocation(),
2783 &Context->Idents.get("arr"),
2784 Context->getPointerType(Context->VoidPtrTy), 0,
2785 /*BitWidth=*/0, /*Mutable=*/true,
2786 /*HasInit=*/false);
2787 MemberExpr *DictLiteralValueME =
2788 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2789 SourceLocation(),
2790 ARRFD->getType(), VK_LValue,
2791 OK_Ordinary);
2792 QualType ConstIdT = Context->getObjCIdType().withConst();
2793 CStyleCastExpr * DictValueObjects =
2794 NoTypeInfoCStyleCastExpr(Context,
2795 Context->getPointerType(ConstIdT),
2796 CK_BitCast,
2797 DictLiteralValueME);
2798 // (const id <NSCopying> [])keys
2799 Expr *NSKeyCallExpr =
2800 new (Context) CallExpr(*Context, NSDictDRE, &KeyExprs[0], KeyExprs.size(),
2801 NSDictFType, VK_LValue, SourceLocation());
2802
2803 MemberExpr *DictLiteralKeyME =
2804 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2805 SourceLocation(),
2806 ARRFD->getType(), VK_LValue,
2807 OK_Ordinary);
2808
2809 CStyleCastExpr * DictKeyObjects =
2810 NoTypeInfoCStyleCastExpr(Context,
2811 Context->getPointerType(ConstIdT),
2812 CK_BitCast,
2813 DictLiteralKeyME);
2814
2815
2816
2817 // Synthesize a call to objc_msgSend().
2818 SmallVector<Expr*, 32> MsgExprs;
2819 SmallVector<Expr*, 4> ClsExprs;
2820 QualType argType = Context->getPointerType(Context->CharTy);
2821 QualType expType = Exp->getType();
2822
2823 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2824 ObjCInterfaceDecl *Class =
2825 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2826
2827 IdentifierInfo *clsName = Class->getIdentifier();
2828 ClsExprs.push_back(StringLiteral::Create(*Context,
2829 clsName->getName(),
2830 StringLiteral::Ascii, false,
2831 argType, SourceLocation()));
2832 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2833 &ClsExprs[0],
2834 ClsExprs.size(),
2835 StartLoc, EndLoc);
2836 MsgExprs.push_back(Cls);
2837
2838 // Create a call to sel_registerName("arrayWithObjects:count:").
2839 // it will be the 2nd argument.
2840 SmallVector<Expr*, 4> SelExprs;
2841 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2842 SelExprs.push_back(StringLiteral::Create(*Context,
2843 DictMethod->getSelector().getAsString(),
2844 StringLiteral::Ascii, false,
2845 argType, SourceLocation()));
2846 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2847 &SelExprs[0], SelExprs.size(),
2848 StartLoc, EndLoc);
2849 MsgExprs.push_back(SelExp);
2850
2851 // (const id [])objects
2852 MsgExprs.push_back(DictValueObjects);
2853
2854 // (const id <NSCopying> [])keys
2855 MsgExprs.push_back(DictKeyObjects);
2856
2857 // (NSUInteger)cnt
2858 Expr *cnt = IntegerLiteral::Create(*Context,
2859 llvm::APInt(UnsignedIntSize, NumElements),
2860 Context->UnsignedIntTy, SourceLocation());
2861 MsgExprs.push_back(cnt);
2862
2863
2864 SmallVector<QualType, 8> ArgTypes;
2865 ArgTypes.push_back(Context->getObjCIdType());
2866 ArgTypes.push_back(Context->getObjCSelType());
2867 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
2868 E = DictMethod->param_end(); PI != E; ++PI) {
2869 QualType T = (*PI)->getType();
2870 if (const PointerType* PT = T->getAs<PointerType>()) {
2871 QualType PointeeTy = PT->getPointeeType();
2872 convertToUnqualifiedObjCType(PointeeTy);
2873 T = Context->getPointerType(PointeeTy);
2874 }
2875 ArgTypes.push_back(T);
2876 }
2877
2878 QualType returnType = Exp->getType();
2879 // Get the type, we will need to reference it in a couple spots.
2880 QualType msgSendType = MsgSendFlavor->getType();
2881
2882 // Create a reference to the objc_msgSend() declaration.
2883 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2884 VK_LValue, SourceLocation());
2885
2886 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2887 Context->getPointerType(Context->VoidTy),
2888 CK_BitCast, DRE);
2889
2890 // Now do the "normal" pointer to function cast.
2891 QualType castType =
2892 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2893 DictMethod->isVariadic());
2894 castType = Context->getPointerType(castType);
2895 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2896 cast);
2897
2898 // Don't forget the parens to enforce the proper binding.
2899 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2900
2901 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2902 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2903 MsgExprs.size(),
2904 FT->getResultType(), VK_RValue,
2905 EndLoc);
2906 ReplaceStmt(Exp, CE);
2907 return CE;
2908}
2909
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002910// struct __rw_objc_super {
2911// struct objc_object *object; struct objc_object *superClass;
2912// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002913QualType RewriteModernObjC::getSuperStructType() {
2914 if (!SuperStructDecl) {
2915 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2916 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002917 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002918 QualType FieldTypes[2];
2919
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002920 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002921 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002922 // struct objc_object *superClass;
2923 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002924
2925 // Create fields
2926 for (unsigned i = 0; i < 2; ++i) {
2927 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2928 SourceLocation(),
2929 SourceLocation(), 0,
2930 FieldTypes[i], 0,
2931 /*BitWidth=*/0,
2932 /*Mutable=*/false,
2933 /*HasInit=*/false));
2934 }
2935
2936 SuperStructDecl->completeDefinition();
2937 }
2938 return Context->getTagDeclType(SuperStructDecl);
2939}
2940
2941QualType RewriteModernObjC::getConstantStringStructType() {
2942 if (!ConstantStringDecl) {
2943 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2944 SourceLocation(), SourceLocation(),
2945 &Context->Idents.get("__NSConstantStringImpl"));
2946 QualType FieldTypes[4];
2947
2948 // struct objc_object *receiver;
2949 FieldTypes[0] = Context->getObjCIdType();
2950 // int flags;
2951 FieldTypes[1] = Context->IntTy;
2952 // char *str;
2953 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2954 // long length;
2955 FieldTypes[3] = Context->LongTy;
2956
2957 // Create fields
2958 for (unsigned i = 0; i < 4; ++i) {
2959 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2960 ConstantStringDecl,
2961 SourceLocation(),
2962 SourceLocation(), 0,
2963 FieldTypes[i], 0,
2964 /*BitWidth=*/0,
2965 /*Mutable=*/true,
2966 /*HasInit=*/false));
2967 }
2968
2969 ConstantStringDecl->completeDefinition();
2970 }
2971 return Context->getTagDeclType(ConstantStringDecl);
2972}
2973
2974Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2975 SourceLocation StartLoc,
2976 SourceLocation EndLoc) {
2977 if (!SelGetUidFunctionDecl)
2978 SynthSelGetUidFunctionDecl();
2979 if (!MsgSendFunctionDecl)
2980 SynthMsgSendFunctionDecl();
2981 if (!MsgSendSuperFunctionDecl)
2982 SynthMsgSendSuperFunctionDecl();
2983 if (!MsgSendStretFunctionDecl)
2984 SynthMsgSendStretFunctionDecl();
2985 if (!MsgSendSuperStretFunctionDecl)
2986 SynthMsgSendSuperStretFunctionDecl();
2987 if (!MsgSendFpretFunctionDecl)
2988 SynthMsgSendFpretFunctionDecl();
2989 if (!GetClassFunctionDecl)
2990 SynthGetClassFunctionDecl();
2991 if (!GetSuperClassFunctionDecl)
2992 SynthGetSuperClassFunctionDecl();
2993 if (!GetMetaClassFunctionDecl)
2994 SynthGetMetaClassFunctionDecl();
2995
2996 // default to objc_msgSend().
2997 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2998 // May need to use objc_msgSend_stret() as well.
2999 FunctionDecl *MsgSendStretFlavor = 0;
3000 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3001 QualType resultType = mDecl->getResultType();
3002 if (resultType->isRecordType())
3003 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3004 else if (resultType->isRealFloatingType())
3005 MsgSendFlavor = MsgSendFpretFunctionDecl;
3006 }
3007
3008 // Synthesize a call to objc_msgSend().
3009 SmallVector<Expr*, 8> MsgExprs;
3010 switch (Exp->getReceiverKind()) {
3011 case ObjCMessageExpr::SuperClass: {
3012 MsgSendFlavor = MsgSendSuperFunctionDecl;
3013 if (MsgSendStretFlavor)
3014 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3015 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3016
3017 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3018
3019 SmallVector<Expr*, 4> InitExprs;
3020
3021 // set the receiver to self, the first argument to all methods.
3022 InitExprs.push_back(
3023 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3024 CK_BitCast,
3025 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003026 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003027 Context->getObjCIdType(),
3028 VK_RValue,
3029 SourceLocation()))
3030 ); // set the 'receiver'.
3031
3032 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3033 SmallVector<Expr*, 8> ClsExprs;
3034 QualType argType = Context->getPointerType(Context->CharTy);
3035 ClsExprs.push_back(StringLiteral::Create(*Context,
3036 ClassDecl->getIdentifier()->getName(),
3037 StringLiteral::Ascii, false,
3038 argType, SourceLocation()));
3039 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3040 &ClsExprs[0],
3041 ClsExprs.size(),
3042 StartLoc,
3043 EndLoc);
3044 // (Class)objc_getClass("CurrentClass")
3045 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3046 Context->getObjCClassType(),
3047 CK_BitCast, Cls);
3048 ClsExprs.clear();
3049 ClsExprs.push_back(ArgExpr);
3050 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3051 &ClsExprs[0], ClsExprs.size(),
3052 StartLoc, EndLoc);
3053
3054 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3055 // To turn off a warning, type-cast to 'id'
3056 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3057 NoTypeInfoCStyleCastExpr(Context,
3058 Context->getObjCIdType(),
3059 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003060 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003061 QualType superType = getSuperStructType();
3062 Expr *SuperRep;
3063
3064 if (LangOpts.MicrosoftExt) {
3065 SynthSuperContructorFunctionDecl();
3066 // Simulate a contructor call...
3067 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003068 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003069 SourceLocation());
3070 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3071 InitExprs.size(),
3072 superType, VK_LValue,
3073 SourceLocation());
3074 // The code for super is a little tricky to prevent collision with
3075 // the structure definition in the header. The rewriter has it's own
3076 // internal definition (__rw_objc_super) that is uses. This is why
3077 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003078 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003079 //
3080 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3081 Context->getPointerType(SuperRep->getType()),
3082 VK_RValue, OK_Ordinary,
3083 SourceLocation());
3084 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3085 Context->getPointerType(superType),
3086 CK_BitCast, SuperRep);
3087 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003088 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003089 InitListExpr *ILE =
3090 new (Context) InitListExpr(*Context, SourceLocation(),
3091 &InitExprs[0], InitExprs.size(),
3092 SourceLocation());
3093 TypeSourceInfo *superTInfo
3094 = Context->getTrivialTypeSourceInfo(superType);
3095 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3096 superType, VK_LValue,
3097 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003098 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003099 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3100 Context->getPointerType(SuperRep->getType()),
3101 VK_RValue, OK_Ordinary,
3102 SourceLocation());
3103 }
3104 MsgExprs.push_back(SuperRep);
3105 break;
3106 }
3107
3108 case ObjCMessageExpr::Class: {
3109 SmallVector<Expr*, 8> ClsExprs;
3110 QualType argType = Context->getPointerType(Context->CharTy);
3111 ObjCInterfaceDecl *Class
3112 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3113 IdentifierInfo *clsName = Class->getIdentifier();
3114 ClsExprs.push_back(StringLiteral::Create(*Context,
3115 clsName->getName(),
3116 StringLiteral::Ascii, false,
3117 argType, SourceLocation()));
3118 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3119 &ClsExprs[0],
3120 ClsExprs.size(),
3121 StartLoc, EndLoc);
3122 MsgExprs.push_back(Cls);
3123 break;
3124 }
3125
3126 case ObjCMessageExpr::SuperInstance:{
3127 MsgSendFlavor = MsgSendSuperFunctionDecl;
3128 if (MsgSendStretFlavor)
3129 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3130 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3131 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3132 SmallVector<Expr*, 4> InitExprs;
3133
3134 InitExprs.push_back(
3135 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3136 CK_BitCast,
3137 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003138 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003139 Context->getObjCIdType(),
3140 VK_RValue, SourceLocation()))
3141 ); // set the 'receiver'.
3142
3143 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3144 SmallVector<Expr*, 8> ClsExprs;
3145 QualType argType = Context->getPointerType(Context->CharTy);
3146 ClsExprs.push_back(StringLiteral::Create(*Context,
3147 ClassDecl->getIdentifier()->getName(),
3148 StringLiteral::Ascii, false, argType,
3149 SourceLocation()));
3150 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3151 &ClsExprs[0],
3152 ClsExprs.size(),
3153 StartLoc, EndLoc);
3154 // (Class)objc_getClass("CurrentClass")
3155 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3156 Context->getObjCClassType(),
3157 CK_BitCast, Cls);
3158 ClsExprs.clear();
3159 ClsExprs.push_back(ArgExpr);
3160 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3161 &ClsExprs[0], ClsExprs.size(),
3162 StartLoc, EndLoc);
3163
3164 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3165 // To turn off a warning, type-cast to 'id'
3166 InitExprs.push_back(
3167 // set 'super class', using class_getSuperclass().
3168 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3169 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003170 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003171 QualType superType = getSuperStructType();
3172 Expr *SuperRep;
3173
3174 if (LangOpts.MicrosoftExt) {
3175 SynthSuperContructorFunctionDecl();
3176 // Simulate a contructor call...
3177 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003178 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003179 SourceLocation());
3180 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3181 InitExprs.size(),
3182 superType, VK_LValue, SourceLocation());
3183 // The code for super is a little tricky to prevent collision with
3184 // the structure definition in the header. The rewriter has it's own
3185 // internal definition (__rw_objc_super) that is uses. This is why
3186 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003187 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003188 //
3189 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3190 Context->getPointerType(SuperRep->getType()),
3191 VK_RValue, OK_Ordinary,
3192 SourceLocation());
3193 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3194 Context->getPointerType(superType),
3195 CK_BitCast, SuperRep);
3196 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003197 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003198 InitListExpr *ILE =
3199 new (Context) InitListExpr(*Context, SourceLocation(),
3200 &InitExprs[0], InitExprs.size(),
3201 SourceLocation());
3202 TypeSourceInfo *superTInfo
3203 = Context->getTrivialTypeSourceInfo(superType);
3204 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3205 superType, VK_RValue, ILE,
3206 false);
3207 }
3208 MsgExprs.push_back(SuperRep);
3209 break;
3210 }
3211
3212 case ObjCMessageExpr::Instance: {
3213 // Remove all type-casts because it may contain objc-style types; e.g.
3214 // Foo<Proto> *.
3215 Expr *recExpr = Exp->getInstanceReceiver();
3216 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3217 recExpr = CE->getSubExpr();
3218 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3219 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3220 ? CK_BlockPointerToObjCPointerCast
3221 : CK_CPointerToObjCPointerCast;
3222
3223 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3224 CK, recExpr);
3225 MsgExprs.push_back(recExpr);
3226 break;
3227 }
3228 }
3229
3230 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3231 SmallVector<Expr*, 8> SelExprs;
3232 QualType argType = Context->getPointerType(Context->CharTy);
3233 SelExprs.push_back(StringLiteral::Create(*Context,
3234 Exp->getSelector().getAsString(),
3235 StringLiteral::Ascii, false,
3236 argType, SourceLocation()));
3237 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3238 &SelExprs[0], SelExprs.size(),
3239 StartLoc,
3240 EndLoc);
3241 MsgExprs.push_back(SelExp);
3242
3243 // Now push any user supplied arguments.
3244 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3245 Expr *userExpr = Exp->getArg(i);
3246 // Make all implicit casts explicit...ICE comes in handy:-)
3247 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3248 // Reuse the ICE type, it is exactly what the doctor ordered.
3249 QualType type = ICE->getType();
3250 if (needToScanForQualifiers(type))
3251 type = Context->getObjCIdType();
3252 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3253 (void)convertBlockPointerToFunctionPointer(type);
3254 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3255 CastKind CK;
3256 if (SubExpr->getType()->isIntegralType(*Context) &&
3257 type->isBooleanType()) {
3258 CK = CK_IntegralToBoolean;
3259 } else if (type->isObjCObjectPointerType()) {
3260 if (SubExpr->getType()->isBlockPointerType()) {
3261 CK = CK_BlockPointerToObjCPointerCast;
3262 } else if (SubExpr->getType()->isPointerType()) {
3263 CK = CK_CPointerToObjCPointerCast;
3264 } else {
3265 CK = CK_BitCast;
3266 }
3267 } else {
3268 CK = CK_BitCast;
3269 }
3270
3271 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3272 }
3273 // Make id<P...> cast into an 'id' cast.
3274 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3275 if (CE->getType()->isObjCQualifiedIdType()) {
3276 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3277 userExpr = CE->getSubExpr();
3278 CastKind CK;
3279 if (userExpr->getType()->isIntegralType(*Context)) {
3280 CK = CK_IntegralToPointer;
3281 } else if (userExpr->getType()->isBlockPointerType()) {
3282 CK = CK_BlockPointerToObjCPointerCast;
3283 } else if (userExpr->getType()->isPointerType()) {
3284 CK = CK_CPointerToObjCPointerCast;
3285 } else {
3286 CK = CK_BitCast;
3287 }
3288 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3289 CK, userExpr);
3290 }
3291 }
3292 MsgExprs.push_back(userExpr);
3293 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3294 // out the argument in the original expression (since we aren't deleting
3295 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3296 //Exp->setArg(i, 0);
3297 }
3298 // Generate the funky cast.
3299 CastExpr *cast;
3300 SmallVector<QualType, 8> ArgTypes;
3301 QualType returnType;
3302
3303 // Push 'id' and 'SEL', the 2 implicit arguments.
3304 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3305 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3306 else
3307 ArgTypes.push_back(Context->getObjCIdType());
3308 ArgTypes.push_back(Context->getObjCSelType());
3309 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3310 // Push any user argument types.
3311 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3312 E = OMD->param_end(); PI != E; ++PI) {
3313 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3314 ? Context->getObjCIdType()
3315 : (*PI)->getType();
3316 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3317 (void)convertBlockPointerToFunctionPointer(t);
3318 ArgTypes.push_back(t);
3319 }
3320 returnType = Exp->getType();
3321 convertToUnqualifiedObjCType(returnType);
3322 (void)convertBlockPointerToFunctionPointer(returnType);
3323 } else {
3324 returnType = Context->getObjCIdType();
3325 }
3326 // Get the type, we will need to reference it in a couple spots.
3327 QualType msgSendType = MsgSendFlavor->getType();
3328
3329 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003330 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003331 VK_LValue, SourceLocation());
3332
3333 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3334 // If we don't do this cast, we get the following bizarre warning/note:
3335 // xx.m:13: warning: function called through a non-compatible type
3336 // xx.m:13: note: if this code is reached, the program will abort
3337 cast = NoTypeInfoCStyleCastExpr(Context,
3338 Context->getPointerType(Context->VoidTy),
3339 CK_BitCast, DRE);
3340
3341 // Now do the "normal" pointer to function cast.
3342 QualType castType =
3343 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3344 // If we don't have a method decl, force a variadic cast.
3345 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3346 castType = Context->getPointerType(castType);
3347 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3348 cast);
3349
3350 // Don't forget the parens to enforce the proper binding.
3351 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3352
3353 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3354 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3355 MsgExprs.size(),
3356 FT->getResultType(), VK_RValue,
3357 EndLoc);
3358 Stmt *ReplacingStmt = CE;
3359 if (MsgSendStretFlavor) {
3360 // We have the method which returns a struct/union. Must also generate
3361 // call to objc_msgSend_stret and hang both varieties on a conditional
3362 // expression which dictate which one to envoke depending on size of
3363 // method's return type.
3364
3365 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003366 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3367 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003368 VK_LValue, SourceLocation());
3369 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3370 cast = NoTypeInfoCStyleCastExpr(Context,
3371 Context->getPointerType(Context->VoidTy),
3372 CK_BitCast, STDRE);
3373 // Now do the "normal" pointer to function cast.
3374 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3375 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3376 castType = Context->getPointerType(castType);
3377 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3378 cast);
3379
3380 // Don't forget the parens to enforce the proper binding.
3381 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3382
3383 FT = msgSendType->getAs<FunctionType>();
3384 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3385 MsgExprs.size(),
3386 FT->getResultType(), VK_RValue,
3387 SourceLocation());
3388
3389 // Build sizeof(returnType)
3390 UnaryExprOrTypeTraitExpr *sizeofExpr =
3391 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3392 Context->getTrivialTypeSourceInfo(returnType),
3393 Context->getSizeType(), SourceLocation(),
3394 SourceLocation());
3395 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3396 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3397 // For X86 it is more complicated and some kind of target specific routine
3398 // is needed to decide what to do.
3399 unsigned IntSize =
3400 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3401 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3402 llvm::APInt(IntSize, 8),
3403 Context->IntTy,
3404 SourceLocation());
3405 BinaryOperator *lessThanExpr =
3406 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3407 VK_RValue, OK_Ordinary, SourceLocation());
3408 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3409 ConditionalOperator *CondExpr =
3410 new (Context) ConditionalOperator(lessThanExpr,
3411 SourceLocation(), CE,
3412 SourceLocation(), STCE,
3413 returnType, VK_RValue, OK_Ordinary);
3414 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3415 CondExpr);
3416 }
3417 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3418 return ReplacingStmt;
3419}
3420
3421Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3422 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3423 Exp->getLocEnd());
3424
3425 // Now do the actual rewrite.
3426 ReplaceStmt(Exp, ReplacingStmt);
3427
3428 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3429 return ReplacingStmt;
3430}
3431
3432// typedef struct objc_object Protocol;
3433QualType RewriteModernObjC::getProtocolType() {
3434 if (!ProtocolTypeDecl) {
3435 TypeSourceInfo *TInfo
3436 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3437 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3438 SourceLocation(), SourceLocation(),
3439 &Context->Idents.get("Protocol"),
3440 TInfo);
3441 }
3442 return Context->getTypeDeclType(ProtocolTypeDecl);
3443}
3444
3445/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3446/// a synthesized/forward data reference (to the protocol's metadata).
3447/// The forward references (and metadata) are generated in
3448/// RewriteModernObjC::HandleTranslationUnit().
3449Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003450 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3451 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003452 IdentifierInfo *ID = &Context->Idents.get(Name);
3453 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3454 SourceLocation(), ID, getProtocolType(), 0,
3455 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003456 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3457 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003458 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3459 Context->getPointerType(DRE->getType()),
3460 VK_RValue, OK_Ordinary, SourceLocation());
3461 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3462 CK_BitCast,
3463 DerefExpr);
3464 ReplaceStmt(Exp, castExpr);
3465 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3466 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3467 return castExpr;
3468
3469}
3470
3471bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3472 const char *endBuf) {
3473 while (startBuf < endBuf) {
3474 if (*startBuf == '#') {
3475 // Skip whitespace.
3476 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3477 ;
3478 if (!strncmp(startBuf, "if", strlen("if")) ||
3479 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3480 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3481 !strncmp(startBuf, "define", strlen("define")) ||
3482 !strncmp(startBuf, "undef", strlen("undef")) ||
3483 !strncmp(startBuf, "else", strlen("else")) ||
3484 !strncmp(startBuf, "elif", strlen("elif")) ||
3485 !strncmp(startBuf, "endif", strlen("endif")) ||
3486 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3487 !strncmp(startBuf, "include", strlen("include")) ||
3488 !strncmp(startBuf, "import", strlen("import")) ||
3489 !strncmp(startBuf, "include_next", strlen("include_next")))
3490 return true;
3491 }
3492 startBuf++;
3493 }
3494 return false;
3495}
3496
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003497/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003498/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003499bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3500 std::string &Result) {
3501 if (Type->isArrayType()) {
3502 QualType ElemTy = Context->getBaseElementType(Type);
3503 return RewriteObjCFieldDeclType(ElemTy, Result);
3504 }
3505 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003506 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3507 if (RD->isCompleteDefinition()) {
3508 if (RD->isStruct())
3509 Result += "\n\tstruct ";
3510 else if (RD->isUnion())
3511 Result += "\n\tunion ";
3512 else
3513 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003514
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003515 Result += RD->getName();
3516 if (TagsDefinedInIvarDecls.count(RD)) {
3517 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003518 Result += " ";
3519 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003520 }
3521 TagsDefinedInIvarDecls.insert(RD);
3522 Result += " {\n";
3523 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003524 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003525 FieldDecl *FD = *i;
3526 RewriteObjCFieldDecl(FD, Result);
3527 }
3528 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003529 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003530 }
3531 }
3532 else if (Type->isEnumeralType()) {
3533 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3534 if (ED->isCompleteDefinition()) {
3535 Result += "\n\tenum ";
3536 Result += ED->getName();
3537 if (TagsDefinedInIvarDecls.count(ED)) {
3538 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003539 Result += " ";
3540 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003541 }
3542 TagsDefinedInIvarDecls.insert(ED);
3543
3544 Result += " {\n";
3545 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3546 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3547 Result += "\t"; Result += EC->getName(); Result += " = ";
3548 llvm::APSInt Val = EC->getInitVal();
3549 Result += Val.toString(10);
3550 Result += ",\n";
3551 }
3552 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003553 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003554 }
3555 }
3556
3557 Result += "\t";
3558 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003559 return false;
3560}
3561
3562
3563/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3564/// It handles elaborated types, as well as enum types in the process.
3565void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3566 std::string &Result) {
3567 QualType Type = fieldDecl->getType();
3568 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003569
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003570 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3571 if (!EleboratedType)
3572 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003573 Result += Name;
3574 if (fieldDecl->isBitField()) {
3575 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3576 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003577 else if (EleboratedType && Type->isArrayType()) {
3578 CanQualType CType = Context->getCanonicalType(Type);
3579 while (isa<ArrayType>(CType)) {
3580 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3581 Result += "[";
3582 llvm::APInt Dim = CAT->getSize();
3583 Result += utostr(Dim.getZExtValue());
3584 Result += "]";
3585 }
3586 CType = CType->getAs<ArrayType>()->getElementType();
3587 }
3588 }
3589
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003590 Result += ";\n";
3591}
3592
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003593/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3594/// an objective-c class with ivars.
3595void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3596 std::string &Result) {
3597 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3598 assert(CDecl->getName() != "" &&
3599 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003600 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003601 SmallVector<ObjCIvarDecl *, 8> IVars;
3602 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003603 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003604 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003605
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003606 SourceLocation LocStart = CDecl->getLocStart();
3607 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003608
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003609 const char *startBuf = SM->getCharacterData(LocStart);
3610 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003611
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003612 // If no ivars and no root or if its root, directly or indirectly,
3613 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003614 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003615 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3616 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3617 ReplaceText(LocStart, endBuf-startBuf, Result);
3618 return;
3619 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003620
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003621 Result += "\nstruct ";
3622 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003623 Result += "_IMPL {\n";
3624
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003625 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003626 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3627 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3628 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003629 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003630 TagsDefinedInIvarDecls.clear();
3631 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3632 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003633
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003634 Result += "};\n";
3635 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3636 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003637 // Mark this struct as having been generated.
3638 if (!ObjCSynthesizedStructs.insert(CDecl))
3639 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003640}
3641
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003642static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3643 ObjCIvarDecl *IvarDecl, std::string &Result) {
3644 Result += "OBJC_IVAR_$_";
3645 Result += IDecl->getName();
3646 Result += "$";
3647 Result += IvarDecl->getName();
3648}
3649
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003650/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3651/// have been referenced in an ivar access expression.
3652void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3653 std::string &Result) {
3654 // write out ivar offset symbols which have been referenced in an ivar
3655 // access expression.
3656 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3657 if (Ivars.empty())
3658 return;
3659 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3660 e = Ivars.end(); i != e; i++) {
3661 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003662 Result += "\n";
3663 if (LangOpts.MicrosoftExt)
3664 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003665 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003666 if (LangOpts.MicrosoftExt &&
3667 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003668 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3669 Result += "__declspec(dllimport) ";
3670
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003671 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003672 WriteInternalIvarName(CDecl, IvarDecl, Result);
3673 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003674 }
3675}
3676
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003677//===----------------------------------------------------------------------===//
3678// Meta Data Emission
3679//===----------------------------------------------------------------------===//
3680
3681
3682/// RewriteImplementations - This routine rewrites all method implementations
3683/// and emits meta-data.
3684
3685void RewriteModernObjC::RewriteImplementations() {
3686 int ClsDefCount = ClassImplementation.size();
3687 int CatDefCount = CategoryImplementation.size();
3688
3689 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003690 for (int i = 0; i < ClsDefCount; i++) {
3691 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3692 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3693 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003694 assert(false &&
3695 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003696 RewriteImplementationDecl(OIMP);
3697 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003698
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003699 for (int i = 0; i < CatDefCount; i++) {
3700 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3701 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3702 if (CDecl->isImplicitInterfaceDecl())
3703 assert(false &&
3704 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003705 RewriteImplementationDecl(CIMP);
3706 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003707}
3708
3709void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3710 const std::string &Name,
3711 ValueDecl *VD, bool def) {
3712 assert(BlockByRefDeclNo.count(VD) &&
3713 "RewriteByRefString: ByRef decl missing");
3714 if (def)
3715 ResultStr += "struct ";
3716 ResultStr += "__Block_byref_" + Name +
3717 "_" + utostr(BlockByRefDeclNo[VD]) ;
3718}
3719
3720static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3721 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3722 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3723 return false;
3724}
3725
3726std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3727 StringRef funcName,
3728 std::string Tag) {
3729 const FunctionType *AFT = CE->getFunctionType();
3730 QualType RT = AFT->getResultType();
3731 std::string StructRef = "struct " + Tag;
3732 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003733 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003734
3735 BlockDecl *BD = CE->getBlockDecl();
3736
3737 if (isa<FunctionNoProtoType>(AFT)) {
3738 // No user-supplied arguments. Still need to pass in a pointer to the
3739 // block (to reference imported block decl refs).
3740 S += "(" + StructRef + " *__cself)";
3741 } else if (BD->param_empty()) {
3742 S += "(" + StructRef + " *__cself)";
3743 } else {
3744 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3745 assert(FT && "SynthesizeBlockFunc: No function proto");
3746 S += '(';
3747 // first add the implicit argument.
3748 S += StructRef + " *__cself, ";
3749 std::string ParamStr;
3750 for (BlockDecl::param_iterator AI = BD->param_begin(),
3751 E = BD->param_end(); AI != E; ++AI) {
3752 if (AI != BD->param_begin()) S += ", ";
3753 ParamStr = (*AI)->getNameAsString();
3754 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003755 (void)convertBlockPointerToFunctionPointer(QT);
3756 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003757 S += ParamStr;
3758 }
3759 if (FT->isVariadic()) {
3760 if (!BD->param_empty()) S += ", ";
3761 S += "...";
3762 }
3763 S += ')';
3764 }
3765 S += " {\n";
3766
3767 // Create local declarations to avoid rewriting all closure decl ref exprs.
3768 // First, emit a declaration for all "by ref" decls.
3769 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3770 E = BlockByRefDecls.end(); I != E; ++I) {
3771 S += " ";
3772 std::string Name = (*I)->getNameAsString();
3773 std::string TypeString;
3774 RewriteByRefString(TypeString, Name, (*I));
3775 TypeString += " *";
3776 Name = TypeString + Name;
3777 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3778 }
3779 // Next, emit a declaration for all "by copy" declarations.
3780 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3781 E = BlockByCopyDecls.end(); I != E; ++I) {
3782 S += " ";
3783 // Handle nested closure invocation. For example:
3784 //
3785 // void (^myImportedClosure)(void);
3786 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3787 //
3788 // void (^anotherClosure)(void);
3789 // anotherClosure = ^(void) {
3790 // myImportedClosure(); // import and invoke the closure
3791 // };
3792 //
3793 if (isTopLevelBlockPointerType((*I)->getType())) {
3794 RewriteBlockPointerTypeVariable(S, (*I));
3795 S += " = (";
3796 RewriteBlockPointerType(S, (*I)->getType());
3797 S += ")";
3798 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3799 }
3800 else {
3801 std::string Name = (*I)->getNameAsString();
3802 QualType QT = (*I)->getType();
3803 if (HasLocalVariableExternalStorage(*I))
3804 QT = Context->getPointerType(QT);
3805 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3806 S += Name + " = __cself->" +
3807 (*I)->getNameAsString() + "; // bound by copy\n";
3808 }
3809 }
3810 std::string RewrittenStr = RewrittenBlockExprs[CE];
3811 const char *cstr = RewrittenStr.c_str();
3812 while (*cstr++ != '{') ;
3813 S += cstr;
3814 S += "\n";
3815 return S;
3816}
3817
3818std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3819 StringRef funcName,
3820 std::string Tag) {
3821 std::string StructRef = "struct " + Tag;
3822 std::string S = "static void __";
3823
3824 S += funcName;
3825 S += "_block_copy_" + utostr(i);
3826 S += "(" + StructRef;
3827 S += "*dst, " + StructRef;
3828 S += "*src) {";
3829 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3830 E = ImportedBlockDecls.end(); I != E; ++I) {
3831 ValueDecl *VD = (*I);
3832 S += "_Block_object_assign((void*)&dst->";
3833 S += (*I)->getNameAsString();
3834 S += ", (void*)src->";
3835 S += (*I)->getNameAsString();
3836 if (BlockByRefDeclsPtrSet.count((*I)))
3837 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3838 else if (VD->getType()->isBlockPointerType())
3839 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3840 else
3841 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3842 }
3843 S += "}\n";
3844
3845 S += "\nstatic void __";
3846 S += funcName;
3847 S += "_block_dispose_" + utostr(i);
3848 S += "(" + StructRef;
3849 S += "*src) {";
3850 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3851 E = ImportedBlockDecls.end(); I != E; ++I) {
3852 ValueDecl *VD = (*I);
3853 S += "_Block_object_dispose((void*)src->";
3854 S += (*I)->getNameAsString();
3855 if (BlockByRefDeclsPtrSet.count((*I)))
3856 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3857 else if (VD->getType()->isBlockPointerType())
3858 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3859 else
3860 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3861 }
3862 S += "}\n";
3863 return S;
3864}
3865
3866std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3867 std::string Desc) {
3868 std::string S = "\nstruct " + Tag;
3869 std::string Constructor = " " + Tag;
3870
3871 S += " {\n struct __block_impl impl;\n";
3872 S += " struct " + Desc;
3873 S += "* Desc;\n";
3874
3875 Constructor += "(void *fp, "; // Invoke function pointer.
3876 Constructor += "struct " + Desc; // Descriptor pointer.
3877 Constructor += " *desc";
3878
3879 if (BlockDeclRefs.size()) {
3880 // Output all "by copy" declarations.
3881 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3882 E = BlockByCopyDecls.end(); I != E; ++I) {
3883 S += " ";
3884 std::string FieldName = (*I)->getNameAsString();
3885 std::string ArgName = "_" + FieldName;
3886 // Handle nested closure invocation. For example:
3887 //
3888 // void (^myImportedBlock)(void);
3889 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3890 //
3891 // void (^anotherBlock)(void);
3892 // anotherBlock = ^(void) {
3893 // myImportedBlock(); // import and invoke the closure
3894 // };
3895 //
3896 if (isTopLevelBlockPointerType((*I)->getType())) {
3897 S += "struct __block_impl *";
3898 Constructor += ", void *" + ArgName;
3899 } else {
3900 QualType QT = (*I)->getType();
3901 if (HasLocalVariableExternalStorage(*I))
3902 QT = Context->getPointerType(QT);
3903 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3904 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3905 Constructor += ", " + ArgName;
3906 }
3907 S += FieldName + ";\n";
3908 }
3909 // Output all "by ref" declarations.
3910 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3911 E = BlockByRefDecls.end(); I != E; ++I) {
3912 S += " ";
3913 std::string FieldName = (*I)->getNameAsString();
3914 std::string ArgName = "_" + FieldName;
3915 {
3916 std::string TypeString;
3917 RewriteByRefString(TypeString, FieldName, (*I));
3918 TypeString += " *";
3919 FieldName = TypeString + FieldName;
3920 ArgName = TypeString + ArgName;
3921 Constructor += ", " + ArgName;
3922 }
3923 S += FieldName + "; // by ref\n";
3924 }
3925 // Finish writing the constructor.
3926 Constructor += ", int flags=0)";
3927 // Initialize all "by copy" arguments.
3928 bool firsTime = true;
3929 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3930 E = BlockByCopyDecls.end(); I != E; ++I) {
3931 std::string Name = (*I)->getNameAsString();
3932 if (firsTime) {
3933 Constructor += " : ";
3934 firsTime = false;
3935 }
3936 else
3937 Constructor += ", ";
3938 if (isTopLevelBlockPointerType((*I)->getType()))
3939 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3940 else
3941 Constructor += Name + "(_" + Name + ")";
3942 }
3943 // Initialize all "by ref" arguments.
3944 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3945 E = BlockByRefDecls.end(); I != E; ++I) {
3946 std::string Name = (*I)->getNameAsString();
3947 if (firsTime) {
3948 Constructor += " : ";
3949 firsTime = false;
3950 }
3951 else
3952 Constructor += ", ";
3953 Constructor += Name + "(_" + Name + "->__forwarding)";
3954 }
3955
3956 Constructor += " {\n";
3957 if (GlobalVarDecl)
3958 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3959 else
3960 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3961 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3962
3963 Constructor += " Desc = desc;\n";
3964 } else {
3965 // Finish writing the constructor.
3966 Constructor += ", int flags=0) {\n";
3967 if (GlobalVarDecl)
3968 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3969 else
3970 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3971 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3972 Constructor += " Desc = desc;\n";
3973 }
3974 Constructor += " ";
3975 Constructor += "}\n";
3976 S += Constructor;
3977 S += "};\n";
3978 return S;
3979}
3980
3981std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3982 std::string ImplTag, int i,
3983 StringRef FunName,
3984 unsigned hasCopy) {
3985 std::string S = "\nstatic struct " + DescTag;
3986
3987 S += " {\n unsigned long reserved;\n";
3988 S += " unsigned long Block_size;\n";
3989 if (hasCopy) {
3990 S += " void (*copy)(struct ";
3991 S += ImplTag; S += "*, struct ";
3992 S += ImplTag; S += "*);\n";
3993
3994 S += " void (*dispose)(struct ";
3995 S += ImplTag; S += "*);\n";
3996 }
3997 S += "} ";
3998
3999 S += DescTag + "_DATA = { 0, sizeof(struct ";
4000 S += ImplTag + ")";
4001 if (hasCopy) {
4002 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4003 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4004 }
4005 S += "};\n";
4006 return S;
4007}
4008
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004009/// getFunctionSourceLocation - returns start location of a function
4010/// definition. Complication arises when function has declared as
4011/// extern "C" or extern "C" {...}
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004012static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
4013 FunctionDecl *FD) {
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004014 if (FD->isExternC() && !FD->isMain()) {
4015 const DeclContext *DC = FD->getDeclContext();
4016 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
4017 // if it is extern "C" {...}, return function decl's own location.
4018 if (!LSD->getRBraceLoc().isValid())
4019 return LSD->getExternLoc();
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004020 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00004021 if (FD->getStorageClassAsWritten() != SC_None)
4022 R.RewriteBlockLiteralFunctionDecl(FD);
Fariborz Jahanian76a98be2012-04-17 18:40:53 +00004023 return FD->getTypeSpecStartLoc();
4024}
4025
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004026void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4027 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004028 bool RewriteSC = (GlobalVarDecl &&
4029 !Blocks.empty() &&
4030 GlobalVarDecl->getStorageClass() == SC_Static &&
4031 GlobalVarDecl->getType().getCVRQualifiers());
4032 if (RewriteSC) {
4033 std::string SC(" void __");
4034 SC += GlobalVarDecl->getNameAsString();
4035 SC += "() {}";
4036 InsertText(FunLocStart, SC);
4037 }
4038
4039 // Insert closures that were part of the function.
4040 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4041 CollectBlockDeclRefInfo(Blocks[i]);
4042 // Need to copy-in the inner copied-in variables not actually used in this
4043 // block.
4044 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004045 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004046 ValueDecl *VD = Exp->getDecl();
4047 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004048 if (!VD->hasAttr<BlocksAttr>()) {
4049 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4050 BlockByCopyDeclsPtrSet.insert(VD);
4051 BlockByCopyDecls.push_back(VD);
4052 }
4053 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004054 }
John McCallf4b88a42012-03-10 09:33:50 +00004055
4056 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004057 BlockByRefDeclsPtrSet.insert(VD);
4058 BlockByRefDecls.push_back(VD);
4059 }
John McCallf4b88a42012-03-10 09:33:50 +00004060
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004061 // imported objects in the inner blocks not used in the outer
4062 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004063 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004064 VD->getType()->isBlockPointerType())
4065 ImportedBlockDecls.insert(VD);
4066 }
4067
4068 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4069 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4070
4071 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4072
4073 InsertText(FunLocStart, CI);
4074
4075 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4076
4077 InsertText(FunLocStart, CF);
4078
4079 if (ImportedBlockDecls.size()) {
4080 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4081 InsertText(FunLocStart, HF);
4082 }
4083 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4084 ImportedBlockDecls.size() > 0);
4085 InsertText(FunLocStart, BD);
4086
4087 BlockDeclRefs.clear();
4088 BlockByRefDecls.clear();
4089 BlockByRefDeclsPtrSet.clear();
4090 BlockByCopyDecls.clear();
4091 BlockByCopyDeclsPtrSet.clear();
4092 ImportedBlockDecls.clear();
4093 }
4094 if (RewriteSC) {
4095 // Must insert any 'const/volatile/static here. Since it has been
4096 // removed as result of rewriting of block literals.
4097 std::string SC;
4098 if (GlobalVarDecl->getStorageClass() == SC_Static)
4099 SC = "static ";
4100 if (GlobalVarDecl->getType().isConstQualified())
4101 SC += "const ";
4102 if (GlobalVarDecl->getType().isVolatileQualified())
4103 SC += "volatile ";
4104 if (GlobalVarDecl->getType().isRestrictQualified())
4105 SC += "restrict ";
4106 InsertText(FunLocStart, SC);
4107 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004108 if (GlobalConstructionExp) {
4109 // extra fancy dance for global literal expression.
4110
4111 // Always the latest block expression on the block stack.
4112 std::string Tag = "__";
4113 Tag += FunName;
4114 Tag += "_block_impl_";
4115 Tag += utostr(Blocks.size()-1);
4116 std::string globalBuf = "static ";
4117 globalBuf += Tag; globalBuf += " ";
4118 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004119
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004120 llvm::raw_string_ostream constructorExprBuf(SStr);
4121 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
4122 PrintingPolicy(LangOpts));
4123 globalBuf += constructorExprBuf.str();
4124 globalBuf += ";\n";
4125 InsertText(FunLocStart, globalBuf);
4126 GlobalConstructionExp = 0;
4127 }
4128
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004129 Blocks.clear();
4130 InnerDeclRefsCount.clear();
4131 InnerDeclRefs.clear();
4132 RewrittenBlockExprs.clear();
4133}
4134
4135void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004136 SourceLocation FunLocStart = getFunctionSourceLocation(*this, FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004137 StringRef FuncName = FD->getName();
4138
4139 SynthesizeBlockLiterals(FunLocStart, FuncName);
4140}
4141
4142static void BuildUniqueMethodName(std::string &Name,
4143 ObjCMethodDecl *MD) {
4144 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4145 Name = IFace->getName();
4146 Name += "__" + MD->getSelector().getAsString();
4147 // Convert colons to underscores.
4148 std::string::size_type loc = 0;
4149 while ((loc = Name.find(":", loc)) != std::string::npos)
4150 Name.replace(loc, 1, "_");
4151}
4152
4153void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4154 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4155 //SourceLocation FunLocStart = MD->getLocStart();
4156 SourceLocation FunLocStart = MD->getLocStart();
4157 std::string FuncName;
4158 BuildUniqueMethodName(FuncName, MD);
4159 SynthesizeBlockLiterals(FunLocStart, FuncName);
4160}
4161
4162void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4163 for (Stmt::child_range CI = S->children(); CI; ++CI)
4164 if (*CI) {
4165 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4166 GetBlockDeclRefExprs(CBE->getBody());
4167 else
4168 GetBlockDeclRefExprs(*CI);
4169 }
4170 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004171 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4172 if (DRE->refersToEnclosingLocal()) {
4173 // FIXME: Handle enums.
4174 if (!isa<FunctionDecl>(DRE->getDecl()))
4175 BlockDeclRefs.push_back(DRE);
4176 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4177 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004178 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004179 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004180
4181 return;
4182}
4183
4184void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004185 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004186 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4187 for (Stmt::child_range CI = S->children(); CI; ++CI)
4188 if (*CI) {
4189 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4190 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4191 GetInnerBlockDeclRefExprs(CBE->getBody(),
4192 InnerBlockDeclRefs,
4193 InnerContexts);
4194 }
4195 else
4196 GetInnerBlockDeclRefExprs(*CI,
4197 InnerBlockDeclRefs,
4198 InnerContexts);
4199
4200 }
4201 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004202 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4203 if (DRE->refersToEnclosingLocal()) {
4204 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4205 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4206 InnerBlockDeclRefs.push_back(DRE);
4207 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4208 if (Var->isFunctionOrMethodVarDecl())
4209 ImportedLocalExternalDecls.insert(Var);
4210 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004211 }
4212
4213 return;
4214}
4215
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004216/// convertObjCTypeToCStyleType - This routine converts such objc types
4217/// as qualified objects, and blocks to their closest c/c++ types that
4218/// it can. It returns true if input type was modified.
4219bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4220 QualType oldT = T;
4221 convertBlockPointerToFunctionPointer(T);
4222 if (T->isFunctionPointerType()) {
4223 QualType PointeeTy;
4224 if (const PointerType* PT = T->getAs<PointerType>()) {
4225 PointeeTy = PT->getPointeeType();
4226 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4227 T = convertFunctionTypeOfBlocks(FT);
4228 T = Context->getPointerType(T);
4229 }
4230 }
4231 }
4232
4233 convertToUnqualifiedObjCType(T);
4234 return T != oldT;
4235}
4236
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004237/// convertFunctionTypeOfBlocks - This routine converts a function type
4238/// whose result type may be a block pointer or whose argument type(s)
4239/// might be block pointers to an equivalent function type replacing
4240/// all block pointers to function pointers.
4241QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4242 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4243 // FTP will be null for closures that don't take arguments.
4244 // Generate a funky cast.
4245 SmallVector<QualType, 8> ArgTypes;
4246 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004247 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004248
4249 if (FTP) {
4250 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4251 E = FTP->arg_type_end(); I && (I != E); ++I) {
4252 QualType t = *I;
4253 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004254 if (convertObjCTypeToCStyleType(t))
4255 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004256 ArgTypes.push_back(t);
4257 }
4258 }
4259 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004260 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004261 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4262 else FuncType = QualType(FT, 0);
4263 return FuncType;
4264}
4265
4266Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4267 // Navigate to relevant type information.
4268 const BlockPointerType *CPT = 0;
4269
4270 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4271 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004272 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4273 CPT = MExpr->getType()->getAs<BlockPointerType>();
4274 }
4275 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4276 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4277 }
4278 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4279 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4280 else if (const ConditionalOperator *CEXPR =
4281 dyn_cast<ConditionalOperator>(BlockExp)) {
4282 Expr *LHSExp = CEXPR->getLHS();
4283 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4284 Expr *RHSExp = CEXPR->getRHS();
4285 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4286 Expr *CONDExp = CEXPR->getCond();
4287 ConditionalOperator *CondExpr =
4288 new (Context) ConditionalOperator(CONDExp,
4289 SourceLocation(), cast<Expr>(LHSStmt),
4290 SourceLocation(), cast<Expr>(RHSStmt),
4291 Exp->getType(), VK_RValue, OK_Ordinary);
4292 return CondExpr;
4293 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4294 CPT = IRE->getType()->getAs<BlockPointerType>();
4295 } else if (const PseudoObjectExpr *POE
4296 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4297 CPT = POE->getType()->castAs<BlockPointerType>();
4298 } else {
4299 assert(1 && "RewriteBlockClass: Bad type");
4300 }
4301 assert(CPT && "RewriteBlockClass: Bad type");
4302 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4303 assert(FT && "RewriteBlockClass: Bad type");
4304 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4305 // FTP will be null for closures that don't take arguments.
4306
4307 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4308 SourceLocation(), SourceLocation(),
4309 &Context->Idents.get("__block_impl"));
4310 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4311
4312 // Generate a funky cast.
4313 SmallVector<QualType, 8> ArgTypes;
4314
4315 // Push the block argument type.
4316 ArgTypes.push_back(PtrBlock);
4317 if (FTP) {
4318 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4319 E = FTP->arg_type_end(); I && (I != E); ++I) {
4320 QualType t = *I;
4321 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4322 if (!convertBlockPointerToFunctionPointer(t))
4323 convertToUnqualifiedObjCType(t);
4324 ArgTypes.push_back(t);
4325 }
4326 }
4327 // Now do the pointer to function cast.
4328 QualType PtrToFuncCastType
4329 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4330
4331 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4332
4333 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4334 CK_BitCast,
4335 const_cast<Expr*>(BlockExp));
4336 // Don't forget the parens to enforce the proper binding.
4337 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4338 BlkCast);
4339 //PE->dump();
4340
4341 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4342 SourceLocation(),
4343 &Context->Idents.get("FuncPtr"),
4344 Context->VoidPtrTy, 0,
4345 /*BitWidth=*/0, /*Mutable=*/true,
4346 /*HasInit=*/false);
4347 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4348 FD->getType(), VK_LValue,
4349 OK_Ordinary);
4350
4351
4352 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4353 CK_BitCast, ME);
4354 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4355
4356 SmallVector<Expr*, 8> BlkExprs;
4357 // Add the implicit argument.
4358 BlkExprs.push_back(BlkCast);
4359 // Add the user arguments.
4360 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4361 E = Exp->arg_end(); I != E; ++I) {
4362 BlkExprs.push_back(*I);
4363 }
4364 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4365 BlkExprs.size(),
4366 Exp->getType(), VK_RValue,
4367 SourceLocation());
4368 return CE;
4369}
4370
4371// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004372// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004373// For example:
4374//
4375// int main() {
4376// __block Foo *f;
4377// __block int i;
4378//
4379// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004380// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004381// i = 77;
4382// };
4383//}
John McCallf4b88a42012-03-10 09:33:50 +00004384Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004385 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4386 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004387 ValueDecl *VD = DeclRefExp->getDecl();
4388 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004389
4390 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4391 SourceLocation(),
4392 &Context->Idents.get("__forwarding"),
4393 Context->VoidPtrTy, 0,
4394 /*BitWidth=*/0, /*Mutable=*/true,
4395 /*HasInit=*/false);
4396 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4397 FD, SourceLocation(),
4398 FD->getType(), VK_LValue,
4399 OK_Ordinary);
4400
4401 StringRef Name = VD->getName();
4402 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4403 &Context->Idents.get(Name),
4404 Context->VoidPtrTy, 0,
4405 /*BitWidth=*/0, /*Mutable=*/true,
4406 /*HasInit=*/false);
4407 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4408 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4409
4410
4411
4412 // Need parens to enforce precedence.
4413 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4414 DeclRefExp->getExprLoc(),
4415 ME);
4416 ReplaceStmt(DeclRefExp, PE);
4417 return PE;
4418}
4419
4420// Rewrites the imported local variable V with external storage
4421// (static, extern, etc.) as *V
4422//
4423Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4424 ValueDecl *VD = DRE->getDecl();
4425 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4426 if (!ImportedLocalExternalDecls.count(Var))
4427 return DRE;
4428 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4429 VK_LValue, OK_Ordinary,
4430 DRE->getLocation());
4431 // Need parens to enforce precedence.
4432 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4433 Exp);
4434 ReplaceStmt(DRE, PE);
4435 return PE;
4436}
4437
4438void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4439 SourceLocation LocStart = CE->getLParenLoc();
4440 SourceLocation LocEnd = CE->getRParenLoc();
4441
4442 // Need to avoid trying to rewrite synthesized casts.
4443 if (LocStart.isInvalid())
4444 return;
4445 // Need to avoid trying to rewrite casts contained in macros.
4446 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4447 return;
4448
4449 const char *startBuf = SM->getCharacterData(LocStart);
4450 const char *endBuf = SM->getCharacterData(LocEnd);
4451 QualType QT = CE->getType();
4452 const Type* TypePtr = QT->getAs<Type>();
4453 if (isa<TypeOfExprType>(TypePtr)) {
4454 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4455 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4456 std::string TypeAsString = "(";
4457 RewriteBlockPointerType(TypeAsString, QT);
4458 TypeAsString += ")";
4459 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4460 return;
4461 }
4462 // advance the location to startArgList.
4463 const char *argPtr = startBuf;
4464
4465 while (*argPtr++ && (argPtr < endBuf)) {
4466 switch (*argPtr) {
4467 case '^':
4468 // Replace the '^' with '*'.
4469 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4470 ReplaceText(LocStart, 1, "*");
4471 break;
4472 }
4473 }
4474 return;
4475}
4476
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004477void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4478 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004479 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4480 CastKind != CK_AnyPointerToBlockPointerCast)
4481 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004482
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004483 QualType QT = IC->getType();
4484 (void)convertBlockPointerToFunctionPointer(QT);
4485 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4486 std::string Str = "(";
4487 Str += TypeString;
4488 Str += ")";
4489 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4490
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004491 return;
4492}
4493
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004494void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4495 SourceLocation DeclLoc = FD->getLocation();
4496 unsigned parenCount = 0;
4497
4498 // We have 1 or more arguments that have closure pointers.
4499 const char *startBuf = SM->getCharacterData(DeclLoc);
4500 const char *startArgList = strchr(startBuf, '(');
4501
4502 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4503
4504 parenCount++;
4505 // advance the location to startArgList.
4506 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4507 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4508
4509 const char *argPtr = startArgList;
4510
4511 while (*argPtr++ && parenCount) {
4512 switch (*argPtr) {
4513 case '^':
4514 // Replace the '^' with '*'.
4515 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4516 ReplaceText(DeclLoc, 1, "*");
4517 break;
4518 case '(':
4519 parenCount++;
4520 break;
4521 case ')':
4522 parenCount--;
4523 break;
4524 }
4525 }
4526 return;
4527}
4528
4529bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4530 const FunctionProtoType *FTP;
4531 const PointerType *PT = QT->getAs<PointerType>();
4532 if (PT) {
4533 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4534 } else {
4535 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4536 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4537 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4538 }
4539 if (FTP) {
4540 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4541 E = FTP->arg_type_end(); I != E; ++I)
4542 if (isTopLevelBlockPointerType(*I))
4543 return true;
4544 }
4545 return false;
4546}
4547
4548bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4549 const FunctionProtoType *FTP;
4550 const PointerType *PT = QT->getAs<PointerType>();
4551 if (PT) {
4552 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4553 } else {
4554 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4555 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4556 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4557 }
4558 if (FTP) {
4559 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4560 E = FTP->arg_type_end(); I != E; ++I) {
4561 if ((*I)->isObjCQualifiedIdType())
4562 return true;
4563 if ((*I)->isObjCObjectPointerType() &&
4564 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4565 return true;
4566 }
4567
4568 }
4569 return false;
4570}
4571
4572void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4573 const char *&RParen) {
4574 const char *argPtr = strchr(Name, '(');
4575 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4576
4577 LParen = argPtr; // output the start.
4578 argPtr++; // skip past the left paren.
4579 unsigned parenCount = 1;
4580
4581 while (*argPtr && parenCount) {
4582 switch (*argPtr) {
4583 case '(': parenCount++; break;
4584 case ')': parenCount--; break;
4585 default: break;
4586 }
4587 if (parenCount) argPtr++;
4588 }
4589 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4590 RParen = argPtr; // output the end
4591}
4592
4593void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4594 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4595 RewriteBlockPointerFunctionArgs(FD);
4596 return;
4597 }
4598 // Handle Variables and Typedefs.
4599 SourceLocation DeclLoc = ND->getLocation();
4600 QualType DeclT;
4601 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4602 DeclT = VD->getType();
4603 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4604 DeclT = TDD->getUnderlyingType();
4605 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4606 DeclT = FD->getType();
4607 else
4608 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4609
4610 const char *startBuf = SM->getCharacterData(DeclLoc);
4611 const char *endBuf = startBuf;
4612 // scan backward (from the decl location) for the end of the previous decl.
4613 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4614 startBuf--;
4615 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4616 std::string buf;
4617 unsigned OrigLength=0;
4618 // *startBuf != '^' if we are dealing with a pointer to function that
4619 // may take block argument types (which will be handled below).
4620 if (*startBuf == '^') {
4621 // Replace the '^' with '*', computing a negative offset.
4622 buf = '*';
4623 startBuf++;
4624 OrigLength++;
4625 }
4626 while (*startBuf != ')') {
4627 buf += *startBuf;
4628 startBuf++;
4629 OrigLength++;
4630 }
4631 buf += ')';
4632 OrigLength++;
4633
4634 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4635 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4636 // Replace the '^' with '*' for arguments.
4637 // Replace id<P> with id/*<>*/
4638 DeclLoc = ND->getLocation();
4639 startBuf = SM->getCharacterData(DeclLoc);
4640 const char *argListBegin, *argListEnd;
4641 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4642 while (argListBegin < argListEnd) {
4643 if (*argListBegin == '^')
4644 buf += '*';
4645 else if (*argListBegin == '<') {
4646 buf += "/*";
4647 buf += *argListBegin++;
4648 OrigLength++;;
4649 while (*argListBegin != '>') {
4650 buf += *argListBegin++;
4651 OrigLength++;
4652 }
4653 buf += *argListBegin;
4654 buf += "*/";
4655 }
4656 else
4657 buf += *argListBegin;
4658 argListBegin++;
4659 OrigLength++;
4660 }
4661 buf += ')';
4662 OrigLength++;
4663 }
4664 ReplaceText(Start, OrigLength, buf);
4665
4666 return;
4667}
4668
4669
4670/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4671/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4672/// struct Block_byref_id_object *src) {
4673/// _Block_object_assign (&_dest->object, _src->object,
4674/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4675/// [|BLOCK_FIELD_IS_WEAK]) // object
4676/// _Block_object_assign(&_dest->object, _src->object,
4677/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4678/// [|BLOCK_FIELD_IS_WEAK]) // block
4679/// }
4680/// And:
4681/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4682/// _Block_object_dispose(_src->object,
4683/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4684/// [|BLOCK_FIELD_IS_WEAK]) // object
4685/// _Block_object_dispose(_src->object,
4686/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4687/// [|BLOCK_FIELD_IS_WEAK]) // block
4688/// }
4689
4690std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4691 int flag) {
4692 std::string S;
4693 if (CopyDestroyCache.count(flag))
4694 return S;
4695 CopyDestroyCache.insert(flag);
4696 S = "static void __Block_byref_id_object_copy_";
4697 S += utostr(flag);
4698 S += "(void *dst, void *src) {\n";
4699
4700 // offset into the object pointer is computed as:
4701 // void * + void* + int + int + void* + void *
4702 unsigned IntSize =
4703 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4704 unsigned VoidPtrSize =
4705 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4706
4707 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4708 S += " _Block_object_assign((char*)dst + ";
4709 S += utostr(offset);
4710 S += ", *(void * *) ((char*)src + ";
4711 S += utostr(offset);
4712 S += "), ";
4713 S += utostr(flag);
4714 S += ");\n}\n";
4715
4716 S += "static void __Block_byref_id_object_dispose_";
4717 S += utostr(flag);
4718 S += "(void *src) {\n";
4719 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4720 S += utostr(offset);
4721 S += "), ";
4722 S += utostr(flag);
4723 S += ");\n}\n";
4724 return S;
4725}
4726
4727/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4728/// the declaration into:
4729/// struct __Block_byref_ND {
4730/// void *__isa; // NULL for everything except __weak pointers
4731/// struct __Block_byref_ND *__forwarding;
4732/// int32_t __flags;
4733/// int32_t __size;
4734/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4735/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4736/// typex ND;
4737/// };
4738///
4739/// It then replaces declaration of ND variable with:
4740/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4741/// __size=sizeof(struct __Block_byref_ND),
4742/// ND=initializer-if-any};
4743///
4744///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004745void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
4746 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004747 int flag = 0;
4748 int isa = 0;
4749 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4750 if (DeclLoc.isInvalid())
4751 // If type location is missing, it is because of missing type (a warning).
4752 // Use variable's location which is good for this case.
4753 DeclLoc = ND->getLocation();
4754 const char *startBuf = SM->getCharacterData(DeclLoc);
4755 SourceLocation X = ND->getLocEnd();
4756 X = SM->getExpansionLoc(X);
4757 const char *endBuf = SM->getCharacterData(X);
4758 std::string Name(ND->getNameAsString());
4759 std::string ByrefType;
4760 RewriteByRefString(ByrefType, Name, ND, true);
4761 ByrefType += " {\n";
4762 ByrefType += " void *__isa;\n";
4763 RewriteByRefString(ByrefType, Name, ND);
4764 ByrefType += " *__forwarding;\n";
4765 ByrefType += " int __flags;\n";
4766 ByrefType += " int __size;\n";
4767 // Add void *__Block_byref_id_object_copy;
4768 // void *__Block_byref_id_object_dispose; if needed.
4769 QualType Ty = ND->getType();
4770 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4771 if (HasCopyAndDispose) {
4772 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4773 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4774 }
4775
4776 QualType T = Ty;
4777 (void)convertBlockPointerToFunctionPointer(T);
4778 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4779
4780 ByrefType += " " + Name + ";\n";
4781 ByrefType += "};\n";
4782 // Insert this type in global scope. It is needed by helper function.
4783 SourceLocation FunLocStart;
4784 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00004785 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004786 else {
4787 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4788 FunLocStart = CurMethodDef->getLocStart();
4789 }
4790 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004791
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004792 if (Ty.isObjCGCWeak()) {
4793 flag |= BLOCK_FIELD_IS_WEAK;
4794 isa = 1;
4795 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004796 if (HasCopyAndDispose) {
4797 flag = BLOCK_BYREF_CALLER;
4798 QualType Ty = ND->getType();
4799 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4800 if (Ty->isBlockPointerType())
4801 flag |= BLOCK_FIELD_IS_BLOCK;
4802 else
4803 flag |= BLOCK_FIELD_IS_OBJECT;
4804 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4805 if (!HF.empty())
4806 InsertText(FunLocStart, HF);
4807 }
4808
4809 // struct __Block_byref_ND ND =
4810 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4811 // initializer-if-any};
4812 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00004813 // FIXME. rewriter does not support __block c++ objects which
4814 // require construction.
4815 if (hasInit && dyn_cast<CXXConstructExpr>(ND->getInit()))
4816 hasInit = false;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004817 unsigned flags = 0;
4818 if (HasCopyAndDispose)
4819 flags |= BLOCK_HAS_COPY_DISPOSE;
4820 Name = ND->getNameAsString();
4821 ByrefType.clear();
4822 RewriteByRefString(ByrefType, Name, ND);
4823 std::string ForwardingCastType("(");
4824 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004825 ByrefType += " " + Name + " = {(void*)";
4826 ByrefType += utostr(isa);
4827 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4828 ByrefType += utostr(flags);
4829 ByrefType += ", ";
4830 ByrefType += "sizeof(";
4831 RewriteByRefString(ByrefType, Name, ND);
4832 ByrefType += ")";
4833 if (HasCopyAndDispose) {
4834 ByrefType += ", __Block_byref_id_object_copy_";
4835 ByrefType += utostr(flag);
4836 ByrefType += ", __Block_byref_id_object_dispose_";
4837 ByrefType += utostr(flag);
4838 }
4839
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004840 if (!firstDecl) {
4841 // In multiple __block declarations, and for all but 1st declaration,
4842 // find location of the separating comma. This would be start location
4843 // where new text is to be inserted.
4844 DeclLoc = ND->getLocation();
4845 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
4846 const char *commaBuf = startDeclBuf;
4847 while (*commaBuf != ',')
4848 commaBuf--;
4849 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
4850 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
4851 startBuf = commaBuf;
4852 }
4853
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004854 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004855 ByrefType += "};\n";
4856 unsigned nameSize = Name.size();
4857 // for block or function pointer declaration. Name is aleady
4858 // part of the declaration.
4859 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4860 nameSize = 1;
4861 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4862 }
4863 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00004864 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004865 SourceLocation startLoc;
4866 Expr *E = ND->getInit();
4867 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4868 startLoc = ECE->getLParenLoc();
4869 else
4870 startLoc = E->getLocStart();
4871 startLoc = SM->getExpansionLoc(startLoc);
4872 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004873 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004874
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00004875 const char separator = lastDecl ? ';' : ',';
4876 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4877 const char *separatorBuf = strchr(startInitializerBuf, separator);
4878 assert((*separatorBuf == separator) &&
4879 "RewriteByRefVar: can't find ';' or ','");
4880 SourceLocation separatorLoc =
4881 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
4882
4883 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004884 }
4885 return;
4886}
4887
4888void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4889 // Add initializers for any closure decl refs.
4890 GetBlockDeclRefExprs(Exp->getBody());
4891 if (BlockDeclRefs.size()) {
4892 // Unique all "by copy" declarations.
4893 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004894 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004895 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4896 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4897 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4898 }
4899 }
4900 // Unique all "by ref" declarations.
4901 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004902 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004903 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4904 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4905 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4906 }
4907 }
4908 // Find any imported blocks...they will need special attention.
4909 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004910 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004911 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4912 BlockDeclRefs[i]->getType()->isBlockPointerType())
4913 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4914 }
4915}
4916
4917FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4918 IdentifierInfo *ID = &Context->Idents.get(name);
4919 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4920 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4921 SourceLocation(), ID, FType, 0, SC_Extern,
4922 SC_None, false, false);
4923}
4924
4925Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004926 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004927
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004928 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004929
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004930 Blocks.push_back(Exp);
4931
4932 CollectBlockDeclRefInfo(Exp);
4933
4934 // Add inner imported variables now used in current block.
4935 int countOfInnerDecls = 0;
4936 if (!InnerBlockDeclRefs.empty()) {
4937 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004938 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004939 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004940 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004941 // We need to save the copied-in variables in nested
4942 // blocks because it is needed at the end for some of the API generations.
4943 // See SynthesizeBlockLiterals routine.
4944 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4945 BlockDeclRefs.push_back(Exp);
4946 BlockByCopyDeclsPtrSet.insert(VD);
4947 BlockByCopyDecls.push_back(VD);
4948 }
John McCallf4b88a42012-03-10 09:33:50 +00004949 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004950 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4951 BlockDeclRefs.push_back(Exp);
4952 BlockByRefDeclsPtrSet.insert(VD);
4953 BlockByRefDecls.push_back(VD);
4954 }
4955 }
4956 // Find any imported blocks...they will need special attention.
4957 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004958 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004959 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4960 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4961 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4962 }
4963 InnerDeclRefsCount.push_back(countOfInnerDecls);
4964
4965 std::string FuncName;
4966
4967 if (CurFunctionDef)
4968 FuncName = CurFunctionDef->getNameAsString();
4969 else if (CurMethodDef)
4970 BuildUniqueMethodName(FuncName, CurMethodDef);
4971 else if (GlobalVarDecl)
4972 FuncName = std::string(GlobalVarDecl->getNameAsString());
4973
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004974 bool GlobalBlockExpr =
4975 block->getDeclContext()->getRedeclContext()->isFileContext();
4976
4977 if (GlobalBlockExpr && !GlobalVarDecl) {
4978 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4979 GlobalBlockExpr = false;
4980 }
4981
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004982 std::string BlockNumber = utostr(Blocks.size()-1);
4983
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004984 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4985
4986 // Get a pointer to the function type so we can cast appropriately.
4987 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4988 QualType FType = Context->getPointerType(BFT);
4989
4990 FunctionDecl *FD;
4991 Expr *NewRep;
4992
4993 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004994 std::string Tag;
4995
4996 if (GlobalBlockExpr)
4997 Tag = "__global_";
4998 else
4999 Tag = "__";
5000 Tag += FuncName + "_block_impl_" + BlockNumber;
5001
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005002 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005003 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005004 SourceLocation());
5005
5006 SmallVector<Expr*, 4> InitExprs;
5007
5008 // Initialize the block function.
5009 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005010 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5011 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005012 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5013 CK_BitCast, Arg);
5014 InitExprs.push_back(castExpr);
5015
5016 // Initialize the block descriptor.
5017 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5018
5019 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5020 SourceLocation(), SourceLocation(),
5021 &Context->Idents.get(DescData.c_str()),
5022 Context->VoidPtrTy, 0,
5023 SC_Static, SC_None);
5024 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005025 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005026 Context->VoidPtrTy,
5027 VK_LValue,
5028 SourceLocation()),
5029 UO_AddrOf,
5030 Context->getPointerType(Context->VoidPtrTy),
5031 VK_RValue, OK_Ordinary,
5032 SourceLocation());
5033 InitExprs.push_back(DescRefExpr);
5034
5035 // Add initializers for any closure decl refs.
5036 if (BlockDeclRefs.size()) {
5037 Expr *Exp;
5038 // Output all "by copy" declarations.
5039 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5040 E = BlockByCopyDecls.end(); I != E; ++I) {
5041 if (isObjCType((*I)->getType())) {
5042 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5043 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005044 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5045 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005046 if (HasLocalVariableExternalStorage(*I)) {
5047 QualType QT = (*I)->getType();
5048 QT = Context->getPointerType(QT);
5049 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5050 OK_Ordinary, SourceLocation());
5051 }
5052 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5053 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005054 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5055 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005056 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5057 CK_BitCast, Arg);
5058 } else {
5059 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005060 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5061 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005062 if (HasLocalVariableExternalStorage(*I)) {
5063 QualType QT = (*I)->getType();
5064 QT = Context->getPointerType(QT);
5065 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5066 OK_Ordinary, SourceLocation());
5067 }
5068
5069 }
5070 InitExprs.push_back(Exp);
5071 }
5072 // Output all "by ref" declarations.
5073 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5074 E = BlockByRefDecls.end(); I != E; ++I) {
5075 ValueDecl *ND = (*I);
5076 std::string Name(ND->getNameAsString());
5077 std::string RecName;
5078 RewriteByRefString(RecName, Name, ND, true);
5079 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5080 + sizeof("struct"));
5081 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5082 SourceLocation(), SourceLocation(),
5083 II);
5084 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5085 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5086
5087 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005088 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005089 SourceLocation());
5090 bool isNestedCapturedVar = false;
5091 if (block)
5092 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5093 ce = block->capture_end(); ci != ce; ++ci) {
5094 const VarDecl *variable = ci->getVariable();
5095 if (variable == ND && ci->isNested()) {
5096 assert (ci->isByRef() &&
5097 "SynthBlockInitExpr - captured block variable is not byref");
5098 isNestedCapturedVar = true;
5099 break;
5100 }
5101 }
5102 // captured nested byref variable has its address passed. Do not take
5103 // its address again.
5104 if (!isNestedCapturedVar)
5105 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5106 Context->getPointerType(Exp->getType()),
5107 VK_RValue, OK_Ordinary, SourceLocation());
5108 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5109 InitExprs.push_back(Exp);
5110 }
5111 }
5112 if (ImportedBlockDecls.size()) {
5113 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5114 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5115 unsigned IntSize =
5116 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5117 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5118 Context->IntTy, SourceLocation());
5119 InitExprs.push_back(FlagExp);
5120 }
5121 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
5122 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005123
5124 if (GlobalBlockExpr) {
5125 assert (GlobalConstructionExp == 0 &&
5126 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5127 GlobalConstructionExp = NewRep;
5128 NewRep = DRE;
5129 }
5130
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005131 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5132 Context->getPointerType(NewRep->getType()),
5133 VK_RValue, OK_Ordinary, SourceLocation());
5134 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5135 NewRep);
5136 BlockDeclRefs.clear();
5137 BlockByRefDecls.clear();
5138 BlockByRefDeclsPtrSet.clear();
5139 BlockByCopyDecls.clear();
5140 BlockByCopyDeclsPtrSet.clear();
5141 ImportedBlockDecls.clear();
5142 return NewRep;
5143}
5144
5145bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5146 if (const ObjCForCollectionStmt * CS =
5147 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5148 return CS->getElement() == DS;
5149 return false;
5150}
5151
5152//===----------------------------------------------------------------------===//
5153// Function Body / Expression rewriting
5154//===----------------------------------------------------------------------===//
5155
5156Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5157 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5158 isa<DoStmt>(S) || isa<ForStmt>(S))
5159 Stmts.push_back(S);
5160 else if (isa<ObjCForCollectionStmt>(S)) {
5161 Stmts.push_back(S);
5162 ObjCBcLabelNo.push_back(++BcLabelCount);
5163 }
5164
5165 // Pseudo-object operations and ivar references need special
5166 // treatment because we're going to recursively rewrite them.
5167 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5168 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5169 return RewritePropertyOrImplicitSetter(PseudoOp);
5170 } else {
5171 return RewritePropertyOrImplicitGetter(PseudoOp);
5172 }
5173 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5174 return RewriteObjCIvarRefExpr(IvarRefExpr);
5175 }
5176
5177 SourceRange OrigStmtRange = S->getSourceRange();
5178
5179 // Perform a bottom up rewrite of all children.
5180 for (Stmt::child_range CI = S->children(); CI; ++CI)
5181 if (*CI) {
5182 Stmt *childStmt = (*CI);
5183 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5184 if (newStmt) {
5185 *CI = newStmt;
5186 }
5187 }
5188
5189 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005190 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005191 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5192 InnerContexts.insert(BE->getBlockDecl());
5193 ImportedLocalExternalDecls.clear();
5194 GetInnerBlockDeclRefExprs(BE->getBody(),
5195 InnerBlockDeclRefs, InnerContexts);
5196 // Rewrite the block body in place.
5197 Stmt *SaveCurrentBody = CurrentBody;
5198 CurrentBody = BE->getBody();
5199 PropParentMap = 0;
5200 // block literal on rhs of a property-dot-sytax assignment
5201 // must be replaced by its synthesize ast so getRewrittenText
5202 // works as expected. In this case, what actually ends up on RHS
5203 // is the blockTranscribed which is the helper function for the
5204 // block literal; as in: self.c = ^() {[ace ARR];};
5205 bool saveDisableReplaceStmt = DisableReplaceStmt;
5206 DisableReplaceStmt = false;
5207 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5208 DisableReplaceStmt = saveDisableReplaceStmt;
5209 CurrentBody = SaveCurrentBody;
5210 PropParentMap = 0;
5211 ImportedLocalExternalDecls.clear();
5212 // Now we snarf the rewritten text and stash it away for later use.
5213 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5214 RewrittenBlockExprs[BE] = Str;
5215
5216 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5217
5218 //blockTranscribed->dump();
5219 ReplaceStmt(S, blockTranscribed);
5220 return blockTranscribed;
5221 }
5222 // Handle specific things.
5223 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5224 return RewriteAtEncode(AtEncode);
5225
5226 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5227 return RewriteAtSelector(AtSelector);
5228
5229 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5230 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005231
5232 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5233 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005234
Patrick Beardeb382ec2012-04-19 00:25:12 +00005235 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5236 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005237
5238 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5239 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005240
5241 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5242 dyn_cast<ObjCDictionaryLiteral>(S))
5243 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005244
5245 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5246#if 0
5247 // Before we rewrite it, put the original message expression in a comment.
5248 SourceLocation startLoc = MessExpr->getLocStart();
5249 SourceLocation endLoc = MessExpr->getLocEnd();
5250
5251 const char *startBuf = SM->getCharacterData(startLoc);
5252 const char *endBuf = SM->getCharacterData(endLoc);
5253
5254 std::string messString;
5255 messString += "// ";
5256 messString.append(startBuf, endBuf-startBuf+1);
5257 messString += "\n";
5258
5259 // FIXME: Missing definition of
5260 // InsertText(clang::SourceLocation, char const*, unsigned int).
5261 // InsertText(startLoc, messString.c_str(), messString.size());
5262 // Tried this, but it didn't work either...
5263 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5264#endif
5265 return RewriteMessageExpr(MessExpr);
5266 }
5267
5268 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5269 return RewriteObjCTryStmt(StmtTry);
5270
5271 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5272 return RewriteObjCSynchronizedStmt(StmtTry);
5273
5274 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5275 return RewriteObjCThrowStmt(StmtThrow);
5276
5277 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5278 return RewriteObjCProtocolExpr(ProtocolExp);
5279
5280 if (ObjCForCollectionStmt *StmtForCollection =
5281 dyn_cast<ObjCForCollectionStmt>(S))
5282 return RewriteObjCForCollectionStmt(StmtForCollection,
5283 OrigStmtRange.getEnd());
5284 if (BreakStmt *StmtBreakStmt =
5285 dyn_cast<BreakStmt>(S))
5286 return RewriteBreakStmt(StmtBreakStmt);
5287 if (ContinueStmt *StmtContinueStmt =
5288 dyn_cast<ContinueStmt>(S))
5289 return RewriteContinueStmt(StmtContinueStmt);
5290
5291 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5292 // and cast exprs.
5293 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5294 // FIXME: What we're doing here is modifying the type-specifier that
5295 // precedes the first Decl. In the future the DeclGroup should have
5296 // a separate type-specifier that we can rewrite.
5297 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5298 // the context of an ObjCForCollectionStmt. For example:
5299 // NSArray *someArray;
5300 // for (id <FooProtocol> index in someArray) ;
5301 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5302 // and it depends on the original text locations/positions.
5303 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5304 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5305
5306 // Blocks rewrite rules.
5307 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5308 DI != DE; ++DI) {
5309 Decl *SD = *DI;
5310 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5311 if (isTopLevelBlockPointerType(ND->getType()))
5312 RewriteBlockPointerDecl(ND);
5313 else if (ND->getType()->isFunctionPointerType())
5314 CheckFunctionPointerDecl(ND->getType(), ND);
5315 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5316 if (VD->hasAttr<BlocksAttr>()) {
5317 static unsigned uniqueByrefDeclCount = 0;
5318 assert(!BlockByRefDeclNo.count(ND) &&
5319 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5320 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005321 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005322 }
5323 else
5324 RewriteTypeOfDecl(VD);
5325 }
5326 }
5327 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5328 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5329 RewriteBlockPointerDecl(TD);
5330 else if (TD->getUnderlyingType()->isFunctionPointerType())
5331 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5332 }
5333 }
5334 }
5335
5336 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5337 RewriteObjCQualifiedInterfaceTypes(CE);
5338
5339 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5340 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5341 assert(!Stmts.empty() && "Statement stack is empty");
5342 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5343 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5344 && "Statement stack mismatch");
5345 Stmts.pop_back();
5346 }
5347 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005348 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5349 ValueDecl *VD = DRE->getDecl();
5350 if (VD->hasAttr<BlocksAttr>())
5351 return RewriteBlockDeclRefExpr(DRE);
5352 if (HasLocalVariableExternalStorage(VD))
5353 return RewriteLocalVariableExternalStorage(DRE);
5354 }
5355
5356 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5357 if (CE->getCallee()->getType()->isBlockPointerType()) {
5358 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5359 ReplaceStmt(S, BlockCall);
5360 return BlockCall;
5361 }
5362 }
5363 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5364 RewriteCastExpr(CE);
5365 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005366 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5367 RewriteImplicitCastObjCExpr(ICE);
5368 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005369#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005370
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005371 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5372 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5373 ICE->getSubExpr(),
5374 SourceLocation());
5375 // Get the new text.
5376 std::string SStr;
5377 llvm::raw_string_ostream Buf(SStr);
5378 Replacement->printPretty(Buf, *Context);
5379 const std::string &Str = Buf.str();
5380
5381 printf("CAST = %s\n", &Str[0]);
5382 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5383 delete S;
5384 return Replacement;
5385 }
5386#endif
5387 // Return this stmt unmodified.
5388 return S;
5389}
5390
5391void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5392 for (RecordDecl::field_iterator i = RD->field_begin(),
5393 e = RD->field_end(); i != e; ++i) {
5394 FieldDecl *FD = *i;
5395 if (isTopLevelBlockPointerType(FD->getType()))
5396 RewriteBlockPointerDecl(FD);
5397 if (FD->getType()->isObjCQualifiedIdType() ||
5398 FD->getType()->isObjCQualifiedInterfaceType())
5399 RewriteObjCQualifiedInterfaceTypes(FD);
5400 }
5401}
5402
5403/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5404/// main file of the input.
5405void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5406 switch (D->getKind()) {
5407 case Decl::Function: {
5408 FunctionDecl *FD = cast<FunctionDecl>(D);
5409 if (FD->isOverloadedOperator())
5410 return;
5411
5412 // Since function prototypes don't have ParmDecl's, we check the function
5413 // prototype. This enables us to rewrite function declarations and
5414 // definitions using the same code.
5415 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5416
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005417 if (!FD->isThisDeclarationADefinition())
5418 break;
5419
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005420 // FIXME: If this should support Obj-C++, support CXXTryStmt
5421 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5422 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005423 CurrentBody = Body;
5424 Body =
5425 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5426 FD->setBody(Body);
5427 CurrentBody = 0;
5428 if (PropParentMap) {
5429 delete PropParentMap;
5430 PropParentMap = 0;
5431 }
5432 // This synthesizes and inserts the block "impl" struct, invoke function,
5433 // and any copy/dispose helper functions.
5434 InsertBlockLiteralsWithinFunction(FD);
5435 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005436 }
5437 break;
5438 }
5439 case Decl::ObjCMethod: {
5440 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5441 if (CompoundStmt *Body = MD->getCompoundBody()) {
5442 CurMethodDef = MD;
5443 CurrentBody = Body;
5444 Body =
5445 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5446 MD->setBody(Body);
5447 CurrentBody = 0;
5448 if (PropParentMap) {
5449 delete PropParentMap;
5450 PropParentMap = 0;
5451 }
5452 InsertBlockLiteralsWithinMethod(MD);
5453 CurMethodDef = 0;
5454 }
5455 break;
5456 }
5457 case Decl::ObjCImplementation: {
5458 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5459 ClassImplementation.push_back(CI);
5460 break;
5461 }
5462 case Decl::ObjCCategoryImpl: {
5463 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5464 CategoryImplementation.push_back(CI);
5465 break;
5466 }
5467 case Decl::Var: {
5468 VarDecl *VD = cast<VarDecl>(D);
5469 RewriteObjCQualifiedInterfaceTypes(VD);
5470 if (isTopLevelBlockPointerType(VD->getType()))
5471 RewriteBlockPointerDecl(VD);
5472 else if (VD->getType()->isFunctionPointerType()) {
5473 CheckFunctionPointerDecl(VD->getType(), VD);
5474 if (VD->getInit()) {
5475 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5476 RewriteCastExpr(CE);
5477 }
5478 }
5479 } else if (VD->getType()->isRecordType()) {
5480 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5481 if (RD->isCompleteDefinition())
5482 RewriteRecordBody(RD);
5483 }
5484 if (VD->getInit()) {
5485 GlobalVarDecl = VD;
5486 CurrentBody = VD->getInit();
5487 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5488 CurrentBody = 0;
5489 if (PropParentMap) {
5490 delete PropParentMap;
5491 PropParentMap = 0;
5492 }
5493 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5494 GlobalVarDecl = 0;
5495
5496 // This is needed for blocks.
5497 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5498 RewriteCastExpr(CE);
5499 }
5500 }
5501 break;
5502 }
5503 case Decl::TypeAlias:
5504 case Decl::Typedef: {
5505 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5506 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5507 RewriteBlockPointerDecl(TD);
5508 else if (TD->getUnderlyingType()->isFunctionPointerType())
5509 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5510 }
5511 break;
5512 }
5513 case Decl::CXXRecord:
5514 case Decl::Record: {
5515 RecordDecl *RD = cast<RecordDecl>(D);
5516 if (RD->isCompleteDefinition())
5517 RewriteRecordBody(RD);
5518 break;
5519 }
5520 default:
5521 break;
5522 }
5523 // Nothing yet.
5524}
5525
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005526/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5527/// protocol reference symbols in the for of:
5528/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5529static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5530 ObjCProtocolDecl *PDecl,
5531 std::string &Result) {
5532 // Also output .objc_protorefs$B section and its meta-data.
5533 if (Context->getLangOpts().MicrosoftExt)
5534 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5535 Result += "struct _protocol_t *";
5536 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5537 Result += PDecl->getNameAsString();
5538 Result += " = &";
5539 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5540 Result += ";\n";
5541}
5542
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005543void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5544 if (Diags.hasErrorOccurred())
5545 return;
5546
5547 RewriteInclude();
5548
5549 // Here's a great place to add any extra declarations that may be needed.
5550 // Write out meta data for each @protocol(<expr>).
5551 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005552 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005553 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005554 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5555 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005556
5557 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005558 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5559 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5560 // Write struct declaration for the class matching its ivar declarations.
5561 // Note that for modern abi, this is postponed until the end of TU
5562 // because class extensions and the implementation might declare their own
5563 // private ivars.
5564 RewriteInterfaceDecl(CDecl);
5565 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005566
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005567 if (ClassImplementation.size() || CategoryImplementation.size())
5568 RewriteImplementations();
5569
5570 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5571 // we are done.
5572 if (const RewriteBuffer *RewriteBuf =
5573 Rewrite.getRewriteBufferFor(MainFileID)) {
5574 //printf("Changed:\n");
5575 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5576 } else {
5577 llvm::errs() << "No changes\n";
5578 }
5579
5580 if (ClassImplementation.size() || CategoryImplementation.size() ||
5581 ProtocolExprDecls.size()) {
5582 // Rewrite Objective-c meta data*
5583 std::string ResultStr;
5584 RewriteMetaDataIntoBuffer(ResultStr);
5585 // Emit metadata.
5586 *OutFile << ResultStr;
5587 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005588 // Emit ImageInfo;
5589 {
5590 std::string ResultStr;
5591 WriteImageInfo(ResultStr);
5592 *OutFile << ResultStr;
5593 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005594 OutFile->flush();
5595}
5596
5597void RewriteModernObjC::Initialize(ASTContext &context) {
5598 InitializeCommon(context);
5599
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005600 Preamble += "#ifndef __OBJC2__\n";
5601 Preamble += "#define __OBJC2__\n";
5602 Preamble += "#endif\n";
5603
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005604 // declaring objc_selector outside the parameter list removes a silly
5605 // scope related warning...
5606 if (IsHeader)
5607 Preamble = "#pragma once\n";
5608 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00005609 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5610 Preamble += "\n\tstruct objc_object *superClass; ";
5611 // Add a constructor for creating temporary objects.
5612 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5613 Preamble += ": object(o), superClass(s) {} ";
5614 Preamble += "\n};\n";
5615
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005616 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005617 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005618 // These are currently generated.
5619 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005620 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005621 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005622 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5623 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005624 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005625 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005626 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005627 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5628 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005629 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005630
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005631 // These need be generated for performance. Currently they are not,
5632 // using API calls instead.
5633 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5634 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5635 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5636
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005637 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005638 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5639 Preamble += "typedef struct objc_object Protocol;\n";
5640 Preamble += "#define _REWRITER_typedef_Protocol\n";
5641 Preamble += "#endif\n";
5642 if (LangOpts.MicrosoftExt) {
5643 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5644 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005645 }
5646 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005647 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005648
5649 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5650 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5651 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5652 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5653 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5654
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005655 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5656 Preamble += "(const char *);\n";
5657 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5658 Preamble += "(struct objc_class *);\n";
5659 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5660 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005661 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005662 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005663 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5664 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005665 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5666 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5667 Preamble += "struct __objcFastEnumerationState {\n\t";
5668 Preamble += "unsigned long state;\n\t";
5669 Preamble += "void **itemsPtr;\n\t";
5670 Preamble += "unsigned long *mutationsPtr;\n\t";
5671 Preamble += "unsigned long extra[5];\n};\n";
5672 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5673 Preamble += "#define __FASTENUMERATIONSTATE\n";
5674 Preamble += "#endif\n";
5675 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5676 Preamble += "struct __NSConstantStringImpl {\n";
5677 Preamble += " int *isa;\n";
5678 Preamble += " int flags;\n";
5679 Preamble += " char *str;\n";
5680 Preamble += " long length;\n";
5681 Preamble += "};\n";
5682 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5683 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5684 Preamble += "#else\n";
5685 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5686 Preamble += "#endif\n";
5687 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5688 Preamble += "#endif\n";
5689 // Blocks preamble.
5690 Preamble += "#ifndef BLOCK_IMPL\n";
5691 Preamble += "#define BLOCK_IMPL\n";
5692 Preamble += "struct __block_impl {\n";
5693 Preamble += " void *isa;\n";
5694 Preamble += " int Flags;\n";
5695 Preamble += " int Reserved;\n";
5696 Preamble += " void *FuncPtr;\n";
5697 Preamble += "};\n";
5698 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5699 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5700 Preamble += "extern \"C\" __declspec(dllexport) "
5701 "void _Block_object_assign(void *, const void *, const int);\n";
5702 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5703 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5704 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5705 Preamble += "#else\n";
5706 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5707 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5708 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5709 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5710 Preamble += "#endif\n";
5711 Preamble += "#endif\n";
5712 if (LangOpts.MicrosoftExt) {
5713 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5714 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5715 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5716 Preamble += "#define __attribute__(X)\n";
5717 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005718 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005719 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00005720 Preamble += "#endif\n";
5721 Preamble += "#ifndef __block\n";
5722 Preamble += "#define __block\n";
5723 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005724 }
5725 else {
5726 Preamble += "#define __block\n";
5727 Preamble += "#define __weak\n";
5728 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005729
5730 // Declarations required for modern objective-c array and dictionary literals.
5731 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005732 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005733 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005734 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005735 Preamble += "\tva_list marker;\n";
5736 Preamble += "\tva_start(marker, count);\n";
5737 Preamble += "\tarr = new void *[count];\n";
5738 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5739 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5740 Preamble += "\tva_end( marker );\n";
5741 Preamble += " };\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005742 Preamble += " __NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005743 Preamble += "\tdelete[] arr;\n";
5744 Preamble += " }\n";
5745 Preamble += "};\n";
5746
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005747 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5748 // as this avoids warning in any 64bit/32bit compilation model.
5749 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5750}
5751
5752/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5753/// ivar offset.
5754void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5755 std::string &Result) {
5756 if (ivar->isBitField()) {
5757 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5758 // place all bitfields at offset 0.
5759 Result += "0";
5760 } else {
5761 Result += "__OFFSETOFIVAR__(struct ";
5762 Result += ivar->getContainingInterface()->getNameAsString();
5763 if (LangOpts.MicrosoftExt)
5764 Result += "_IMPL";
5765 Result += ", ";
5766 Result += ivar->getNameAsString();
5767 Result += ")";
5768 }
5769}
5770
5771/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5772/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005773/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005774/// char *attributes;
5775/// }
5776
5777/// struct _prop_list_t {
5778/// uint32_t entsize; // sizeof(struct _prop_t)
5779/// uint32_t count_of_properties;
5780/// struct _prop_t prop_list[count_of_properties];
5781/// }
5782
5783/// struct _protocol_t;
5784
5785/// struct _protocol_list_t {
5786/// long protocol_count; // Note, this is 32/64 bit
5787/// struct _protocol_t * protocol_list[protocol_count];
5788/// }
5789
5790/// struct _objc_method {
5791/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005792/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005793/// char *_imp;
5794/// }
5795
5796/// struct _method_list_t {
5797/// uint32_t entsize; // sizeof(struct _objc_method)
5798/// uint32_t method_count;
5799/// struct _objc_method method_list[method_count];
5800/// }
5801
5802/// struct _protocol_t {
5803/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005804/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005805/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005806/// const struct method_list_t *instance_methods;
5807/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005808/// const struct method_list_t *optionalInstanceMethods;
5809/// const struct method_list_t *optionalClassMethods;
5810/// const struct _prop_list_t * properties;
5811/// const uint32_t size; // sizeof(struct _protocol_t)
5812/// const uint32_t flags; // = 0
5813/// const char ** extendedMethodTypes;
5814/// }
5815
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005816/// struct _ivar_t {
5817/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005818/// const char *name;
5819/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005820/// uint32_t alignment;
5821/// uint32_t size;
5822/// }
5823
5824/// struct _ivar_list_t {
5825/// uint32 entsize; // sizeof(struct _ivar_t)
5826/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005827/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005828/// }
5829
5830/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005831/// uint32_t flags;
5832/// uint32_t instanceStart;
5833/// uint32_t instanceSize;
5834/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005835/// const uint8_t *ivarLayout;
5836/// const char *name;
5837/// const struct _method_list_t *baseMethods;
5838/// const struct _protocol_list_t *baseProtocols;
5839/// const struct _ivar_list_t *ivars;
5840/// const uint8_t *weakIvarLayout;
5841/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005842/// }
5843
5844/// struct _class_t {
5845/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005846/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005847/// void *cache;
5848/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005849/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005850/// }
5851
5852/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005853/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005854/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005855/// const struct _method_list_t *instance_methods;
5856/// const struct _method_list_t *class_methods;
5857/// const struct _protocol_list_t *protocols;
5858/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005859/// }
5860
5861/// MessageRefTy - LLVM for:
5862/// struct _message_ref_t {
5863/// IMP messenger;
5864/// SEL name;
5865/// };
5866
5867/// SuperMessageRefTy - LLVM for:
5868/// struct _super_message_ref_t {
5869/// SUPER_IMP messenger;
5870/// SEL name;
5871/// };
5872
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005873static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005874 static bool meta_data_declared = false;
5875 if (meta_data_declared)
5876 return;
5877
5878 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005879 Result += "\tconst char *name;\n";
5880 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005881 Result += "};\n";
5882
5883 Result += "\nstruct _protocol_t;\n";
5884
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005885 Result += "\nstruct _objc_method {\n";
5886 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005887 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005888 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005889 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005890
5891 Result += "\nstruct _protocol_t {\n";
5892 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005893 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005894 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005895 Result += "\tconst struct method_list_t *instance_methods;\n";
5896 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005897 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5898 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5899 Result += "\tconst struct _prop_list_t * properties;\n";
5900 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5901 Result += "\tconst unsigned int flags; // = 0\n";
5902 Result += "\tconst char ** extendedMethodTypes;\n";
5903 Result += "};\n";
5904
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005905 Result += "\nstruct _ivar_t {\n";
5906 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005907 Result += "\tconst char *name;\n";
5908 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005909 Result += "\tunsigned int alignment;\n";
5910 Result += "\tunsigned int size;\n";
5911 Result += "};\n";
5912
5913 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005914 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005915 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005916 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005917 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5918 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005919 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005920 Result += "\tconst unsigned char *ivarLayout;\n";
5921 Result += "\tconst char *name;\n";
5922 Result += "\tconst struct _method_list_t *baseMethods;\n";
5923 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5924 Result += "\tconst struct _ivar_list_t *ivars;\n";
5925 Result += "\tconst unsigned char *weakIvarLayout;\n";
5926 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005927 Result += "};\n";
5928
5929 Result += "\nstruct _class_t {\n";
5930 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005931 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005932 Result += "\tvoid *cache;\n";
5933 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005934 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005935 Result += "};\n";
5936
5937 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005938 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005939 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005940 Result += "\tconst struct _method_list_t *instance_methods;\n";
5941 Result += "\tconst struct _method_list_t *class_methods;\n";
5942 Result += "\tconst struct _protocol_list_t *protocols;\n";
5943 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005944 Result += "};\n";
5945
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005946 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005947 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005948 meta_data_declared = true;
5949}
5950
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005951static void Write_protocol_list_t_TypeDecl(std::string &Result,
5952 long super_protocol_count) {
5953 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5954 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5955 Result += "\tstruct _protocol_t *super_protocols[";
5956 Result += utostr(super_protocol_count); Result += "];\n";
5957 Result += "}";
5958}
5959
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005960static void Write_method_list_t_TypeDecl(std::string &Result,
5961 unsigned int method_count) {
5962 Result += "struct /*_method_list_t*/"; Result += " {\n";
5963 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5964 Result += "\tunsigned int method_count;\n";
5965 Result += "\tstruct _objc_method method_list[";
5966 Result += utostr(method_count); Result += "];\n";
5967 Result += "}";
5968}
5969
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005970static void Write__prop_list_t_TypeDecl(std::string &Result,
5971 unsigned int property_count) {
5972 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5973 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5974 Result += "\tunsigned int count_of_properties;\n";
5975 Result += "\tstruct _prop_t prop_list[";
5976 Result += utostr(property_count); Result += "];\n";
5977 Result += "}";
5978}
5979
Fariborz Jahanianae932952012-02-10 20:47:10 +00005980static void Write__ivar_list_t_TypeDecl(std::string &Result,
5981 unsigned int ivar_count) {
5982 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5983 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5984 Result += "\tunsigned int count;\n";
5985 Result += "\tstruct _ivar_t ivar_list[";
5986 Result += utostr(ivar_count); Result += "];\n";
5987 Result += "}";
5988}
5989
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005990static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5991 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5992 StringRef VarName,
5993 StringRef ProtocolName) {
5994 if (SuperProtocols.size() > 0) {
5995 Result += "\nstatic ";
5996 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5997 Result += " "; Result += VarName;
5998 Result += ProtocolName;
5999 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6000 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6001 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6002 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6003 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6004 Result += SuperPD->getNameAsString();
6005 if (i == e-1)
6006 Result += "\n};\n";
6007 else
6008 Result += ",\n";
6009 }
6010 }
6011}
6012
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006013static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6014 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006015 ArrayRef<ObjCMethodDecl *> Methods,
6016 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006017 StringRef TopLevelDeclName,
6018 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006019 if (Methods.size() > 0) {
6020 Result += "\nstatic ";
6021 Write_method_list_t_TypeDecl(Result, Methods.size());
6022 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006023 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006024 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6025 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6026 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6027 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6028 ObjCMethodDecl *MD = Methods[i];
6029 if (i == 0)
6030 Result += "\t{{(struct objc_selector *)\"";
6031 else
6032 Result += "\t{(struct objc_selector *)\"";
6033 Result += (MD)->getSelector().getAsString(); Result += "\"";
6034 Result += ", ";
6035 std::string MethodTypeString;
6036 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6037 Result += "\""; Result += MethodTypeString; Result += "\"";
6038 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006039 if (!MethodImpl)
6040 Result += "0";
6041 else {
6042 Result += "(void *)";
6043 Result += RewriteObj.MethodInternalNames[MD];
6044 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006045 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006046 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006047 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006048 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006049 }
6050 Result += "};\n";
6051 }
6052}
6053
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006054static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006055 ASTContext *Context, std::string &Result,
6056 ArrayRef<ObjCPropertyDecl *> Properties,
6057 const Decl *Container,
6058 StringRef VarName,
6059 StringRef ProtocolName) {
6060 if (Properties.size() > 0) {
6061 Result += "\nstatic ";
6062 Write__prop_list_t_TypeDecl(Result, Properties.size());
6063 Result += " "; Result += VarName;
6064 Result += ProtocolName;
6065 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6066 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6067 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6068 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6069 ObjCPropertyDecl *PropDecl = Properties[i];
6070 if (i == 0)
6071 Result += "\t{{\"";
6072 else
6073 Result += "\t{\"";
6074 Result += PropDecl->getName(); Result += "\",";
6075 std::string PropertyTypeString, QuotePropertyTypeString;
6076 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6077 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6078 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6079 if (i == e-1)
6080 Result += "}}\n";
6081 else
6082 Result += "},\n";
6083 }
6084 Result += "};\n";
6085 }
6086}
6087
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006088// Metadata flags
6089enum MetaDataDlags {
6090 CLS = 0x0,
6091 CLS_META = 0x1,
6092 CLS_ROOT = 0x2,
6093 OBJC2_CLS_HIDDEN = 0x10,
6094 CLS_EXCEPTION = 0x20,
6095
6096 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6097 CLS_HAS_IVAR_RELEASER = 0x40,
6098 /// class was compiled with -fobjc-arr
6099 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6100};
6101
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006102static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6103 unsigned int flags,
6104 const std::string &InstanceStart,
6105 const std::string &InstanceSize,
6106 ArrayRef<ObjCMethodDecl *>baseMethods,
6107 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6108 ArrayRef<ObjCIvarDecl *>ivars,
6109 ArrayRef<ObjCPropertyDecl *>Properties,
6110 StringRef VarName,
6111 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006112 Result += "\nstatic struct _class_ro_t ";
6113 Result += VarName; Result += ClassName;
6114 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6115 Result += "\t";
6116 Result += llvm::utostr(flags); Result += ", ";
6117 Result += InstanceStart; Result += ", ";
6118 Result += InstanceSize; Result += ", \n";
6119 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006120 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6121 if (Triple.getArch() == llvm::Triple::x86_64)
6122 // uint32_t const reserved; // only when building for 64bit targets
6123 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006124 // const uint8_t * const ivarLayout;
6125 Result += "0, \n\t";
6126 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006127 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006128 if (baseMethods.size() > 0) {
6129 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006130 if (metaclass)
6131 Result += "_OBJC_$_CLASS_METHODS_";
6132 else
6133 Result += "_OBJC_$_INSTANCE_METHODS_";
6134 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006135 Result += ",\n\t";
6136 }
6137 else
6138 Result += "0, \n\t";
6139
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006140 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006141 Result += "(const struct _objc_protocol_list *)&";
6142 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6143 Result += ",\n\t";
6144 }
6145 else
6146 Result += "0, \n\t";
6147
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006148 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006149 Result += "(const struct _ivar_list_t *)&";
6150 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6151 Result += ",\n\t";
6152 }
6153 else
6154 Result += "0, \n\t";
6155
6156 // weakIvarLayout
6157 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006158 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006159 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006160 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006161 Result += ",\n";
6162 }
6163 else
6164 Result += "0, \n";
6165
6166 Result += "};\n";
6167}
6168
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006169static void Write_class_t(ASTContext *Context, std::string &Result,
6170 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006171 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6172 bool rootClass = (!CDecl->getSuperClass());
6173 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006174
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006175 if (!rootClass) {
6176 // Find the Root class
6177 RootClass = CDecl->getSuperClass();
6178 while (RootClass->getSuperClass()) {
6179 RootClass = RootClass->getSuperClass();
6180 }
6181 }
6182
6183 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006184 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006185 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006186 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006187 if (CDecl->getImplementation())
6188 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006189 else
6190 Result += "__declspec(dllimport) ";
6191
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006192 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006193 Result += CDecl->getNameAsString();
6194 Result += ";\n";
6195 }
6196 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006197 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006198 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006199 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006200 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006201 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006202 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006203 else
6204 Result += "__declspec(dllimport) ";
6205
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006206 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006207 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006208 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006209 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006210
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006211 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006212 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006213 if (RootClass->getImplementation())
6214 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006215 else
6216 Result += "__declspec(dllimport) ";
6217
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006218 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006219 Result += VarName;
6220 Result += RootClass->getNameAsString();
6221 Result += ";\n";
6222 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006223 }
6224
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006225 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6226 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006227 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6228 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006229 if (metaclass) {
6230 if (!rootClass) {
6231 Result += "0, // &"; Result += VarName;
6232 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006233 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006234 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006235 Result += CDecl->getSuperClass()->getNameAsString();
6236 Result += ",\n\t";
6237 }
6238 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006239 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006240 Result += CDecl->getNameAsString();
6241 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006242 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006243 Result += ",\n\t";
6244 }
6245 }
6246 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006247 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006248 Result += CDecl->getNameAsString();
6249 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006250 if (!rootClass) {
6251 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006252 Result += CDecl->getSuperClass()->getNameAsString();
6253 Result += ",\n\t";
6254 }
6255 else
6256 Result += "0,\n\t";
6257 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006258 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6259 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6260 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006261 Result += "&_OBJC_METACLASS_RO_$_";
6262 else
6263 Result += "&_OBJC_CLASS_RO_$_";
6264 Result += CDecl->getNameAsString();
6265 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006266
6267 // Add static function to initialize some of the meta-data fields.
6268 // avoid doing it twice.
6269 if (metaclass)
6270 return;
6271
6272 const ObjCInterfaceDecl *SuperClass =
6273 rootClass ? CDecl : CDecl->getSuperClass();
6274
6275 Result += "static void OBJC_CLASS_SETUP_$_";
6276 Result += CDecl->getNameAsString();
6277 Result += "(void ) {\n";
6278 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6279 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006280 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006281
6282 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006283 Result += ".superclass = ";
6284 if (rootClass)
6285 Result += "&OBJC_CLASS_$_";
6286 else
6287 Result += "&OBJC_METACLASS_$_";
6288
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006289 Result += SuperClass->getNameAsString(); Result += ";\n";
6290
6291 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6292 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6293
6294 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6295 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6296 Result += CDecl->getNameAsString(); Result += ";\n";
6297
6298 if (!rootClass) {
6299 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6300 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6301 Result += SuperClass->getNameAsString(); Result += ";\n";
6302 }
6303
6304 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6305 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6306 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006307}
6308
Fariborz Jahanian61186122012-02-17 18:40:41 +00006309static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6310 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006311 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006312 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006313 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6314 ArrayRef<ObjCMethodDecl *> ClassMethods,
6315 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6316 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006317 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006318 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006319 // must declare an extern class object in case this class is not implemented
6320 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006321 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006322 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006323 if (ClassDecl->getImplementation())
6324 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006325 else
6326 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006327
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006328 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006329 Result += "OBJC_CLASS_$_"; Result += ClassName;
6330 Result += ";\n";
6331
Fariborz Jahanian61186122012-02-17 18:40:41 +00006332 Result += "\nstatic struct _category_t ";
6333 Result += "_OBJC_$_CATEGORY_";
6334 Result += ClassName; Result += "_$_"; Result += CatName;
6335 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6336 Result += "{\n";
6337 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006338 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006339 Result += ",\n";
6340 if (InstanceMethods.size() > 0) {
6341 Result += "\t(const struct _method_list_t *)&";
6342 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6343 Result += ClassName; Result += "_$_"; Result += CatName;
6344 Result += ",\n";
6345 }
6346 else
6347 Result += "\t0,\n";
6348
6349 if (ClassMethods.size() > 0) {
6350 Result += "\t(const struct _method_list_t *)&";
6351 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6352 Result += ClassName; Result += "_$_"; Result += CatName;
6353 Result += ",\n";
6354 }
6355 else
6356 Result += "\t0,\n";
6357
6358 if (RefedProtocols.size() > 0) {
6359 Result += "\t(const struct _protocol_list_t *)&";
6360 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6361 Result += ClassName; Result += "_$_"; Result += CatName;
6362 Result += ",\n";
6363 }
6364 else
6365 Result += "\t0,\n";
6366
6367 if (ClassProperties.size() > 0) {
6368 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6369 Result += ClassName; Result += "_$_"; Result += CatName;
6370 Result += ",\n";
6371 }
6372 else
6373 Result += "\t0,\n";
6374
6375 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006376
6377 // Add static function to initialize the class pointer in the category structure.
6378 Result += "static void OBJC_CATEGORY_SETUP_$_";
6379 Result += ClassDecl->getNameAsString();
6380 Result += "_$_";
6381 Result += CatName;
6382 Result += "(void ) {\n";
6383 Result += "\t_OBJC_$_CATEGORY_";
6384 Result += ClassDecl->getNameAsString();
6385 Result += "_$_";
6386 Result += CatName;
6387 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6388 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006389}
6390
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006391static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6392 ASTContext *Context, std::string &Result,
6393 ArrayRef<ObjCMethodDecl *> Methods,
6394 StringRef VarName,
6395 StringRef ProtocolName) {
6396 if (Methods.size() == 0)
6397 return;
6398
6399 Result += "\nstatic const char *";
6400 Result += VarName; Result += ProtocolName;
6401 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6402 Result += "{\n";
6403 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6404 ObjCMethodDecl *MD = Methods[i];
6405 std::string MethodTypeString, QuoteMethodTypeString;
6406 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6407 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6408 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6409 if (i == e-1)
6410 Result += "\n};\n";
6411 else {
6412 Result += ",\n";
6413 }
6414 }
6415}
6416
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006417static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6418 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006419 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006420 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006421 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006422 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6423 // this is what happens:
6424 /**
6425 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6426 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6427 Class->getVisibility() == HiddenVisibility)
6428 Visibility shoud be: HiddenVisibility;
6429 else
6430 Visibility shoud be: DefaultVisibility;
6431 */
6432
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006433 Result += "\n";
6434 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6435 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006436 if (Context->getLangOpts().MicrosoftExt)
6437 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6438
6439 if (!Context->getLangOpts().MicrosoftExt ||
6440 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006441 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006442 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006443 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006444 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006445 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006446 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6447 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006448 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6449 Result += ";\n";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006450 }
6451}
6452
Fariborz Jahanianae932952012-02-10 20:47:10 +00006453static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6454 ASTContext *Context, std::string &Result,
6455 ArrayRef<ObjCIvarDecl *> Ivars,
6456 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006457 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006458 if (Ivars.size() > 0) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006459 Write_IvarOffsetVar(RewriteObj, Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006460
Fariborz Jahanianae932952012-02-10 20:47:10 +00006461 Result += "\nstatic ";
6462 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6463 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006464 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006465 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6466 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6467 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6468 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6469 ObjCIvarDecl *IvarDecl = Ivars[i];
6470 if (i == 0)
6471 Result += "\t{{";
6472 else
6473 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006474 Result += "(unsigned long int *)&";
6475 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006476 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006477
6478 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6479 std::string IvarTypeString, QuoteIvarTypeString;
6480 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6481 IvarDecl);
6482 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6483 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6484
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006485 // FIXME. this alignment represents the host alignment and need be changed to
6486 // represent the target alignment.
6487 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6488 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006489 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006490 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6491 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006492 if (i == e-1)
6493 Result += "}}\n";
6494 else
6495 Result += "},\n";
6496 }
6497 Result += "};\n";
6498 }
6499}
6500
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006501/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006502void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6503 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006504
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006505 // Do not synthesize the protocol more than once.
6506 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6507 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006508 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006509
6510 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6511 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006512 // Must write out all protocol definitions in current qualifier list,
6513 // and in their nested qualifiers before writing out current definition.
6514 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6515 E = PDecl->protocol_end(); I != E; ++I)
6516 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006517
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006518 // Construct method lists.
6519 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6520 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6521 for (ObjCProtocolDecl::instmeth_iterator
6522 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6523 I != E; ++I) {
6524 ObjCMethodDecl *MD = *I;
6525 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6526 OptInstanceMethods.push_back(MD);
6527 } else {
6528 InstanceMethods.push_back(MD);
6529 }
6530 }
6531
6532 for (ObjCProtocolDecl::classmeth_iterator
6533 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6534 I != E; ++I) {
6535 ObjCMethodDecl *MD = *I;
6536 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6537 OptClassMethods.push_back(MD);
6538 } else {
6539 ClassMethods.push_back(MD);
6540 }
6541 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006542 std::vector<ObjCMethodDecl *> AllMethods;
6543 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6544 AllMethods.push_back(InstanceMethods[i]);
6545 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6546 AllMethods.push_back(ClassMethods[i]);
6547 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6548 AllMethods.push_back(OptInstanceMethods[i]);
6549 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6550 AllMethods.push_back(OptClassMethods[i]);
6551
6552 Write__extendedMethodTypes_initializer(*this, Context, Result,
6553 AllMethods,
6554 "_OBJC_PROTOCOL_METHOD_TYPES_",
6555 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006556 // Protocol's super protocol list
6557 std::vector<ObjCProtocolDecl *> SuperProtocols;
6558 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6559 E = PDecl->protocol_end(); I != E; ++I)
6560 SuperProtocols.push_back(*I);
6561
6562 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6563 "_OBJC_PROTOCOL_REFS_",
6564 PDecl->getNameAsString());
6565
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006566 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006567 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006568 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006569
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006570 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006571 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006572 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006573
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006574 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006575 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006576 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006577
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006578 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006579 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006580 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006581
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006582 // Protocol's property metadata.
6583 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6584 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6585 E = PDecl->prop_end(); I != E; ++I)
6586 ProtocolProperties.push_back(*I);
6587
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006588 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006589 /* Container */0,
6590 "_OBJC_PROTOCOL_PROPERTIES_",
6591 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006592
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006593 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006594 Result += "\n";
6595 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006596 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006597 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006598 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006599 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6600 Result += "\t0,\n"; // id is; is null
6601 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006602 if (SuperProtocols.size() > 0) {
6603 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6604 Result += PDecl->getNameAsString(); Result += ",\n";
6605 }
6606 else
6607 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006608 if (InstanceMethods.size() > 0) {
6609 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6610 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006611 }
6612 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006613 Result += "\t0,\n";
6614
6615 if (ClassMethods.size() > 0) {
6616 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6617 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006618 }
6619 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006620 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006621
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006622 if (OptInstanceMethods.size() > 0) {
6623 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6624 Result += PDecl->getNameAsString(); Result += ",\n";
6625 }
6626 else
6627 Result += "\t0,\n";
6628
6629 if (OptClassMethods.size() > 0) {
6630 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6631 Result += PDecl->getNameAsString(); Result += ",\n";
6632 }
6633 else
6634 Result += "\t0,\n";
6635
6636 if (ProtocolProperties.size() > 0) {
6637 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6638 Result += PDecl->getNameAsString(); Result += ",\n";
6639 }
6640 else
6641 Result += "\t0,\n";
6642
6643 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6644 Result += "\t0,\n";
6645
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006646 if (AllMethods.size() > 0) {
6647 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6648 Result += PDecl->getNameAsString();
6649 Result += "\n};\n";
6650 }
6651 else
6652 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006653
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006654 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00006655 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006656 Result += "struct _protocol_t *";
6657 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6658 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6659 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006660
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006661 // Mark this protocol as having been generated.
6662 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6663 llvm_unreachable("protocol already synthesized");
6664
6665}
6666
6667void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6668 const ObjCList<ObjCProtocolDecl> &Protocols,
6669 StringRef prefix, StringRef ClassName,
6670 std::string &Result) {
6671 if (Protocols.empty()) return;
6672
6673 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006674 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006675
6676 // Output the top lovel protocol meta-data for the class.
6677 /* struct _objc_protocol_list {
6678 struct _objc_protocol_list *next;
6679 int protocol_count;
6680 struct _objc_protocol *class_protocols[];
6681 }
6682 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006683 Result += "\n";
6684 if (LangOpts.MicrosoftExt)
6685 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6686 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006687 Result += "\tstruct _objc_protocol_list *next;\n";
6688 Result += "\tint protocol_count;\n";
6689 Result += "\tstruct _objc_protocol *class_protocols[";
6690 Result += utostr(Protocols.size());
6691 Result += "];\n} _OBJC_";
6692 Result += prefix;
6693 Result += "_PROTOCOLS_";
6694 Result += ClassName;
6695 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6696 "{\n\t0, ";
6697 Result += utostr(Protocols.size());
6698 Result += "\n";
6699
6700 Result += "\t,{&_OBJC_PROTOCOL_";
6701 Result += Protocols[0]->getNameAsString();
6702 Result += " \n";
6703
6704 for (unsigned i = 1; i != Protocols.size(); i++) {
6705 Result += "\t ,&_OBJC_PROTOCOL_";
6706 Result += Protocols[i]->getNameAsString();
6707 Result += "\n";
6708 }
6709 Result += "\t }\n};\n";
6710}
6711
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006712/// hasObjCExceptionAttribute - Return true if this class or any super
6713/// class has the __objc_exception__ attribute.
6714/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6715static bool hasObjCExceptionAttribute(ASTContext &Context,
6716 const ObjCInterfaceDecl *OID) {
6717 if (OID->hasAttr<ObjCExceptionAttr>())
6718 return true;
6719 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6720 return hasObjCExceptionAttribute(Context, Super);
6721 return false;
6722}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006723
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006724void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6725 std::string &Result) {
6726 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6727
6728 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006729 if (CDecl->isImplicitInterfaceDecl())
6730 assert(false &&
6731 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006732
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006733 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006734 SmallVector<ObjCIvarDecl *, 8> IVars;
6735
6736 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6737 IVD; IVD = IVD->getNextIvar()) {
6738 // Ignore unnamed bit-fields.
6739 if (!IVD->getDeclName())
6740 continue;
6741 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006742 }
6743
Fariborz Jahanianae932952012-02-10 20:47:10 +00006744 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006745 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006746 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006747
6748 // Build _objc_method_list for class's instance methods if needed
6749 SmallVector<ObjCMethodDecl *, 32>
6750 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6751
6752 // If any of our property implementations have associated getters or
6753 // setters, produce metadata for them as well.
6754 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6755 PropEnd = IDecl->propimpl_end();
6756 Prop != PropEnd; ++Prop) {
6757 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6758 continue;
6759 if (!(*Prop)->getPropertyIvarDecl())
6760 continue;
6761 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6762 if (!PD)
6763 continue;
6764 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6765 if (!Getter->isDefined())
6766 InstanceMethods.push_back(Getter);
6767 if (PD->isReadOnly())
6768 continue;
6769 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6770 if (!Setter->isDefined())
6771 InstanceMethods.push_back(Setter);
6772 }
6773
6774 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6775 "_OBJC_$_INSTANCE_METHODS_",
6776 IDecl->getNameAsString(), true);
6777
6778 SmallVector<ObjCMethodDecl *, 32>
6779 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6780
6781 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6782 "_OBJC_$_CLASS_METHODS_",
6783 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006784
6785 // Protocols referenced in class declaration?
6786 // Protocol's super protocol list
6787 std::vector<ObjCProtocolDecl *> RefedProtocols;
6788 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6789 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6790 E = Protocols.end();
6791 I != E; ++I) {
6792 RefedProtocols.push_back(*I);
6793 // Must write out all protocol definitions in current qualifier list,
6794 // and in their nested qualifiers before writing out current definition.
6795 RewriteObjCProtocolMetaData(*I, Result);
6796 }
6797
6798 Write_protocol_list_initializer(Context, Result,
6799 RefedProtocols,
6800 "_OBJC_CLASS_PROTOCOLS_$_",
6801 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006802
6803 // Protocol's property metadata.
6804 std::vector<ObjCPropertyDecl *> ClassProperties;
6805 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6806 E = CDecl->prop_end(); I != E; ++I)
6807 ClassProperties.push_back(*I);
6808
6809 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006810 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006811 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006812 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006813
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006814
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006815 // Data for initializing _class_ro_t metaclass meta-data
6816 uint32_t flags = CLS_META;
6817 std::string InstanceSize;
6818 std::string InstanceStart;
6819
6820
6821 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6822 if (classIsHidden)
6823 flags |= OBJC2_CLS_HIDDEN;
6824
6825 if (!CDecl->getSuperClass())
6826 // class is root
6827 flags |= CLS_ROOT;
6828 InstanceSize = "sizeof(struct _class_t)";
6829 InstanceStart = InstanceSize;
6830 Write__class_ro_t_initializer(Context, Result, flags,
6831 InstanceStart, InstanceSize,
6832 ClassMethods,
6833 0,
6834 0,
6835 0,
6836 "_OBJC_METACLASS_RO_$_",
6837 CDecl->getNameAsString());
6838
6839
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006840 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006841 flags = CLS;
6842 if (classIsHidden)
6843 flags |= OBJC2_CLS_HIDDEN;
6844
6845 if (hasObjCExceptionAttribute(*Context, CDecl))
6846 flags |= CLS_EXCEPTION;
6847
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006848 if (!CDecl->getSuperClass())
6849 // class is root
6850 flags |= CLS_ROOT;
6851
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006852 InstanceSize.clear();
6853 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006854 if (!ObjCSynthesizedStructs.count(CDecl)) {
6855 InstanceSize = "0";
6856 InstanceStart = "0";
6857 }
6858 else {
6859 InstanceSize = "sizeof(struct ";
6860 InstanceSize += CDecl->getNameAsString();
6861 InstanceSize += "_IMPL)";
6862
6863 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6864 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006865 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006866 }
6867 else
6868 InstanceStart = InstanceSize;
6869 }
6870 Write__class_ro_t_initializer(Context, Result, flags,
6871 InstanceStart, InstanceSize,
6872 InstanceMethods,
6873 RefedProtocols,
6874 IVars,
6875 ClassProperties,
6876 "_OBJC_CLASS_RO_$_",
6877 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006878
6879 Write_class_t(Context, Result,
6880 "OBJC_METACLASS_$_",
6881 CDecl, /*metaclass*/true);
6882
6883 Write_class_t(Context, Result,
6884 "OBJC_CLASS_$_",
6885 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006886
6887 if (ImplementationIsNonLazy(IDecl))
6888 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006889
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006890}
6891
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006892void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6893 int ClsDefCount = ClassImplementation.size();
6894 if (!ClsDefCount)
6895 return;
6896 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6897 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6898 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6899 for (int i = 0; i < ClsDefCount; i++) {
6900 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6901 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6902 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6903 Result += CDecl->getName(); Result += ",\n";
6904 }
6905 Result += "};\n";
6906}
6907
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006908void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6909 int ClsDefCount = ClassImplementation.size();
6910 int CatDefCount = CategoryImplementation.size();
6911
6912 // For each implemented class, write out all its meta data.
6913 for (int i = 0; i < ClsDefCount; i++)
6914 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6915
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006916 RewriteClassSetupInitHook(Result);
6917
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006918 // For each implemented category, write out all its meta data.
6919 for (int i = 0; i < CatDefCount; i++)
6920 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6921
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006922 RewriteCategorySetupInitHook(Result);
6923
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006924 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006925 if (LangOpts.MicrosoftExt)
6926 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006927 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6928 Result += llvm::utostr(ClsDefCount); Result += "]";
6929 Result +=
6930 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6931 "regular,no_dead_strip\")))= {\n";
6932 for (int i = 0; i < ClsDefCount; i++) {
6933 Result += "\t&OBJC_CLASS_$_";
6934 Result += ClassImplementation[i]->getNameAsString();
6935 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006936 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006937 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006938
6939 if (!DefinedNonLazyClasses.empty()) {
6940 if (LangOpts.MicrosoftExt)
6941 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6942 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6943 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6944 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6945 Result += ",\n";
6946 }
6947 Result += "};\n";
6948 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006949 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006950
6951 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006952 if (LangOpts.MicrosoftExt)
6953 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006954 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6955 Result += llvm::utostr(CatDefCount); Result += "]";
6956 Result +=
6957 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6958 "regular,no_dead_strip\")))= {\n";
6959 for (int i = 0; i < CatDefCount; i++) {
6960 Result += "\t&_OBJC_$_CATEGORY_";
6961 Result +=
6962 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6963 Result += "_$_";
6964 Result += CategoryImplementation[i]->getNameAsString();
6965 Result += ",\n";
6966 }
6967 Result += "};\n";
6968 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006969
6970 if (!DefinedNonLazyCategories.empty()) {
6971 if (LangOpts.MicrosoftExt)
6972 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6973 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6974 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6975 Result += "\t&_OBJC_$_CATEGORY_";
6976 Result +=
6977 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6978 Result += "_$_";
6979 Result += DefinedNonLazyCategories[i]->getNameAsString();
6980 Result += ",\n";
6981 }
6982 Result += "};\n";
6983 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006984}
6985
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006986void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6987 if (LangOpts.MicrosoftExt)
6988 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6989
6990 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6991 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006992 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006993}
6994
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006995/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6996/// implementation.
6997void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6998 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006999 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007000 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7001 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00007002 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007003 for (CDecl = ClassDecl->getCategoryList(); CDecl;
7004 CDecl = CDecl->getNextClassCategory())
7005 if (CDecl->getIdentifier() == IDecl->getIdentifier())
7006 break;
7007
7008 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007009 FullCategoryName += "_$_";
7010 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007011
7012 // Build _objc_method_list for class's instance methods if needed
7013 SmallVector<ObjCMethodDecl *, 32>
7014 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7015
7016 // If any of our property implementations have associated getters or
7017 // setters, produce metadata for them as well.
7018 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7019 PropEnd = IDecl->propimpl_end();
7020 Prop != PropEnd; ++Prop) {
7021 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7022 continue;
7023 if (!(*Prop)->getPropertyIvarDecl())
7024 continue;
7025 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
7026 if (!PD)
7027 continue;
7028 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7029 InstanceMethods.push_back(Getter);
7030 if (PD->isReadOnly())
7031 continue;
7032 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7033 InstanceMethods.push_back(Setter);
7034 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007035
Fariborz Jahanian61186122012-02-17 18:40:41 +00007036 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7037 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7038 FullCategoryName, true);
7039
7040 SmallVector<ObjCMethodDecl *, 32>
7041 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7042
7043 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7044 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7045 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007046
7047 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007048 // Protocol's super protocol list
7049 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007050 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7051 E = CDecl->protocol_end();
7052
7053 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007054 RefedProtocols.push_back(*I);
7055 // Must write out all protocol definitions in current qualifier list,
7056 // and in their nested qualifiers before writing out current definition.
7057 RewriteObjCProtocolMetaData(*I, Result);
7058 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007059
Fariborz Jahanian61186122012-02-17 18:40:41 +00007060 Write_protocol_list_initializer(Context, Result,
7061 RefedProtocols,
7062 "_OBJC_CATEGORY_PROTOCOLS_$_",
7063 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007064
Fariborz Jahanian61186122012-02-17 18:40:41 +00007065 // Protocol's property metadata.
7066 std::vector<ObjCPropertyDecl *> ClassProperties;
7067 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7068 E = CDecl->prop_end(); I != E; ++I)
7069 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007070
Fariborz Jahanian61186122012-02-17 18:40:41 +00007071 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7072 /* Container */0,
7073 "_OBJC_$_PROP_LIST_",
7074 FullCategoryName);
7075
7076 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007077 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007078 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007079 InstanceMethods,
7080 ClassMethods,
7081 RefedProtocols,
7082 ClassProperties);
7083
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007084 // Determine if this category is also "non-lazy".
7085 if (ImplementationIsNonLazy(IDecl))
7086 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007087
7088}
7089
7090void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7091 int CatDefCount = CategoryImplementation.size();
7092 if (!CatDefCount)
7093 return;
7094 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7095 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7096 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7097 for (int i = 0; i < CatDefCount; i++) {
7098 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7099 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7100 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7101 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7102 Result += ClassDecl->getName();
7103 Result += "_$_";
7104 Result += CatDecl->getName();
7105 Result += ",\n";
7106 }
7107 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007108}
7109
7110// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7111/// class methods.
7112template<typename MethodIterator>
7113void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7114 MethodIterator MethodEnd,
7115 bool IsInstanceMethod,
7116 StringRef prefix,
7117 StringRef ClassName,
7118 std::string &Result) {
7119 if (MethodBegin == MethodEnd) return;
7120
7121 if (!objc_impl_method) {
7122 /* struct _objc_method {
7123 SEL _cmd;
7124 char *method_types;
7125 void *_imp;
7126 }
7127 */
7128 Result += "\nstruct _objc_method {\n";
7129 Result += "\tSEL _cmd;\n";
7130 Result += "\tchar *method_types;\n";
7131 Result += "\tvoid *_imp;\n";
7132 Result += "};\n";
7133
7134 objc_impl_method = true;
7135 }
7136
7137 // Build _objc_method_list for class's methods if needed
7138
7139 /* struct {
7140 struct _objc_method_list *next_method;
7141 int method_count;
7142 struct _objc_method method_list[];
7143 }
7144 */
7145 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007146 Result += "\n";
7147 if (LangOpts.MicrosoftExt) {
7148 if (IsInstanceMethod)
7149 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7150 else
7151 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7152 }
7153 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007154 Result += "\tstruct _objc_method_list *next_method;\n";
7155 Result += "\tint method_count;\n";
7156 Result += "\tstruct _objc_method method_list[";
7157 Result += utostr(NumMethods);
7158 Result += "];\n} _OBJC_";
7159 Result += prefix;
7160 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7161 Result += "_METHODS_";
7162 Result += ClassName;
7163 Result += " __attribute__ ((used, section (\"__OBJC, __";
7164 Result += IsInstanceMethod ? "inst" : "cls";
7165 Result += "_meth\")))= ";
7166 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7167
7168 Result += "\t,{{(SEL)\"";
7169 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7170 std::string MethodTypeString;
7171 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7172 Result += "\", \"";
7173 Result += MethodTypeString;
7174 Result += "\", (void *)";
7175 Result += MethodInternalNames[*MethodBegin];
7176 Result += "}\n";
7177 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7178 Result += "\t ,{(SEL)\"";
7179 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7180 std::string MethodTypeString;
7181 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7182 Result += "\", \"";
7183 Result += MethodTypeString;
7184 Result += "\", (void *)";
7185 Result += MethodInternalNames[*MethodBegin];
7186 Result += "}\n";
7187 }
7188 Result += "\t }\n};\n";
7189}
7190
7191Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7192 SourceRange OldRange = IV->getSourceRange();
7193 Expr *BaseExpr = IV->getBase();
7194
7195 // Rewrite the base, but without actually doing replaces.
7196 {
7197 DisableReplaceStmtScope S(*this);
7198 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7199 IV->setBase(BaseExpr);
7200 }
7201
7202 ObjCIvarDecl *D = IV->getDecl();
7203
7204 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007205
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007206 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7207 const ObjCInterfaceType *iFaceDecl =
7208 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7209 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7210 // lookup which class implements the instance variable.
7211 ObjCInterfaceDecl *clsDeclared = 0;
7212 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7213 clsDeclared);
7214 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7215
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007216 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007217 std::string IvarOffsetName;
7218 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7219
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007220 ReferencedIvars[clsDeclared].insert(D);
7221
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007222 // cast offset to "char *".
7223 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7224 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007225 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007226 BaseExpr);
7227 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7228 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7229 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007230 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7231 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007232 SourceLocation());
7233 BinaryOperator *addExpr =
7234 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7235 Context->getPointerType(Context->CharTy),
7236 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007237 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007238 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7239 SourceLocation(),
7240 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007241 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007242 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007243 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007244
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007245 castExpr = NoTypeInfoCStyleCastExpr(Context,
7246 castT,
7247 CK_BitCast,
7248 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007249 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007250 VK_LValue, OK_Ordinary,
7251 SourceLocation());
7252 PE = new (Context) ParenExpr(OldRange.getBegin(),
7253 OldRange.getEnd(),
7254 Exp);
7255
7256 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007257 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007258
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007259 ReplaceStmtWithRange(IV, Replacement, OldRange);
7260 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007261}