blob: 45369a95deaefc55eeba74479e70cf7c68c32a5c [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;
105 FunctionDecl *CurFunctionDeclToDeclareForBlock;
106
107 /* Misc. containers needed for meta-data rewrite. */
108 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
109 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
111 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000113 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000114 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000115 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
116 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
117
118 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
119 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000121 SmallVector<Stmt *, 32> Stmts;
122 SmallVector<int, 8> ObjCBcLabelNo;
123 // Remember all the @protocol(<expr>) expressions.
124 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
125
126 llvm::DenseSet<uint64_t> CopyDestroyCache;
127
128 // Block expressions.
129 SmallVector<BlockExpr *, 32> Blocks;
130 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
John McCallf4b88a42012-03-10 09:33:50 +0000133 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000134
135 // Block related declarations.
136 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
138 SmallVector<ValueDecl *, 8> BlockByRefDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
140 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
141 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
142 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
143
144 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000145 llvm::DenseMap<ObjCInterfaceDecl *,
146 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
147
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000148 // This maps an original source AST to it's rewritten form. This allows
149 // us to avoid rewriting the same node twice (which is very uncommon).
150 // This is needed to support some of the exotic property rewriting.
151 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
152
153 // Needed for header files being rewritten
154 bool IsHeader;
155 bool SilenceRewriteMacroWarning;
156 bool objc_impl_method;
157
158 bool DisableReplaceStmt;
159 class DisableReplaceStmtScope {
160 RewriteModernObjC &R;
161 bool SavedValue;
162
163 public:
164 DisableReplaceStmtScope(RewriteModernObjC &R)
165 : R(R), SavedValue(R.DisableReplaceStmt) {
166 R.DisableReplaceStmt = true;
167 }
168 ~DisableReplaceStmtScope() {
169 R.DisableReplaceStmt = SavedValue;
170 }
171 };
172 void InitializeCommon(ASTContext &context);
173
174 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000175 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000176 // Top Level Driver code.
177 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
178 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
179 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
180 if (!Class->isThisDeclarationADefinition()) {
181 RewriteForwardClassDecl(D);
182 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000183 } else {
184 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000185 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000186 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000187 }
188 }
189
190 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
191 if (!Proto->isThisDeclarationADefinition()) {
192 RewriteForwardProtocolDecl(D);
193 break;
194 }
195 }
196
197 HandleTopLevelSingleDecl(*I);
198 }
199 return true;
200 }
201 void HandleTopLevelSingleDecl(Decl *D);
202 void HandleDeclInMainFile(Decl *D);
203 RewriteModernObjC(std::string inFile, raw_ostream *OS,
204 DiagnosticsEngine &D, const LangOptions &LOpts,
205 bool silenceMacroWarn);
206
207 ~RewriteModernObjC() {}
208
209 virtual void HandleTranslationUnit(ASTContext &C);
210
211 void ReplaceStmt(Stmt *Old, Stmt *New) {
212 Stmt *ReplacingStmt = ReplacedNodes[Old];
213
214 if (ReplacingStmt)
215 return; // We can't rewrite the same node twice.
216
217 if (DisableReplaceStmt)
218 return;
219
220 // If replacement succeeded or warning disabled return with no warning.
221 if (!Rewrite.ReplaceStmt(Old, New)) {
222 ReplacedNodes[Old] = New;
223 return;
224 }
225 if (SilenceRewriteMacroWarning)
226 return;
227 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
228 << Old->getSourceRange();
229 }
230
231 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
232 if (DisableReplaceStmt)
233 return;
234
235 // Measure the old text.
236 int Size = Rewrite.getRangeSize(SrcRange);
237 if (Size == -1) {
238 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
239 << Old->getSourceRange();
240 return;
241 }
242 // Get the new text.
243 std::string SStr;
244 llvm::raw_string_ostream S(SStr);
245 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
246 const std::string &Str = S.str();
247
248 // If replacement succeeded or warning disabled return with no warning.
249 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
250 ReplacedNodes[Old] = New;
251 return;
252 }
253 if (SilenceRewriteMacroWarning)
254 return;
255 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
256 << Old->getSourceRange();
257 }
258
259 void InsertText(SourceLocation Loc, StringRef Str,
260 bool InsertAfter = true) {
261 // If insertion succeeded or warning disabled return with no warning.
262 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
263 SilenceRewriteMacroWarning)
264 return;
265
266 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
267 }
268
269 void ReplaceText(SourceLocation Start, unsigned OrigLength,
270 StringRef Str) {
271 // If removal succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
273 SilenceRewriteMacroWarning)
274 return;
275
276 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
277 }
278
279 // Syntactic Rewriting.
280 void RewriteRecordBody(RecordDecl *RD);
281 void RewriteInclude();
282 void RewriteForwardClassDecl(DeclGroupRef D);
283 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
284 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
285 const std::string &typedefString);
286 void RewriteImplementations();
287 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
288 ObjCImplementationDecl *IMD,
289 ObjCCategoryImplDecl *CID);
290 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
291 void RewriteImplementationDecl(Decl *Dcl);
292 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
293 ObjCMethodDecl *MDecl, std::string &ResultStr);
294 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
295 const FunctionType *&FPRetType);
296 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
297 ValueDecl *VD, bool def=false);
298 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
299 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
300 void RewriteForwardProtocolDecl(DeclGroupRef D);
301 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
302 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
303 void RewriteProperty(ObjCPropertyDecl *prop);
304 void RewriteFunctionDecl(FunctionDecl *FD);
305 void RewriteBlockPointerType(std::string& Str, QualType Type);
306 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
307 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
308 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
309 void RewriteTypeOfDecl(VarDecl *VD);
310 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
311
312 // Expression Rewriting.
313 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
314 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
315 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
316 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
317 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
318 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
319 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000320 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +0000321 Stmt *RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000322 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *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 Jahanianb3f904f2012-04-03 17:35:38 +0000332 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000333
334 // Block rewriting.
335 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
336
337 // Block specific rewrite rules.
338 void RewriteBlockPointerDecl(NamedDecl *VD);
339 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000340 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000341 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
342 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
343
344 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
345 std::string &Result);
346
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000347 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
348
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000349 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
350
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000351 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
352 std::string &Result);
353
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000354 virtual void Initialize(ASTContext &context);
355
356 // Misc. AST transformation routines. Somtimes they end up calling
357 // rewriting routines on the new ASTs.
358 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
359 Expr **args, unsigned nargs,
360 SourceLocation StartLoc=SourceLocation(),
361 SourceLocation EndLoc=SourceLocation());
362
363 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
364 SourceLocation StartLoc=SourceLocation(),
365 SourceLocation EndLoc=SourceLocation());
366
367 void SynthCountByEnumWithState(std::string &buf);
368 void SynthMsgSendFunctionDecl();
369 void SynthMsgSendSuperFunctionDecl();
370 void SynthMsgSendStretFunctionDecl();
371 void SynthMsgSendFpretFunctionDecl();
372 void SynthMsgSendSuperStretFunctionDecl();
373 void SynthGetClassFunctionDecl();
374 void SynthGetMetaClassFunctionDecl();
375 void SynthGetSuperClassFunctionDecl();
376 void SynthSelGetUidFunctionDecl();
377 void SynthSuperContructorFunctionDecl();
378
379 // Rewriting metadata
380 template<typename MethodIterator>
381 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
382 MethodIterator MethodEnd,
383 bool IsInstanceMethod,
384 StringRef prefix,
385 StringRef ClassName,
386 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000387 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
388 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000389 virtual void RewriteObjCProtocolListMetaData(
390 const ObjCList<ObjCProtocolDecl> &Prots,
391 StringRef prefix, StringRef ClassName, std::string &Result);
392 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
393 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000394 virtual void RewriteClassSetupInitHook(std::string &Result);
395
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000396 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000397 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000398 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
399 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000400 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000401
402 // Rewriting ivar
403 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
404 std::string &Result);
405 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
406
407
408 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
409 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
410 StringRef funcName, std::string Tag);
411 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
412 StringRef funcName, std::string Tag);
413 std::string SynthesizeBlockImpl(BlockExpr *CE,
414 std::string Tag, std::string Desc);
415 std::string SynthesizeBlockDescriptor(std::string DescTag,
416 std::string ImplTag,
417 int i, StringRef funcName,
418 unsigned hasCopy);
419 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
420 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
421 StringRef FunName);
422 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
423 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000424 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000425
426 // Misc. helper routines.
427 QualType getProtocolType();
428 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000429 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
430 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
431 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
432
433 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
434 void CollectBlockDeclRefInfo(BlockExpr *Exp);
435 void GetBlockDeclRefExprs(Stmt *S);
436 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000437 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000438 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
439
440 // We avoid calling Type::isBlockPointerType(), since it operates on the
441 // canonical type. We only care if the top-level type is a closure pointer.
442 bool isTopLevelBlockPointerType(QualType T) {
443 return isa<BlockPointerType>(T);
444 }
445
446 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
447 /// to a function pointer type and upon success, returns true; false
448 /// otherwise.
449 bool convertBlockPointerToFunctionPointer(QualType &T) {
450 if (isTopLevelBlockPointerType(T)) {
451 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
452 T = Context->getPointerType(BPT->getPointeeType());
453 return true;
454 }
455 return false;
456 }
457
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000458 bool convertObjCTypeToCStyleType(QualType &T);
459
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000460 bool needToScanForQualifiers(QualType T);
461 QualType getSuperStructType();
462 QualType getConstantStringStructType();
463 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
464 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
465
466 void convertToUnqualifiedObjCType(QualType &T) {
467 if (T->isObjCQualifiedIdType())
468 T = Context->getObjCIdType();
469 else if (T->isObjCQualifiedClassType())
470 T = Context->getObjCClassType();
471 else if (T->isObjCObjectPointerType() &&
472 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
473 if (const ObjCObjectPointerType * OBJPT =
474 T->getAsObjCInterfacePointerType()) {
475 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
476 T = QualType(IFaceT, 0);
477 T = Context->getPointerType(T);
478 }
479 }
480 }
481
482 // FIXME: This predicate seems like it would be useful to add to ASTContext.
483 bool isObjCType(QualType T) {
484 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
485 return false;
486
487 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
488
489 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
490 OCT == Context->getCanonicalType(Context->getObjCClassType()))
491 return true;
492
493 if (const PointerType *PT = OCT->getAs<PointerType>()) {
494 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
495 PT->getPointeeType()->isObjCQualifiedIdType())
496 return true;
497 }
498 return false;
499 }
500 bool PointerTypeTakesAnyBlockArguments(QualType QT);
501 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
502 void GetExtentOfArgList(const char *Name, const char *&LParen,
503 const char *&RParen);
504
505 void QuoteDoublequotes(std::string &From, std::string &To) {
506 for (unsigned i = 0; i < From.length(); i++) {
507 if (From[i] == '"')
508 To += "\\\"";
509 else
510 To += From[i];
511 }
512 }
513
514 QualType getSimpleFunctionType(QualType result,
515 const QualType *args,
516 unsigned numArgs,
517 bool variadic = false) {
518 if (result == Context->getObjCInstanceType())
519 result = Context->getObjCIdType();
520 FunctionProtoType::ExtProtoInfo fpi;
521 fpi.Variadic = variadic;
522 return Context->getFunctionType(result, args, numArgs, fpi);
523 }
524
525 // Helper function: create a CStyleCastExpr with trivial type source info.
526 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
527 CastKind Kind, Expr *E) {
528 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
529 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
530 SourceLocation(), SourceLocation());
531 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000532
533 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
534 IdentifierInfo* II = &Context->Idents.get("load");
535 Selector LoadSel = Context->Selectors.getSelector(0, &II);
536 return OD->getClassMethod(LoadSel) != 0;
537 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000538 };
539
540}
541
542void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
543 NamedDecl *D) {
544 if (const FunctionProtoType *fproto
545 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
546 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
547 E = fproto->arg_type_end(); I && (I != E); ++I)
548 if (isTopLevelBlockPointerType(*I)) {
549 // All the args are checked/rewritten. Don't call twice!
550 RewriteBlockPointerDecl(D);
551 break;
552 }
553 }
554}
555
556void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
557 const PointerType *PT = funcType->getAs<PointerType>();
558 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
559 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
560}
561
562static bool IsHeaderFile(const std::string &Filename) {
563 std::string::size_type DotPos = Filename.rfind('.');
564
565 if (DotPos == std::string::npos) {
566 // no file extension
567 return false;
568 }
569
570 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
571 // C header: .h
572 // C++ header: .hh or .H;
573 return Ext == "h" || Ext == "hh" || Ext == "H";
574}
575
576RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
577 DiagnosticsEngine &D, const LangOptions &LOpts,
578 bool silenceMacroWarn)
579 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
580 SilenceRewriteMacroWarning(silenceMacroWarn) {
581 IsHeader = IsHeaderFile(inFile);
582 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
583 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000584 // FIXME. This should be an error. But if block is not called, it is OK. And it
585 // may break including some headers.
586 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
587 "rewriting block literal declared in global scope is not implemented");
588
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000589 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
590 DiagnosticsEngine::Warning,
591 "rewriter doesn't support user-specified control flow semantics "
592 "for @try/@finally (code may not execute properly)");
593}
594
595ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
596 raw_ostream* OS,
597 DiagnosticsEngine &Diags,
598 const LangOptions &LOpts,
599 bool SilenceRewriteMacroWarning) {
600 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
601}
602
603void RewriteModernObjC::InitializeCommon(ASTContext &context) {
604 Context = &context;
605 SM = &Context->getSourceManager();
606 TUDecl = Context->getTranslationUnitDecl();
607 MsgSendFunctionDecl = 0;
608 MsgSendSuperFunctionDecl = 0;
609 MsgSendStretFunctionDecl = 0;
610 MsgSendSuperStretFunctionDecl = 0;
611 MsgSendFpretFunctionDecl = 0;
612 GetClassFunctionDecl = 0;
613 GetMetaClassFunctionDecl = 0;
614 GetSuperClassFunctionDecl = 0;
615 SelGetUidFunctionDecl = 0;
616 CFStringFunctionDecl = 0;
617 ConstantStringClassReference = 0;
618 NSStringRecord = 0;
619 CurMethodDef = 0;
620 CurFunctionDef = 0;
621 CurFunctionDeclToDeclareForBlock = 0;
622 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000623 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000624 SuperStructDecl = 0;
625 ProtocolTypeDecl = 0;
626 ConstantStringDecl = 0;
627 BcLabelCount = 0;
628 SuperContructorFunctionDecl = 0;
629 NumObjCStringLiterals = 0;
630 PropParentMap = 0;
631 CurrentBody = 0;
632 DisableReplaceStmt = false;
633 objc_impl_method = false;
634
635 // Get the ID and start/end of the main file.
636 MainFileID = SM->getMainFileID();
637 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
638 MainFileStart = MainBuf->getBufferStart();
639 MainFileEnd = MainBuf->getBufferEnd();
640
David Blaikie4e4d0842012-03-11 07:00:24 +0000641 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000642}
643
644//===----------------------------------------------------------------------===//
645// Top Level Driver Code
646//===----------------------------------------------------------------------===//
647
648void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
649 if (Diags.hasErrorOccurred())
650 return;
651
652 // Two cases: either the decl could be in the main file, or it could be in a
653 // #included file. If the former, rewrite it now. If the later, check to see
654 // if we rewrote the #include/#import.
655 SourceLocation Loc = D->getLocation();
656 Loc = SM->getExpansionLoc(Loc);
657
658 // If this is for a builtin, ignore it.
659 if (Loc.isInvalid()) return;
660
661 // Look for built-in declarations that we need to refer during the rewrite.
662 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
663 RewriteFunctionDecl(FD);
664 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
665 // declared in <Foundation/NSString.h>
666 if (FVD->getName() == "_NSConstantStringClassReference") {
667 ConstantStringClassReference = FVD;
668 return;
669 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000670 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
671 RewriteCategoryDecl(CD);
672 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
673 if (PD->isThisDeclarationADefinition())
674 RewriteProtocolDecl(PD);
675 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000676 RewriteLinkageSpec(LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000677 // Recurse into linkage specifications
678 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
679 DIEnd = LSD->decls_end();
680 DI != DIEnd; ) {
681 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
682 if (!IFace->isThisDeclarationADefinition()) {
683 SmallVector<Decl *, 8> DG;
684 SourceLocation StartLoc = IFace->getLocStart();
685 do {
686 if (isa<ObjCInterfaceDecl>(*DI) &&
687 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
688 StartLoc == (*DI)->getLocStart())
689 DG.push_back(*DI);
690 else
691 break;
692
693 ++DI;
694 } while (DI != DIEnd);
695 RewriteForwardClassDecl(DG);
696 continue;
697 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000698 else {
699 // Keep track of all interface declarations seen.
700 ObjCInterfacesSeen.push_back(IFace);
701 ++DI;
702 continue;
703 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000704 }
705
706 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
707 if (!Proto->isThisDeclarationADefinition()) {
708 SmallVector<Decl *, 8> DG;
709 SourceLocation StartLoc = Proto->getLocStart();
710 do {
711 if (isa<ObjCProtocolDecl>(*DI) &&
712 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
713 StartLoc == (*DI)->getLocStart())
714 DG.push_back(*DI);
715 else
716 break;
717
718 ++DI;
719 } while (DI != DIEnd);
720 RewriteForwardProtocolDecl(DG);
721 continue;
722 }
723 }
724
725 HandleTopLevelSingleDecl(*DI);
726 ++DI;
727 }
728 }
729 // If we have a decl in the main file, see if we should rewrite it.
730 if (SM->isFromMainFile(Loc))
731 return HandleDeclInMainFile(D);
732}
733
734//===----------------------------------------------------------------------===//
735// Syntactic (non-AST) Rewriting Code
736//===----------------------------------------------------------------------===//
737
738void RewriteModernObjC::RewriteInclude() {
739 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
740 StringRef MainBuf = SM->getBufferData(MainFileID);
741 const char *MainBufStart = MainBuf.begin();
742 const char *MainBufEnd = MainBuf.end();
743 size_t ImportLen = strlen("import");
744
745 // Loop over the whole file, looking for includes.
746 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
747 if (*BufPtr == '#') {
748 if (++BufPtr == MainBufEnd)
749 return;
750 while (*BufPtr == ' ' || *BufPtr == '\t')
751 if (++BufPtr == MainBufEnd)
752 return;
753 if (!strncmp(BufPtr, "import", ImportLen)) {
754 // replace import with include
755 SourceLocation ImportLoc =
756 LocStart.getLocWithOffset(BufPtr-MainBufStart);
757 ReplaceText(ImportLoc, ImportLen, "include");
758 BufPtr += ImportLen;
759 }
760 }
761 }
762}
763
764static std::string getIvarAccessString(ObjCIvarDecl *OID) {
765 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
766 std::string S;
767 S = "((struct ";
768 S += ClassDecl->getIdentifier()->getName();
769 S += "_IMPL *)self)->";
770 S += OID->getName();
771 return S;
772}
773
774void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
775 ObjCImplementationDecl *IMD,
776 ObjCCategoryImplDecl *CID) {
777 static bool objcGetPropertyDefined = false;
778 static bool objcSetPropertyDefined = false;
779 SourceLocation startLoc = PID->getLocStart();
780 InsertText(startLoc, "// ");
781 const char *startBuf = SM->getCharacterData(startLoc);
782 assert((*startBuf == '@') && "bogus @synthesize location");
783 const char *semiBuf = strchr(startBuf, ';');
784 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
785 SourceLocation onePastSemiLoc =
786 startLoc.getLocWithOffset(semiBuf-startBuf+1);
787
788 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
789 return; // FIXME: is this correct?
790
791 // Generate the 'getter' function.
792 ObjCPropertyDecl *PD = PID->getPropertyDecl();
793 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
794
795 if (!OID)
796 return;
797 unsigned Attributes = PD->getPropertyAttributes();
798 if (!PD->getGetterMethodDecl()->isDefined()) {
799 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
800 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
801 ObjCPropertyDecl::OBJC_PR_copy));
802 std::string Getr;
803 if (GenGetProperty && !objcGetPropertyDefined) {
804 objcGetPropertyDefined = true;
805 // FIXME. Is this attribute correct in all cases?
806 Getr = "\nextern \"C\" __declspec(dllimport) "
807 "id objc_getProperty(id, SEL, long, bool);\n";
808 }
809 RewriteObjCMethodDecl(OID->getContainingInterface(),
810 PD->getGetterMethodDecl(), Getr);
811 Getr += "{ ";
812 // Synthesize an explicit cast to gain access to the ivar.
813 // See objc-act.c:objc_synthesize_new_getter() for details.
814 if (GenGetProperty) {
815 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
816 Getr += "typedef ";
817 const FunctionType *FPRetType = 0;
818 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
819 FPRetType);
820 Getr += " _TYPE";
821 if (FPRetType) {
822 Getr += ")"; // close the precedence "scope" for "*".
823
824 // Now, emit the argument types (if any).
825 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
826 Getr += "(";
827 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
828 if (i) Getr += ", ";
829 std::string ParamStr = FT->getArgType(i).getAsString(
830 Context->getPrintingPolicy());
831 Getr += ParamStr;
832 }
833 if (FT->isVariadic()) {
834 if (FT->getNumArgs()) Getr += ", ";
835 Getr += "...";
836 }
837 Getr += ")";
838 } else
839 Getr += "()";
840 }
841 Getr += ";\n";
842 Getr += "return (_TYPE)";
843 Getr += "objc_getProperty(self, _cmd, ";
844 RewriteIvarOffsetComputation(OID, Getr);
845 Getr += ", 1)";
846 }
847 else
848 Getr += "return " + getIvarAccessString(OID);
849 Getr += "; }";
850 InsertText(onePastSemiLoc, Getr);
851 }
852
853 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
854 return;
855
856 // Generate the 'setter' function.
857 std::string Setr;
858 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
859 ObjCPropertyDecl::OBJC_PR_copy);
860 if (GenSetProperty && !objcSetPropertyDefined) {
861 objcSetPropertyDefined = true;
862 // FIXME. Is this attribute correct in all cases?
863 Setr = "\nextern \"C\" __declspec(dllimport) "
864 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
865 }
866
867 RewriteObjCMethodDecl(OID->getContainingInterface(),
868 PD->getSetterMethodDecl(), Setr);
869 Setr += "{ ";
870 // Synthesize an explicit cast to initialize the ivar.
871 // See objc-act.c:objc_synthesize_new_setter() for details.
872 if (GenSetProperty) {
873 Setr += "objc_setProperty (self, _cmd, ";
874 RewriteIvarOffsetComputation(OID, Setr);
875 Setr += ", (id)";
876 Setr += PD->getName();
877 Setr += ", ";
878 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
879 Setr += "0, ";
880 else
881 Setr += "1, ";
882 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
883 Setr += "1)";
884 else
885 Setr += "0)";
886 }
887 else {
888 Setr += getIvarAccessString(OID) + " = ";
889 Setr += PD->getName();
890 }
891 Setr += "; }";
892 InsertText(onePastSemiLoc, Setr);
893}
894
895static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
896 std::string &typedefString) {
897 typedefString += "#ifndef _REWRITER_typedef_";
898 typedefString += ForwardDecl->getNameAsString();
899 typedefString += "\n";
900 typedefString += "#define _REWRITER_typedef_";
901 typedefString += ForwardDecl->getNameAsString();
902 typedefString += "\n";
903 typedefString += "typedef struct objc_object ";
904 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000905 // typedef struct { } _objc_exc_Classname;
906 typedefString += ";\ntypedef struct {} _objc_exc_";
907 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000908 typedefString += ";\n#endif\n";
909}
910
911void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
912 const std::string &typedefString) {
913 SourceLocation startLoc = ClassDecl->getLocStart();
914 const char *startBuf = SM->getCharacterData(startLoc);
915 const char *semiPtr = strchr(startBuf, ';');
916 // Replace the @class with typedefs corresponding to the classes.
917 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
918}
919
920void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
921 std::string typedefString;
922 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
923 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
924 if (I == D.begin()) {
925 // Translate to typedef's that forward reference structs with the same name
926 // as the class. As a convenience, we include the original declaration
927 // as a comment.
928 typedefString += "// @class ";
929 typedefString += ForwardDecl->getNameAsString();
930 typedefString += ";\n";
931 }
932 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
933 }
934 DeclGroupRef::iterator I = D.begin();
935 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
936}
937
938void RewriteModernObjC::RewriteForwardClassDecl(
939 const llvm::SmallVector<Decl*, 8> &D) {
940 std::string typedefString;
941 for (unsigned i = 0; i < D.size(); i++) {
942 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
943 if (i == 0) {
944 typedefString += "// @class ";
945 typedefString += ForwardDecl->getNameAsString();
946 typedefString += ";\n";
947 }
948 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
949 }
950 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
951}
952
953void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
954 // When method is a synthesized one, such as a getter/setter there is
955 // nothing to rewrite.
956 if (Method->isImplicit())
957 return;
958 SourceLocation LocStart = Method->getLocStart();
959 SourceLocation LocEnd = Method->getLocEnd();
960
961 if (SM->getExpansionLineNumber(LocEnd) >
962 SM->getExpansionLineNumber(LocStart)) {
963 InsertText(LocStart, "#if 0\n");
964 ReplaceText(LocEnd, 1, ";\n#endif\n");
965 } else {
966 InsertText(LocStart, "// ");
967 }
968}
969
970void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
971 SourceLocation Loc = prop->getAtLoc();
972
973 ReplaceText(Loc, 0, "// ");
974 // FIXME: handle properties that are declared across multiple lines.
975}
976
977void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
978 SourceLocation LocStart = CatDecl->getLocStart();
979
980 // FIXME: handle category headers that are declared across multiple lines.
981 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000982 if (CatDecl->getIvarLBraceLoc().isValid())
983 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000984 for (ObjCCategoryDecl::ivar_iterator
985 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
986 ObjCIvarDecl *Ivar = (*I);
987 SourceLocation LocStart = Ivar->getLocStart();
988 ReplaceText(LocStart, 0, "// ");
989 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000990 if (CatDecl->getIvarRBraceLoc().isValid())
991 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
992
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000993 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
994 E = CatDecl->prop_end(); I != E; ++I)
995 RewriteProperty(*I);
996
997 for (ObjCCategoryDecl::instmeth_iterator
998 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
999 I != E; ++I)
1000 RewriteMethodDeclaration(*I);
1001 for (ObjCCategoryDecl::classmeth_iterator
1002 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1003 I != E; ++I)
1004 RewriteMethodDeclaration(*I);
1005
1006 // Lastly, comment out the @end.
1007 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1008 strlen("@end"), "/* @end */");
1009}
1010
1011void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1012 SourceLocation LocStart = PDecl->getLocStart();
1013 assert(PDecl->isThisDeclarationADefinition());
1014
1015 // FIXME: handle protocol headers that are declared across multiple lines.
1016 ReplaceText(LocStart, 0, "// ");
1017
1018 for (ObjCProtocolDecl::instmeth_iterator
1019 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1020 I != E; ++I)
1021 RewriteMethodDeclaration(*I);
1022 for (ObjCProtocolDecl::classmeth_iterator
1023 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1024 I != E; ++I)
1025 RewriteMethodDeclaration(*I);
1026
1027 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1028 E = PDecl->prop_end(); I != E; ++I)
1029 RewriteProperty(*I);
1030
1031 // Lastly, comment out the @end.
1032 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1033 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1034
1035 // Must comment out @optional/@required
1036 const char *startBuf = SM->getCharacterData(LocStart);
1037 const char *endBuf = SM->getCharacterData(LocEnd);
1038 for (const char *p = startBuf; p < endBuf; p++) {
1039 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1040 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1041 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1042
1043 }
1044 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1045 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1046 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1047
1048 }
1049 }
1050}
1051
1052void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1053 SourceLocation LocStart = (*D.begin())->getLocStart();
1054 if (LocStart.isInvalid())
1055 llvm_unreachable("Invalid SourceLocation");
1056 // FIXME: handle forward protocol that are declared across multiple lines.
1057 ReplaceText(LocStart, 0, "// ");
1058}
1059
1060void
1061RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1062 SourceLocation LocStart = DG[0]->getLocStart();
1063 if (LocStart.isInvalid())
1064 llvm_unreachable("Invalid SourceLocation");
1065 // FIXME: handle forward protocol that are declared across multiple lines.
1066 ReplaceText(LocStart, 0, "// ");
1067}
1068
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001069void
1070RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1071 SourceLocation LocStart = LSD->getExternLoc();
1072 if (LocStart.isInvalid())
1073 llvm_unreachable("Invalid extern SourceLocation");
1074
1075 ReplaceText(LocStart, 0, "// ");
1076 if (!LSD->hasBraces())
1077 return;
1078 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1079 SourceLocation LocRBrace = LSD->getRBraceLoc();
1080 if (LocRBrace.isInvalid())
1081 llvm_unreachable("Invalid rbrace SourceLocation");
1082 ReplaceText(LocRBrace, 0, "// ");
1083}
1084
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001085void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1086 const FunctionType *&FPRetType) {
1087 if (T->isObjCQualifiedIdType())
1088 ResultStr += "id";
1089 else if (T->isFunctionPointerType() ||
1090 T->isBlockPointerType()) {
1091 // needs special handling, since pointer-to-functions have special
1092 // syntax (where a decaration models use).
1093 QualType retType = T;
1094 QualType PointeeTy;
1095 if (const PointerType* PT = retType->getAs<PointerType>())
1096 PointeeTy = PT->getPointeeType();
1097 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1098 PointeeTy = BPT->getPointeeType();
1099 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1100 ResultStr += FPRetType->getResultType().getAsString(
1101 Context->getPrintingPolicy());
1102 ResultStr += "(*";
1103 }
1104 } else
1105 ResultStr += T.getAsString(Context->getPrintingPolicy());
1106}
1107
1108void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1109 ObjCMethodDecl *OMD,
1110 std::string &ResultStr) {
1111 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1112 const FunctionType *FPRetType = 0;
1113 ResultStr += "\nstatic ";
1114 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1115 ResultStr += " ";
1116
1117 // Unique method name
1118 std::string NameStr;
1119
1120 if (OMD->isInstanceMethod())
1121 NameStr += "_I_";
1122 else
1123 NameStr += "_C_";
1124
1125 NameStr += IDecl->getNameAsString();
1126 NameStr += "_";
1127
1128 if (ObjCCategoryImplDecl *CID =
1129 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1130 NameStr += CID->getNameAsString();
1131 NameStr += "_";
1132 }
1133 // Append selector names, replacing ':' with '_'
1134 {
1135 std::string selString = OMD->getSelector().getAsString();
1136 int len = selString.size();
1137 for (int i = 0; i < len; i++)
1138 if (selString[i] == ':')
1139 selString[i] = '_';
1140 NameStr += selString;
1141 }
1142 // Remember this name for metadata emission
1143 MethodInternalNames[OMD] = NameStr;
1144 ResultStr += NameStr;
1145
1146 // Rewrite arguments
1147 ResultStr += "(";
1148
1149 // invisible arguments
1150 if (OMD->isInstanceMethod()) {
1151 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1152 selfTy = Context->getPointerType(selfTy);
1153 if (!LangOpts.MicrosoftExt) {
1154 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1155 ResultStr += "struct ";
1156 }
1157 // When rewriting for Microsoft, explicitly omit the structure name.
1158 ResultStr += IDecl->getNameAsString();
1159 ResultStr += " *";
1160 }
1161 else
1162 ResultStr += Context->getObjCClassType().getAsString(
1163 Context->getPrintingPolicy());
1164
1165 ResultStr += " self, ";
1166 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1167 ResultStr += " _cmd";
1168
1169 // Method arguments.
1170 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1171 E = OMD->param_end(); PI != E; ++PI) {
1172 ParmVarDecl *PDecl = *PI;
1173 ResultStr += ", ";
1174 if (PDecl->getType()->isObjCQualifiedIdType()) {
1175 ResultStr += "id ";
1176 ResultStr += PDecl->getNameAsString();
1177 } else {
1178 std::string Name = PDecl->getNameAsString();
1179 QualType QT = PDecl->getType();
1180 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001181 (void)convertBlockPointerToFunctionPointer(QT);
1182 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001183 ResultStr += Name;
1184 }
1185 }
1186 if (OMD->isVariadic())
1187 ResultStr += ", ...";
1188 ResultStr += ") ";
1189
1190 if (FPRetType) {
1191 ResultStr += ")"; // close the precedence "scope" for "*".
1192
1193 // Now, emit the argument types (if any).
1194 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1195 ResultStr += "(";
1196 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1197 if (i) ResultStr += ", ";
1198 std::string ParamStr = FT->getArgType(i).getAsString(
1199 Context->getPrintingPolicy());
1200 ResultStr += ParamStr;
1201 }
1202 if (FT->isVariadic()) {
1203 if (FT->getNumArgs()) ResultStr += ", ";
1204 ResultStr += "...";
1205 }
1206 ResultStr += ")";
1207 } else {
1208 ResultStr += "()";
1209 }
1210 }
1211}
1212void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1213 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1214 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1215
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001216 if (IMD) {
1217 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001218 if (IMD->getIvarLBraceLoc().isValid())
1219 InsertText(IMD->getIvarLBraceLoc(), "// ");
1220 for (ObjCImplementationDecl::ivar_iterator
1221 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1222 ObjCIvarDecl *Ivar = (*I);
1223 SourceLocation LocStart = Ivar->getLocStart();
1224 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001225 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001226 if (IMD->getIvarRBraceLoc().isValid())
1227 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001228 }
1229 else
1230 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001231
1232 for (ObjCCategoryImplDecl::instmeth_iterator
1233 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1234 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1235 I != E; ++I) {
1236 std::string ResultStr;
1237 ObjCMethodDecl *OMD = *I;
1238 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1239 SourceLocation LocStart = OMD->getLocStart();
1240 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1241
1242 const char *startBuf = SM->getCharacterData(LocStart);
1243 const char *endBuf = SM->getCharacterData(LocEnd);
1244 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1245 }
1246
1247 for (ObjCCategoryImplDecl::classmeth_iterator
1248 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1249 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1250 I != E; ++I) {
1251 std::string ResultStr;
1252 ObjCMethodDecl *OMD = *I;
1253 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1254 SourceLocation LocStart = OMD->getLocStart();
1255 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1256
1257 const char *startBuf = SM->getCharacterData(LocStart);
1258 const char *endBuf = SM->getCharacterData(LocEnd);
1259 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1260 }
1261 for (ObjCCategoryImplDecl::propimpl_iterator
1262 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1263 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1264 I != E; ++I) {
1265 RewritePropertyImplDecl(*I, IMD, CID);
1266 }
1267
1268 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1269}
1270
1271void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001272 // Do not synthesize more than once.
1273 if (ObjCSynthesizedStructs.count(ClassDecl))
1274 return;
1275 // Make sure super class's are written before current class is written.
1276 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1277 while (SuperClass) {
1278 RewriteInterfaceDecl(SuperClass);
1279 SuperClass = SuperClass->getSuperClass();
1280 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001281 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001282 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001283 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001284 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001285 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1286
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001287 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001288 // Mark this typedef as having been written into its c++ equivalent.
1289 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001290
1291 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001292 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001293 RewriteProperty(*I);
1294 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001295 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001296 I != E; ++I)
1297 RewriteMethodDeclaration(*I);
1298 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001299 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001300 I != E; ++I)
1301 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001302
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001303 // Lastly, comment out the @end.
1304 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1305 "/* @end */");
1306 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001307}
1308
1309Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1310 SourceRange OldRange = PseudoOp->getSourceRange();
1311
1312 // We just magically know some things about the structure of this
1313 // expression.
1314 ObjCMessageExpr *OldMsg =
1315 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1316 PseudoOp->getNumSemanticExprs() - 1));
1317
1318 // Because the rewriter doesn't allow us to rewrite rewritten code,
1319 // we need to suppress rewriting the sub-statements.
1320 Expr *Base, *RHS;
1321 {
1322 DisableReplaceStmtScope S(*this);
1323
1324 // Rebuild the base expression if we have one.
1325 Base = 0;
1326 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1327 Base = OldMsg->getInstanceReceiver();
1328 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1329 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1330 }
1331
1332 // Rebuild the RHS.
1333 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1334 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1335 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1336 }
1337
1338 // TODO: avoid this copy.
1339 SmallVector<SourceLocation, 1> SelLocs;
1340 OldMsg->getSelectorLocs(SelLocs);
1341
1342 ObjCMessageExpr *NewMsg = 0;
1343 switch (OldMsg->getReceiverKind()) {
1344 case ObjCMessageExpr::Class:
1345 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1346 OldMsg->getValueKind(),
1347 OldMsg->getLeftLoc(),
1348 OldMsg->getClassReceiverTypeInfo(),
1349 OldMsg->getSelector(),
1350 SelLocs,
1351 OldMsg->getMethodDecl(),
1352 RHS,
1353 OldMsg->getRightLoc(),
1354 OldMsg->isImplicit());
1355 break;
1356
1357 case ObjCMessageExpr::Instance:
1358 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1359 OldMsg->getValueKind(),
1360 OldMsg->getLeftLoc(),
1361 Base,
1362 OldMsg->getSelector(),
1363 SelLocs,
1364 OldMsg->getMethodDecl(),
1365 RHS,
1366 OldMsg->getRightLoc(),
1367 OldMsg->isImplicit());
1368 break;
1369
1370 case ObjCMessageExpr::SuperClass:
1371 case ObjCMessageExpr::SuperInstance:
1372 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1373 OldMsg->getValueKind(),
1374 OldMsg->getLeftLoc(),
1375 OldMsg->getSuperLoc(),
1376 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1377 OldMsg->getSuperType(),
1378 OldMsg->getSelector(),
1379 SelLocs,
1380 OldMsg->getMethodDecl(),
1381 RHS,
1382 OldMsg->getRightLoc(),
1383 OldMsg->isImplicit());
1384 break;
1385 }
1386
1387 Stmt *Replacement = SynthMessageExpr(NewMsg);
1388 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1389 return Replacement;
1390}
1391
1392Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1393 SourceRange OldRange = PseudoOp->getSourceRange();
1394
1395 // We just magically know some things about the structure of this
1396 // expression.
1397 ObjCMessageExpr *OldMsg =
1398 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1399
1400 // Because the rewriter doesn't allow us to rewrite rewritten code,
1401 // we need to suppress rewriting the sub-statements.
1402 Expr *Base = 0;
1403 {
1404 DisableReplaceStmtScope S(*this);
1405
1406 // Rebuild the base expression if we have one.
1407 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1408 Base = OldMsg->getInstanceReceiver();
1409 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1410 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1411 }
1412 }
1413
1414 // Intentionally empty.
1415 SmallVector<SourceLocation, 1> SelLocs;
1416 SmallVector<Expr*, 1> Args;
1417
1418 ObjCMessageExpr *NewMsg = 0;
1419 switch (OldMsg->getReceiverKind()) {
1420 case ObjCMessageExpr::Class:
1421 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1422 OldMsg->getValueKind(),
1423 OldMsg->getLeftLoc(),
1424 OldMsg->getClassReceiverTypeInfo(),
1425 OldMsg->getSelector(),
1426 SelLocs,
1427 OldMsg->getMethodDecl(),
1428 Args,
1429 OldMsg->getRightLoc(),
1430 OldMsg->isImplicit());
1431 break;
1432
1433 case ObjCMessageExpr::Instance:
1434 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1435 OldMsg->getValueKind(),
1436 OldMsg->getLeftLoc(),
1437 Base,
1438 OldMsg->getSelector(),
1439 SelLocs,
1440 OldMsg->getMethodDecl(),
1441 Args,
1442 OldMsg->getRightLoc(),
1443 OldMsg->isImplicit());
1444 break;
1445
1446 case ObjCMessageExpr::SuperClass:
1447 case ObjCMessageExpr::SuperInstance:
1448 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1449 OldMsg->getValueKind(),
1450 OldMsg->getLeftLoc(),
1451 OldMsg->getSuperLoc(),
1452 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1453 OldMsg->getSuperType(),
1454 OldMsg->getSelector(),
1455 SelLocs,
1456 OldMsg->getMethodDecl(),
1457 Args,
1458 OldMsg->getRightLoc(),
1459 OldMsg->isImplicit());
1460 break;
1461 }
1462
1463 Stmt *Replacement = SynthMessageExpr(NewMsg);
1464 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1465 return Replacement;
1466}
1467
1468/// SynthCountByEnumWithState - To print:
1469/// ((unsigned int (*)
1470/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1471/// (void *)objc_msgSend)((id)l_collection,
1472/// sel_registerName(
1473/// "countByEnumeratingWithState:objects:count:"),
1474/// &enumState,
1475/// (id *)__rw_items, (unsigned int)16)
1476///
1477void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1478 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1479 "id *, unsigned int))(void *)objc_msgSend)";
1480 buf += "\n\t\t";
1481 buf += "((id)l_collection,\n\t\t";
1482 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1483 buf += "\n\t\t";
1484 buf += "&enumState, "
1485 "(id *)__rw_items, (unsigned int)16)";
1486}
1487
1488/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1489/// statement to exit to its outer synthesized loop.
1490///
1491Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1492 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1493 return S;
1494 // replace break with goto __break_label
1495 std::string buf;
1496
1497 SourceLocation startLoc = S->getLocStart();
1498 buf = "goto __break_label_";
1499 buf += utostr(ObjCBcLabelNo.back());
1500 ReplaceText(startLoc, strlen("break"), buf);
1501
1502 return 0;
1503}
1504
1505/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1506/// statement to continue with its inner synthesized loop.
1507///
1508Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1509 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1510 return S;
1511 // replace continue with goto __continue_label
1512 std::string buf;
1513
1514 SourceLocation startLoc = S->getLocStart();
1515 buf = "goto __continue_label_";
1516 buf += utostr(ObjCBcLabelNo.back());
1517 ReplaceText(startLoc, strlen("continue"), buf);
1518
1519 return 0;
1520}
1521
1522/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1523/// It rewrites:
1524/// for ( type elem in collection) { stmts; }
1525
1526/// Into:
1527/// {
1528/// type elem;
1529/// struct __objcFastEnumerationState enumState = { 0 };
1530/// id __rw_items[16];
1531/// id l_collection = (id)collection;
1532/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1533/// objects:__rw_items count:16];
1534/// if (limit) {
1535/// unsigned long startMutations = *enumState.mutationsPtr;
1536/// do {
1537/// unsigned long counter = 0;
1538/// do {
1539/// if (startMutations != *enumState.mutationsPtr)
1540/// objc_enumerationMutation(l_collection);
1541/// elem = (type)enumState.itemsPtr[counter++];
1542/// stmts;
1543/// __continue_label: ;
1544/// } while (counter < limit);
1545/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1546/// objects:__rw_items count:16]);
1547/// elem = nil;
1548/// __break_label: ;
1549/// }
1550/// else
1551/// elem = nil;
1552/// }
1553///
1554Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1555 SourceLocation OrigEnd) {
1556 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1557 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1558 "ObjCForCollectionStmt Statement stack mismatch");
1559 assert(!ObjCBcLabelNo.empty() &&
1560 "ObjCForCollectionStmt - Label No stack empty");
1561
1562 SourceLocation startLoc = S->getLocStart();
1563 const char *startBuf = SM->getCharacterData(startLoc);
1564 StringRef elementName;
1565 std::string elementTypeAsString;
1566 std::string buf;
1567 buf = "\n{\n\t";
1568 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1569 // type elem;
1570 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1571 QualType ElementType = cast<ValueDecl>(D)->getType();
1572 if (ElementType->isObjCQualifiedIdType() ||
1573 ElementType->isObjCQualifiedInterfaceType())
1574 // Simply use 'id' for all qualified types.
1575 elementTypeAsString = "id";
1576 else
1577 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1578 buf += elementTypeAsString;
1579 buf += " ";
1580 elementName = D->getName();
1581 buf += elementName;
1582 buf += ";\n\t";
1583 }
1584 else {
1585 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1586 elementName = DR->getDecl()->getName();
1587 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1588 if (VD->getType()->isObjCQualifiedIdType() ||
1589 VD->getType()->isObjCQualifiedInterfaceType())
1590 // Simply use 'id' for all qualified types.
1591 elementTypeAsString = "id";
1592 else
1593 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1594 }
1595
1596 // struct __objcFastEnumerationState enumState = { 0 };
1597 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1598 // id __rw_items[16];
1599 buf += "id __rw_items[16];\n\t";
1600 // id l_collection = (id)
1601 buf += "id l_collection = (id)";
1602 // Find start location of 'collection' the hard way!
1603 const char *startCollectionBuf = startBuf;
1604 startCollectionBuf += 3; // skip 'for'
1605 startCollectionBuf = strchr(startCollectionBuf, '(');
1606 startCollectionBuf++; // skip '('
1607 // find 'in' and skip it.
1608 while (*startCollectionBuf != ' ' ||
1609 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1610 (*(startCollectionBuf+3) != ' ' &&
1611 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1612 startCollectionBuf++;
1613 startCollectionBuf += 3;
1614
1615 // Replace: "for (type element in" with string constructed thus far.
1616 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1617 // Replace ')' in for '(' type elem in collection ')' with ';'
1618 SourceLocation rightParenLoc = S->getRParenLoc();
1619 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1620 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1621 buf = ";\n\t";
1622
1623 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1624 // objects:__rw_items count:16];
1625 // which is synthesized into:
1626 // unsigned int limit =
1627 // ((unsigned int (*)
1628 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1629 // (void *)objc_msgSend)((id)l_collection,
1630 // sel_registerName(
1631 // "countByEnumeratingWithState:objects:count:"),
1632 // (struct __objcFastEnumerationState *)&state,
1633 // (id *)__rw_items, (unsigned int)16);
1634 buf += "unsigned long limit =\n\t\t";
1635 SynthCountByEnumWithState(buf);
1636 buf += ";\n\t";
1637 /// if (limit) {
1638 /// unsigned long startMutations = *enumState.mutationsPtr;
1639 /// do {
1640 /// unsigned long counter = 0;
1641 /// do {
1642 /// if (startMutations != *enumState.mutationsPtr)
1643 /// objc_enumerationMutation(l_collection);
1644 /// elem = (type)enumState.itemsPtr[counter++];
1645 buf += "if (limit) {\n\t";
1646 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1647 buf += "do {\n\t\t";
1648 buf += "unsigned long counter = 0;\n\t\t";
1649 buf += "do {\n\t\t\t";
1650 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1651 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1652 buf += elementName;
1653 buf += " = (";
1654 buf += elementTypeAsString;
1655 buf += ")enumState.itemsPtr[counter++];";
1656 // Replace ')' in for '(' type elem in collection ')' with all of these.
1657 ReplaceText(lparenLoc, 1, buf);
1658
1659 /// __continue_label: ;
1660 /// } while (counter < limit);
1661 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1662 /// objects:__rw_items count:16]);
1663 /// elem = nil;
1664 /// __break_label: ;
1665 /// }
1666 /// else
1667 /// elem = nil;
1668 /// }
1669 ///
1670 buf = ";\n\t";
1671 buf += "__continue_label_";
1672 buf += utostr(ObjCBcLabelNo.back());
1673 buf += ": ;";
1674 buf += "\n\t\t";
1675 buf += "} while (counter < limit);\n\t";
1676 buf += "} while (limit = ";
1677 SynthCountByEnumWithState(buf);
1678 buf += ");\n\t";
1679 buf += elementName;
1680 buf += " = ((";
1681 buf += elementTypeAsString;
1682 buf += ")0);\n\t";
1683 buf += "__break_label_";
1684 buf += utostr(ObjCBcLabelNo.back());
1685 buf += ": ;\n\t";
1686 buf += "}\n\t";
1687 buf += "else\n\t\t";
1688 buf += elementName;
1689 buf += " = ((";
1690 buf += elementTypeAsString;
1691 buf += ")0);\n\t";
1692 buf += "}\n";
1693
1694 // Insert all these *after* the statement body.
1695 // FIXME: If this should support Obj-C++, support CXXTryStmt
1696 if (isa<CompoundStmt>(S->getBody())) {
1697 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1698 InsertText(endBodyLoc, buf);
1699 } else {
1700 /* Need to treat single statements specially. For example:
1701 *
1702 * for (A *a in b) if (stuff()) break;
1703 * for (A *a in b) xxxyy;
1704 *
1705 * The following code simply scans ahead to the semi to find the actual end.
1706 */
1707 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1708 const char *semiBuf = strchr(stmtBuf, ';');
1709 assert(semiBuf && "Can't find ';'");
1710 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1711 InsertText(endBodyLoc, buf);
1712 }
1713 Stmts.pop_back();
1714 ObjCBcLabelNo.pop_back();
1715 return 0;
1716}
1717
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001718static void Write_RethrowObject(std::string &buf) {
1719 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1720 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1721 buf += "\tid rethrow;\n";
1722 buf += "\t} _fin_force_rethow(_rethrow);";
1723}
1724
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001725/// RewriteObjCSynchronizedStmt -
1726/// This routine rewrites @synchronized(expr) stmt;
1727/// into:
1728/// objc_sync_enter(expr);
1729/// @try stmt @finally { objc_sync_exit(expr); }
1730///
1731Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1732 // Get the start location and compute the semi location.
1733 SourceLocation startLoc = S->getLocStart();
1734 const char *startBuf = SM->getCharacterData(startLoc);
1735
1736 assert((*startBuf == '@') && "bogus @synchronized location");
1737
1738 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001739 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001740
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001741 const char *lparenBuf = startBuf;
1742 while (*lparenBuf != '(') lparenBuf++;
1743 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001744
1745 buf = "; objc_sync_enter(_sync_obj);\n";
1746 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1747 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1748 buf += "\n\tid sync_exit;";
1749 buf += "\n\t} _sync_exit(_sync_obj);\n";
1750
1751 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1752 // the sync expression is typically a message expression that's already
1753 // been rewritten! (which implies the SourceLocation's are invalid).
1754 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1755 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1756 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1757 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1758
1759 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1760 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1761 assert (*LBraceLocBuf == '{');
1762 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001763
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001764 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001765 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1766 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001767
1768 buf = "} catch (id e) {_rethrow = e;}\n";
1769 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001770 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001771 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001772
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001773 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001774
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001775 return 0;
1776}
1777
1778void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1779{
1780 // Perform a bottom up traversal of all children.
1781 for (Stmt::child_range CI = S->children(); CI; ++CI)
1782 if (*CI)
1783 WarnAboutReturnGotoStmts(*CI);
1784
1785 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1786 Diags.Report(Context->getFullLoc(S->getLocStart()),
1787 TryFinallyContainsReturnDiag);
1788 }
1789 return;
1790}
1791
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001792Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001793 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001794 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001795 std::string buf;
1796
1797 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001798 if (noCatch)
1799 buf = "{ id volatile _rethrow = 0;\n";
1800 else {
1801 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1802 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001803 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001804 // Get the start location and compute the semi location.
1805 SourceLocation startLoc = S->getLocStart();
1806 const char *startBuf = SM->getCharacterData(startLoc);
1807
1808 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001809 if (finalStmt)
1810 ReplaceText(startLoc, 1, buf);
1811 else
1812 // @try -> try
1813 ReplaceText(startLoc, 1, "");
1814
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001815 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1816 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001817 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001818
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001819 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001820 bool AtRemoved = false;
1821 if (catchDecl) {
1822 QualType t = catchDecl->getType();
1823 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1824 // Should be a pointer to a class.
1825 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1826 if (IDecl) {
1827 std::string Result;
1828 startBuf = SM->getCharacterData(startLoc);
1829 assert((*startBuf == '@') && "bogus @catch location");
1830 SourceLocation rParenLoc = Catch->getRParenLoc();
1831 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1832
1833 // _objc_exc_Foo *_e as argument to catch.
1834 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1835 Result += " *_"; Result += catchDecl->getNameAsString();
1836 Result += ")";
1837 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1838 // Foo *e = (Foo *)_e;
1839 Result.clear();
1840 Result = "{ ";
1841 Result += IDecl->getNameAsString();
1842 Result += " *"; Result += catchDecl->getNameAsString();
1843 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1844 Result += "_"; Result += catchDecl->getNameAsString();
1845
1846 Result += "; ";
1847 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1848 ReplaceText(lBraceLoc, 1, Result);
1849 AtRemoved = true;
1850 }
1851 }
1852 }
1853 if (!AtRemoved)
1854 // @catch -> catch
1855 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001856
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001857 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001858 if (finalStmt) {
1859 buf.clear();
1860 if (noCatch)
1861 buf = "catch (id e) {_rethrow = e;}\n";
1862 else
1863 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1864
1865 SourceLocation startFinalLoc = finalStmt->getLocStart();
1866 ReplaceText(startFinalLoc, 8, buf);
1867 Stmt *body = finalStmt->getFinallyBody();
1868 SourceLocation startFinalBodyLoc = body->getLocStart();
1869 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001870 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001871 ReplaceText(startFinalBodyLoc, 1, buf);
1872
1873 SourceLocation endFinalBodyLoc = body->getLocEnd();
1874 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001875 // Now check for any return/continue/go statements within the @try.
1876 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001877 }
1878
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001879 return 0;
1880}
1881
1882// This can't be done with ReplaceStmt(S, ThrowExpr), since
1883// the throw expression is typically a message expression that's already
1884// been rewritten! (which implies the SourceLocation's are invalid).
1885Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1886 // Get the start location and compute the semi location.
1887 SourceLocation startLoc = S->getLocStart();
1888 const char *startBuf = SM->getCharacterData(startLoc);
1889
1890 assert((*startBuf == '@') && "bogus @throw location");
1891
1892 std::string buf;
1893 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1894 if (S->getThrowExpr())
1895 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001896 else
1897 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001898
1899 // handle "@ throw" correctly.
1900 const char *wBuf = strchr(startBuf, 'w');
1901 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1902 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1903
1904 const char *semiBuf = strchr(startBuf, ';');
1905 assert((*semiBuf == ';') && "@throw: can't find ';'");
1906 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001907 if (S->getThrowExpr())
1908 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001909 return 0;
1910}
1911
1912Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1913 // Create a new string expression.
1914 QualType StrType = Context->getPointerType(Context->CharTy);
1915 std::string StrEncoding;
1916 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1917 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1918 StringLiteral::Ascii, false,
1919 StrType, SourceLocation());
1920 ReplaceStmt(Exp, Replacement);
1921
1922 // Replace this subexpr in the parent.
1923 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1924 return Replacement;
1925}
1926
1927Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1928 if (!SelGetUidFunctionDecl)
1929 SynthSelGetUidFunctionDecl();
1930 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1931 // Create a call to sel_registerName("selName").
1932 SmallVector<Expr*, 8> SelExprs;
1933 QualType argType = Context->getPointerType(Context->CharTy);
1934 SelExprs.push_back(StringLiteral::Create(*Context,
1935 Exp->getSelector().getAsString(),
1936 StringLiteral::Ascii, false,
1937 argType, SourceLocation()));
1938 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1939 &SelExprs[0], SelExprs.size());
1940 ReplaceStmt(Exp, SelExp);
1941 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1942 return SelExp;
1943}
1944
1945CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1946 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1947 SourceLocation EndLoc) {
1948 // Get the type, we will need to reference it in a couple spots.
1949 QualType msgSendType = FD->getType();
1950
1951 // Create a reference to the objc_msgSend() declaration.
1952 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001953 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001954
1955 // Now, we cast the reference to a pointer to the objc_msgSend type.
1956 QualType pToFunc = Context->getPointerType(msgSendType);
1957 ImplicitCastExpr *ICE =
1958 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1959 DRE, 0, VK_RValue);
1960
1961 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1962
1963 CallExpr *Exp =
1964 new (Context) CallExpr(*Context, ICE, args, nargs,
1965 FT->getCallResultType(*Context),
1966 VK_RValue, EndLoc);
1967 return Exp;
1968}
1969
1970static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1971 const char *&startRef, const char *&endRef) {
1972 while (startBuf < endBuf) {
1973 if (*startBuf == '<')
1974 startRef = startBuf; // mark the start.
1975 if (*startBuf == '>') {
1976 if (startRef && *startRef == '<') {
1977 endRef = startBuf; // mark the end.
1978 return true;
1979 }
1980 return false;
1981 }
1982 startBuf++;
1983 }
1984 return false;
1985}
1986
1987static void scanToNextArgument(const char *&argRef) {
1988 int angle = 0;
1989 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1990 if (*argRef == '<')
1991 angle++;
1992 else if (*argRef == '>')
1993 angle--;
1994 argRef++;
1995 }
1996 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1997}
1998
1999bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2000 if (T->isObjCQualifiedIdType())
2001 return true;
2002 if (const PointerType *PT = T->getAs<PointerType>()) {
2003 if (PT->getPointeeType()->isObjCQualifiedIdType())
2004 return true;
2005 }
2006 if (T->isObjCObjectPointerType()) {
2007 T = T->getPointeeType();
2008 return T->isObjCQualifiedInterfaceType();
2009 }
2010 if (T->isArrayType()) {
2011 QualType ElemTy = Context->getBaseElementType(T);
2012 return needToScanForQualifiers(ElemTy);
2013 }
2014 return false;
2015}
2016
2017void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2018 QualType Type = E->getType();
2019 if (needToScanForQualifiers(Type)) {
2020 SourceLocation Loc, EndLoc;
2021
2022 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2023 Loc = ECE->getLParenLoc();
2024 EndLoc = ECE->getRParenLoc();
2025 } else {
2026 Loc = E->getLocStart();
2027 EndLoc = E->getLocEnd();
2028 }
2029 // This will defend against trying to rewrite synthesized expressions.
2030 if (Loc.isInvalid() || EndLoc.isInvalid())
2031 return;
2032
2033 const char *startBuf = SM->getCharacterData(Loc);
2034 const char *endBuf = SM->getCharacterData(EndLoc);
2035 const char *startRef = 0, *endRef = 0;
2036 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2037 // Get the locations of the startRef, endRef.
2038 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2039 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2040 // Comment out the protocol references.
2041 InsertText(LessLoc, "/*");
2042 InsertText(GreaterLoc, "*/");
2043 }
2044 }
2045}
2046
2047void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2048 SourceLocation Loc;
2049 QualType Type;
2050 const FunctionProtoType *proto = 0;
2051 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2052 Loc = VD->getLocation();
2053 Type = VD->getType();
2054 }
2055 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2056 Loc = FD->getLocation();
2057 // Check for ObjC 'id' and class types that have been adorned with protocol
2058 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2059 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2060 assert(funcType && "missing function type");
2061 proto = dyn_cast<FunctionProtoType>(funcType);
2062 if (!proto)
2063 return;
2064 Type = proto->getResultType();
2065 }
2066 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2067 Loc = FD->getLocation();
2068 Type = FD->getType();
2069 }
2070 else
2071 return;
2072
2073 if (needToScanForQualifiers(Type)) {
2074 // Since types are unique, we need to scan the buffer.
2075
2076 const char *endBuf = SM->getCharacterData(Loc);
2077 const char *startBuf = endBuf;
2078 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2079 startBuf--; // scan backward (from the decl location) for return type.
2080 const char *startRef = 0, *endRef = 0;
2081 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2082 // Get the locations of the startRef, endRef.
2083 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2084 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2085 // Comment out the protocol references.
2086 InsertText(LessLoc, "/*");
2087 InsertText(GreaterLoc, "*/");
2088 }
2089 }
2090 if (!proto)
2091 return; // most likely, was a variable
2092 // Now check arguments.
2093 const char *startBuf = SM->getCharacterData(Loc);
2094 const char *startFuncBuf = startBuf;
2095 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2096 if (needToScanForQualifiers(proto->getArgType(i))) {
2097 // Since types are unique, we need to scan the buffer.
2098
2099 const char *endBuf = startBuf;
2100 // scan forward (from the decl location) for argument types.
2101 scanToNextArgument(endBuf);
2102 const char *startRef = 0, *endRef = 0;
2103 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2104 // Get the locations of the startRef, endRef.
2105 SourceLocation LessLoc =
2106 Loc.getLocWithOffset(startRef-startFuncBuf);
2107 SourceLocation GreaterLoc =
2108 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2109 // Comment out the protocol references.
2110 InsertText(LessLoc, "/*");
2111 InsertText(GreaterLoc, "*/");
2112 }
2113 startBuf = ++endBuf;
2114 }
2115 else {
2116 // If the function name is derived from a macro expansion, then the
2117 // argument buffer will not follow the name. Need to speak with Chris.
2118 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2119 startBuf++; // scan forward (from the decl location) for argument types.
2120 startBuf++;
2121 }
2122 }
2123}
2124
2125void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2126 QualType QT = ND->getType();
2127 const Type* TypePtr = QT->getAs<Type>();
2128 if (!isa<TypeOfExprType>(TypePtr))
2129 return;
2130 while (isa<TypeOfExprType>(TypePtr)) {
2131 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2132 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2133 TypePtr = QT->getAs<Type>();
2134 }
2135 // FIXME. This will not work for multiple declarators; as in:
2136 // __typeof__(a) b,c,d;
2137 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2138 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2139 const char *startBuf = SM->getCharacterData(DeclLoc);
2140 if (ND->getInit()) {
2141 std::string Name(ND->getNameAsString());
2142 TypeAsString += " " + Name + " = ";
2143 Expr *E = ND->getInit();
2144 SourceLocation startLoc;
2145 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2146 startLoc = ECE->getLParenLoc();
2147 else
2148 startLoc = E->getLocStart();
2149 startLoc = SM->getExpansionLoc(startLoc);
2150 const char *endBuf = SM->getCharacterData(startLoc);
2151 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2152 }
2153 else {
2154 SourceLocation X = ND->getLocEnd();
2155 X = SM->getExpansionLoc(X);
2156 const char *endBuf = SM->getCharacterData(X);
2157 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2158 }
2159}
2160
2161// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2162void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2163 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2164 SmallVector<QualType, 16> ArgTys;
2165 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2166 QualType getFuncType =
2167 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2168 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2169 SourceLocation(),
2170 SourceLocation(),
2171 SelGetUidIdent, getFuncType, 0,
2172 SC_Extern,
2173 SC_None, false);
2174}
2175
2176void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2177 // declared in <objc/objc.h>
2178 if (FD->getIdentifier() &&
2179 FD->getName() == "sel_registerName") {
2180 SelGetUidFunctionDecl = FD;
2181 return;
2182 }
2183 RewriteObjCQualifiedInterfaceTypes(FD);
2184}
2185
2186void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2187 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2188 const char *argPtr = TypeString.c_str();
2189 if (!strchr(argPtr, '^')) {
2190 Str += TypeString;
2191 return;
2192 }
2193 while (*argPtr) {
2194 Str += (*argPtr == '^' ? '*' : *argPtr);
2195 argPtr++;
2196 }
2197}
2198
2199// FIXME. Consolidate this routine with RewriteBlockPointerType.
2200void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2201 ValueDecl *VD) {
2202 QualType Type = VD->getType();
2203 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2204 const char *argPtr = TypeString.c_str();
2205 int paren = 0;
2206 while (*argPtr) {
2207 switch (*argPtr) {
2208 case '(':
2209 Str += *argPtr;
2210 paren++;
2211 break;
2212 case ')':
2213 Str += *argPtr;
2214 paren--;
2215 break;
2216 case '^':
2217 Str += '*';
2218 if (paren == 1)
2219 Str += VD->getNameAsString();
2220 break;
2221 default:
2222 Str += *argPtr;
2223 break;
2224 }
2225 argPtr++;
2226 }
2227}
2228
2229
2230void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2231 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2232 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2233 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2234 if (!proto)
2235 return;
2236 QualType Type = proto->getResultType();
2237 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2238 FdStr += " ";
2239 FdStr += FD->getName();
2240 FdStr += "(";
2241 unsigned numArgs = proto->getNumArgs();
2242 for (unsigned i = 0; i < numArgs; i++) {
2243 QualType ArgType = proto->getArgType(i);
2244 RewriteBlockPointerType(FdStr, ArgType);
2245 if (i+1 < numArgs)
2246 FdStr += ", ";
2247 }
2248 FdStr += ");\n";
2249 InsertText(FunLocStart, FdStr);
2250 CurFunctionDeclToDeclareForBlock = 0;
2251}
2252
2253// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2254void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2255 if (SuperContructorFunctionDecl)
2256 return;
2257 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2258 SmallVector<QualType, 16> ArgTys;
2259 QualType argT = Context->getObjCIdType();
2260 assert(!argT.isNull() && "Can't find 'id' type");
2261 ArgTys.push_back(argT);
2262 ArgTys.push_back(argT);
2263 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2264 &ArgTys[0], ArgTys.size());
2265 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2266 SourceLocation(),
2267 SourceLocation(),
2268 msgSendIdent, msgSendType, 0,
2269 SC_Extern,
2270 SC_None, false);
2271}
2272
2273// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2274void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2275 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2276 SmallVector<QualType, 16> ArgTys;
2277 QualType argT = Context->getObjCIdType();
2278 assert(!argT.isNull() && "Can't find 'id' type");
2279 ArgTys.push_back(argT);
2280 argT = Context->getObjCSelType();
2281 assert(!argT.isNull() && "Can't find 'SEL' type");
2282 ArgTys.push_back(argT);
2283 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2284 &ArgTys[0], ArgTys.size(),
2285 true /*isVariadic*/);
2286 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2287 SourceLocation(),
2288 SourceLocation(),
2289 msgSendIdent, msgSendType, 0,
2290 SC_Extern,
2291 SC_None, false);
2292}
2293
2294// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2295void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2296 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2297 SmallVector<QualType, 16> ArgTys;
2298 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2299 SourceLocation(), SourceLocation(),
2300 &Context->Idents.get("objc_super"));
2301 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2302 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2303 ArgTys.push_back(argT);
2304 argT = Context->getObjCSelType();
2305 assert(!argT.isNull() && "Can't find 'SEL' type");
2306 ArgTys.push_back(argT);
2307 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2308 &ArgTys[0], ArgTys.size(),
2309 true /*isVariadic*/);
2310 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2311 SourceLocation(),
2312 SourceLocation(),
2313 msgSendIdent, msgSendType, 0,
2314 SC_Extern,
2315 SC_None, false);
2316}
2317
2318// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2319void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2320 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2321 SmallVector<QualType, 16> ArgTys;
2322 QualType argT = Context->getObjCIdType();
2323 assert(!argT.isNull() && "Can't find 'id' type");
2324 ArgTys.push_back(argT);
2325 argT = Context->getObjCSelType();
2326 assert(!argT.isNull() && "Can't find 'SEL' type");
2327 ArgTys.push_back(argT);
2328 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2329 &ArgTys[0], ArgTys.size(),
2330 true /*isVariadic*/);
2331 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2332 SourceLocation(),
2333 SourceLocation(),
2334 msgSendIdent, msgSendType, 0,
2335 SC_Extern,
2336 SC_None, false);
2337}
2338
2339// SynthMsgSendSuperStretFunctionDecl -
2340// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2341void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2342 IdentifierInfo *msgSendIdent =
2343 &Context->Idents.get("objc_msgSendSuper_stret");
2344 SmallVector<QualType, 16> ArgTys;
2345 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2346 SourceLocation(), SourceLocation(),
2347 &Context->Idents.get("objc_super"));
2348 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2349 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2350 ArgTys.push_back(argT);
2351 argT = Context->getObjCSelType();
2352 assert(!argT.isNull() && "Can't find 'SEL' type");
2353 ArgTys.push_back(argT);
2354 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2355 &ArgTys[0], ArgTys.size(),
2356 true /*isVariadic*/);
2357 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 msgSendIdent, msgSendType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2366void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2367 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2368 SmallVector<QualType, 16> ArgTys;
2369 QualType argT = Context->getObjCIdType();
2370 assert(!argT.isNull() && "Can't find 'id' type");
2371 ArgTys.push_back(argT);
2372 argT = Context->getObjCSelType();
2373 assert(!argT.isNull() && "Can't find 'SEL' type");
2374 ArgTys.push_back(argT);
2375 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2376 &ArgTys[0], ArgTys.size(),
2377 true /*isVariadic*/);
2378 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2379 SourceLocation(),
2380 SourceLocation(),
2381 msgSendIdent, msgSendType, 0,
2382 SC_Extern,
2383 SC_None, false);
2384}
2385
2386// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2387void RewriteModernObjC::SynthGetClassFunctionDecl() {
2388 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2389 SmallVector<QualType, 16> ArgTys;
2390 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2391 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2392 &ArgTys[0], ArgTys.size());
2393 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2394 SourceLocation(),
2395 SourceLocation(),
2396 getClassIdent, getClassType, 0,
2397 SC_Extern,
2398 SC_None, false);
2399}
2400
2401// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2402void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2403 IdentifierInfo *getSuperClassIdent =
2404 &Context->Idents.get("class_getSuperclass");
2405 SmallVector<QualType, 16> ArgTys;
2406 ArgTys.push_back(Context->getObjCClassType());
2407 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2408 &ArgTys[0], ArgTys.size());
2409 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2410 SourceLocation(),
2411 SourceLocation(),
2412 getSuperClassIdent,
2413 getClassType, 0,
2414 SC_Extern,
2415 SC_None,
2416 false);
2417}
2418
2419// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2420void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2421 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2422 SmallVector<QualType, 16> ArgTys;
2423 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2424 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2425 &ArgTys[0], ArgTys.size());
2426 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2427 SourceLocation(),
2428 SourceLocation(),
2429 getClassIdent, getClassType, 0,
2430 SC_Extern,
2431 SC_None, false);
2432}
2433
2434Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2435 QualType strType = getConstantStringStructType();
2436
2437 std::string S = "__NSConstantStringImpl_";
2438
2439 std::string tmpName = InFileName;
2440 unsigned i;
2441 for (i=0; i < tmpName.length(); i++) {
2442 char c = tmpName.at(i);
2443 // replace any non alphanumeric characters with '_'.
2444 if (!isalpha(c) && (c < '0' || c > '9'))
2445 tmpName[i] = '_';
2446 }
2447 S += tmpName;
2448 S += "_";
2449 S += utostr(NumObjCStringLiterals++);
2450
2451 Preamble += "static __NSConstantStringImpl " + S;
2452 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2453 Preamble += "0x000007c8,"; // utf8_str
2454 // The pretty printer for StringLiteral handles escape characters properly.
2455 std::string prettyBufS;
2456 llvm::raw_string_ostream prettyBuf(prettyBufS);
2457 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2458 PrintingPolicy(LangOpts));
2459 Preamble += prettyBuf.str();
2460 Preamble += ",";
2461 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2462
2463 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2464 SourceLocation(), &Context->Idents.get(S),
2465 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002466 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002467 SourceLocation());
2468 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2469 Context->getPointerType(DRE->getType()),
2470 VK_RValue, OK_Ordinary,
2471 SourceLocation());
2472 // cast to NSConstantString *
2473 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2474 CK_CPointerToObjCPointerCast, Unop);
2475 ReplaceStmt(Exp, cast);
2476 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2477 return cast;
2478}
2479
Fariborz Jahanian55947042012-03-27 20:17:30 +00002480Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2481 unsigned IntSize =
2482 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2483
2484 Expr *FlagExp = IntegerLiteral::Create(*Context,
2485 llvm::APInt(IntSize, Exp->getValue()),
2486 Context->IntTy, Exp->getLocation());
2487 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2488 CK_BitCast, FlagExp);
2489 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2490 cast);
2491 ReplaceStmt(Exp, PE);
2492 return PE;
2493}
2494
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002495Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2496 // synthesize declaration of helper functions needed in this routine.
2497 if (!SelGetUidFunctionDecl)
2498 SynthSelGetUidFunctionDecl();
2499 // use objc_msgSend() for all.
2500 if (!MsgSendFunctionDecl)
2501 SynthMsgSendFunctionDecl();
2502 if (!GetClassFunctionDecl)
2503 SynthGetClassFunctionDecl();
2504
2505 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2506 SourceLocation StartLoc = Exp->getLocStart();
2507 SourceLocation EndLoc = Exp->getLocEnd();
2508
2509 // Synthesize a call to objc_msgSend().
2510 SmallVector<Expr*, 4> MsgExprs;
2511 SmallVector<Expr*, 4> ClsExprs;
2512 QualType argType = Context->getPointerType(Context->CharTy);
2513 QualType expType = Exp->getType();
2514
2515 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2516 ObjCInterfaceDecl *Class =
2517 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2518
2519 IdentifierInfo *clsName = Class->getIdentifier();
2520 ClsExprs.push_back(StringLiteral::Create(*Context,
2521 clsName->getName(),
2522 StringLiteral::Ascii, false,
2523 argType, SourceLocation()));
2524 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2525 &ClsExprs[0],
2526 ClsExprs.size(),
2527 StartLoc, EndLoc);
2528 MsgExprs.push_back(Cls);
2529
2530 // Create a call to sel_registerName("numberWithBool:"), etc.
2531 // it will be the 2nd argument.
2532 SmallVector<Expr*, 4> SelExprs;
2533 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2534 SelExprs.push_back(StringLiteral::Create(*Context,
2535 NumericMethod->getSelector().getAsString(),
2536 StringLiteral::Ascii, false,
2537 argType, SourceLocation()));
2538 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2539 &SelExprs[0], SelExprs.size(),
2540 StartLoc, EndLoc);
2541 MsgExprs.push_back(SelExp);
2542
2543 // User provided numeric literal is the 3rd, and last, argument.
2544 Expr *userExpr = Exp->getNumber();
2545 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2546 QualType type = ICE->getType();
2547 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2548 CastKind CK = CK_BitCast;
2549 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2550 CK = CK_IntegralToBoolean;
2551 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2552 }
2553 MsgExprs.push_back(userExpr);
2554
2555 SmallVector<QualType, 4> ArgTypes;
2556 ArgTypes.push_back(Context->getObjCIdType());
2557 ArgTypes.push_back(Context->getObjCSelType());
2558 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2559 E = NumericMethod->param_end(); PI != E; ++PI)
2560 ArgTypes.push_back((*PI)->getType());
2561
2562 QualType returnType = Exp->getType();
2563 // Get the type, we will need to reference it in a couple spots.
2564 QualType msgSendType = MsgSendFlavor->getType();
2565
2566 // Create a reference to the objc_msgSend() declaration.
2567 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2568 VK_LValue, SourceLocation());
2569
2570 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2571 Context->getPointerType(Context->VoidTy),
2572 CK_BitCast, DRE);
2573
2574 // Now do the "normal" pointer to function cast.
2575 QualType castType =
2576 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2577 NumericMethod->isVariadic());
2578 castType = Context->getPointerType(castType);
2579 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2580 cast);
2581
2582 // Don't forget the parens to enforce the proper binding.
2583 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2584
2585 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2586 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2587 MsgExprs.size(),
2588 FT->getResultType(), VK_RValue,
2589 EndLoc);
2590 ReplaceStmt(Exp, CE);
2591 return CE;
2592}
2593
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002594Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2595 // synthesize declaration of helper functions needed in this routine.
2596 if (!SelGetUidFunctionDecl)
2597 SynthSelGetUidFunctionDecl();
2598 // use objc_msgSend() for all.
2599 if (!MsgSendFunctionDecl)
2600 SynthMsgSendFunctionDecl();
2601 if (!GetClassFunctionDecl)
2602 SynthGetClassFunctionDecl();
2603
2604 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2605 SourceLocation StartLoc = Exp->getLocStart();
2606 SourceLocation EndLoc = Exp->getLocEnd();
2607
2608 // Synthesize a call to objc_msgSend().
2609 SmallVector<Expr*, 32> MsgExprs;
2610 SmallVector<Expr*, 4> ClsExprs;
2611 QualType argType = Context->getPointerType(Context->CharTy);
2612 QualType expType = Exp->getType();
2613
2614 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2615 ObjCInterfaceDecl *Class =
2616 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2617
2618 IdentifierInfo *clsName = Class->getIdentifier();
2619 ClsExprs.push_back(StringLiteral::Create(*Context,
2620 clsName->getName(),
2621 StringLiteral::Ascii, false,
2622 argType, SourceLocation()));
2623 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2624 &ClsExprs[0],
2625 ClsExprs.size(),
2626 StartLoc, EndLoc);
2627 MsgExprs.push_back(Cls);
2628
2629 // Create a call to sel_registerName("arrayWithObjects:count:").
2630 // it will be the 2nd argument.
2631 SmallVector<Expr*, 4> SelExprs;
2632 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2633 SelExprs.push_back(StringLiteral::Create(*Context,
2634 ArrayMethod->getSelector().getAsString(),
2635 StringLiteral::Ascii, false,
2636 argType, SourceLocation()));
2637 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2638 &SelExprs[0], SelExprs.size(),
2639 StartLoc, EndLoc);
2640 MsgExprs.push_back(SelExp);
2641
2642 unsigned NumElements = Exp->getNumElements();
2643
2644 // FIXME. Incomplete.
2645 InitListExpr *ILE =
2646 new (Context) InitListExpr(*Context, SourceLocation(),
2647 Exp->getElements(), NumElements,
2648 SourceLocation());
2649 MsgExprs.push_back(ILE);
2650 unsigned UnsignedIntSize =
2651 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2652
2653 Expr *count = IntegerLiteral::Create(*Context,
2654 llvm::APInt(UnsignedIntSize, NumElements),
2655 Context->UnsignedIntTy,
2656 SourceLocation());
2657 MsgExprs.push_back(count);
2658
2659
2660 SmallVector<QualType, 4> ArgTypes;
2661 ArgTypes.push_back(Context->getObjCIdType());
2662 ArgTypes.push_back(Context->getObjCSelType());
2663 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2664 E = ArrayMethod->param_end(); PI != E; ++PI)
2665 ArgTypes.push_back((*PI)->getType());
2666
2667 QualType returnType = Exp->getType();
2668 // Get the type, we will need to reference it in a couple spots.
2669 QualType msgSendType = MsgSendFlavor->getType();
2670
2671 // Create a reference to the objc_msgSend() declaration.
2672 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2673 VK_LValue, SourceLocation());
2674
2675 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2676 Context->getPointerType(Context->VoidTy),
2677 CK_BitCast, DRE);
2678
2679 // Now do the "normal" pointer to function cast.
2680 QualType castType =
2681 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2682 ArrayMethod->isVariadic());
2683 castType = Context->getPointerType(castType);
2684 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2685 cast);
2686
2687 // Don't forget the parens to enforce the proper binding.
2688 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2689
2690 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2691 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2692 MsgExprs.size(),
2693 FT->getResultType(), VK_RValue,
2694 EndLoc);
2695 ReplaceStmt(Exp, CE);
2696 return CE;
2697}
2698
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002699// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2700QualType RewriteModernObjC::getSuperStructType() {
2701 if (!SuperStructDecl) {
2702 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2703 SourceLocation(), SourceLocation(),
2704 &Context->Idents.get("objc_super"));
2705 QualType FieldTypes[2];
2706
2707 // struct objc_object *receiver;
2708 FieldTypes[0] = Context->getObjCIdType();
2709 // struct objc_class *super;
2710 FieldTypes[1] = Context->getObjCClassType();
2711
2712 // Create fields
2713 for (unsigned i = 0; i < 2; ++i) {
2714 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2715 SourceLocation(),
2716 SourceLocation(), 0,
2717 FieldTypes[i], 0,
2718 /*BitWidth=*/0,
2719 /*Mutable=*/false,
2720 /*HasInit=*/false));
2721 }
2722
2723 SuperStructDecl->completeDefinition();
2724 }
2725 return Context->getTagDeclType(SuperStructDecl);
2726}
2727
2728QualType RewriteModernObjC::getConstantStringStructType() {
2729 if (!ConstantStringDecl) {
2730 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2731 SourceLocation(), SourceLocation(),
2732 &Context->Idents.get("__NSConstantStringImpl"));
2733 QualType FieldTypes[4];
2734
2735 // struct objc_object *receiver;
2736 FieldTypes[0] = Context->getObjCIdType();
2737 // int flags;
2738 FieldTypes[1] = Context->IntTy;
2739 // char *str;
2740 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2741 // long length;
2742 FieldTypes[3] = Context->LongTy;
2743
2744 // Create fields
2745 for (unsigned i = 0; i < 4; ++i) {
2746 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2747 ConstantStringDecl,
2748 SourceLocation(),
2749 SourceLocation(), 0,
2750 FieldTypes[i], 0,
2751 /*BitWidth=*/0,
2752 /*Mutable=*/true,
2753 /*HasInit=*/false));
2754 }
2755
2756 ConstantStringDecl->completeDefinition();
2757 }
2758 return Context->getTagDeclType(ConstantStringDecl);
2759}
2760
2761Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2762 SourceLocation StartLoc,
2763 SourceLocation EndLoc) {
2764 if (!SelGetUidFunctionDecl)
2765 SynthSelGetUidFunctionDecl();
2766 if (!MsgSendFunctionDecl)
2767 SynthMsgSendFunctionDecl();
2768 if (!MsgSendSuperFunctionDecl)
2769 SynthMsgSendSuperFunctionDecl();
2770 if (!MsgSendStretFunctionDecl)
2771 SynthMsgSendStretFunctionDecl();
2772 if (!MsgSendSuperStretFunctionDecl)
2773 SynthMsgSendSuperStretFunctionDecl();
2774 if (!MsgSendFpretFunctionDecl)
2775 SynthMsgSendFpretFunctionDecl();
2776 if (!GetClassFunctionDecl)
2777 SynthGetClassFunctionDecl();
2778 if (!GetSuperClassFunctionDecl)
2779 SynthGetSuperClassFunctionDecl();
2780 if (!GetMetaClassFunctionDecl)
2781 SynthGetMetaClassFunctionDecl();
2782
2783 // default to objc_msgSend().
2784 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2785 // May need to use objc_msgSend_stret() as well.
2786 FunctionDecl *MsgSendStretFlavor = 0;
2787 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2788 QualType resultType = mDecl->getResultType();
2789 if (resultType->isRecordType())
2790 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2791 else if (resultType->isRealFloatingType())
2792 MsgSendFlavor = MsgSendFpretFunctionDecl;
2793 }
2794
2795 // Synthesize a call to objc_msgSend().
2796 SmallVector<Expr*, 8> MsgExprs;
2797 switch (Exp->getReceiverKind()) {
2798 case ObjCMessageExpr::SuperClass: {
2799 MsgSendFlavor = MsgSendSuperFunctionDecl;
2800 if (MsgSendStretFlavor)
2801 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2802 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2803
2804 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2805
2806 SmallVector<Expr*, 4> InitExprs;
2807
2808 // set the receiver to self, the first argument to all methods.
2809 InitExprs.push_back(
2810 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2811 CK_BitCast,
2812 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002813 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002814 Context->getObjCIdType(),
2815 VK_RValue,
2816 SourceLocation()))
2817 ); // set the 'receiver'.
2818
2819 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2820 SmallVector<Expr*, 8> ClsExprs;
2821 QualType argType = Context->getPointerType(Context->CharTy);
2822 ClsExprs.push_back(StringLiteral::Create(*Context,
2823 ClassDecl->getIdentifier()->getName(),
2824 StringLiteral::Ascii, false,
2825 argType, SourceLocation()));
2826 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2827 &ClsExprs[0],
2828 ClsExprs.size(),
2829 StartLoc,
2830 EndLoc);
2831 // (Class)objc_getClass("CurrentClass")
2832 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2833 Context->getObjCClassType(),
2834 CK_BitCast, Cls);
2835 ClsExprs.clear();
2836 ClsExprs.push_back(ArgExpr);
2837 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2838 &ClsExprs[0], ClsExprs.size(),
2839 StartLoc, EndLoc);
2840
2841 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2842 // To turn off a warning, type-cast to 'id'
2843 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2844 NoTypeInfoCStyleCastExpr(Context,
2845 Context->getObjCIdType(),
2846 CK_BitCast, Cls));
2847 // struct objc_super
2848 QualType superType = getSuperStructType();
2849 Expr *SuperRep;
2850
2851 if (LangOpts.MicrosoftExt) {
2852 SynthSuperContructorFunctionDecl();
2853 // Simulate a contructor call...
2854 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002855 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002856 SourceLocation());
2857 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2858 InitExprs.size(),
2859 superType, VK_LValue,
2860 SourceLocation());
2861 // The code for super is a little tricky to prevent collision with
2862 // the structure definition in the header. The rewriter has it's own
2863 // internal definition (__rw_objc_super) that is uses. This is why
2864 // we need the cast below. For example:
2865 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2866 //
2867 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2868 Context->getPointerType(SuperRep->getType()),
2869 VK_RValue, OK_Ordinary,
2870 SourceLocation());
2871 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2872 Context->getPointerType(superType),
2873 CK_BitCast, SuperRep);
2874 } else {
2875 // (struct objc_super) { <exprs from above> }
2876 InitListExpr *ILE =
2877 new (Context) InitListExpr(*Context, SourceLocation(),
2878 &InitExprs[0], InitExprs.size(),
2879 SourceLocation());
2880 TypeSourceInfo *superTInfo
2881 = Context->getTrivialTypeSourceInfo(superType);
2882 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2883 superType, VK_LValue,
2884 ILE, false);
2885 // struct objc_super *
2886 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2887 Context->getPointerType(SuperRep->getType()),
2888 VK_RValue, OK_Ordinary,
2889 SourceLocation());
2890 }
2891 MsgExprs.push_back(SuperRep);
2892 break;
2893 }
2894
2895 case ObjCMessageExpr::Class: {
2896 SmallVector<Expr*, 8> ClsExprs;
2897 QualType argType = Context->getPointerType(Context->CharTy);
2898 ObjCInterfaceDecl *Class
2899 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2900 IdentifierInfo *clsName = Class->getIdentifier();
2901 ClsExprs.push_back(StringLiteral::Create(*Context,
2902 clsName->getName(),
2903 StringLiteral::Ascii, false,
2904 argType, SourceLocation()));
2905 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2906 &ClsExprs[0],
2907 ClsExprs.size(),
2908 StartLoc, EndLoc);
2909 MsgExprs.push_back(Cls);
2910 break;
2911 }
2912
2913 case ObjCMessageExpr::SuperInstance:{
2914 MsgSendFlavor = MsgSendSuperFunctionDecl;
2915 if (MsgSendStretFlavor)
2916 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2917 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2918 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2919 SmallVector<Expr*, 4> InitExprs;
2920
2921 InitExprs.push_back(
2922 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2923 CK_BitCast,
2924 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002925 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002926 Context->getObjCIdType(),
2927 VK_RValue, SourceLocation()))
2928 ); // set the 'receiver'.
2929
2930 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2931 SmallVector<Expr*, 8> ClsExprs;
2932 QualType argType = Context->getPointerType(Context->CharTy);
2933 ClsExprs.push_back(StringLiteral::Create(*Context,
2934 ClassDecl->getIdentifier()->getName(),
2935 StringLiteral::Ascii, false, argType,
2936 SourceLocation()));
2937 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2938 &ClsExprs[0],
2939 ClsExprs.size(),
2940 StartLoc, EndLoc);
2941 // (Class)objc_getClass("CurrentClass")
2942 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2943 Context->getObjCClassType(),
2944 CK_BitCast, Cls);
2945 ClsExprs.clear();
2946 ClsExprs.push_back(ArgExpr);
2947 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2948 &ClsExprs[0], ClsExprs.size(),
2949 StartLoc, EndLoc);
2950
2951 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2952 // To turn off a warning, type-cast to 'id'
2953 InitExprs.push_back(
2954 // set 'super class', using class_getSuperclass().
2955 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2956 CK_BitCast, Cls));
2957 // struct objc_super
2958 QualType superType = getSuperStructType();
2959 Expr *SuperRep;
2960
2961 if (LangOpts.MicrosoftExt) {
2962 SynthSuperContructorFunctionDecl();
2963 // Simulate a contructor call...
2964 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002965 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002966 SourceLocation());
2967 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2968 InitExprs.size(),
2969 superType, VK_LValue, SourceLocation());
2970 // The code for super is a little tricky to prevent collision with
2971 // the structure definition in the header. The rewriter has it's own
2972 // internal definition (__rw_objc_super) that is uses. This is why
2973 // we need the cast below. For example:
2974 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2975 //
2976 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2977 Context->getPointerType(SuperRep->getType()),
2978 VK_RValue, OK_Ordinary,
2979 SourceLocation());
2980 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2981 Context->getPointerType(superType),
2982 CK_BitCast, SuperRep);
2983 } else {
2984 // (struct objc_super) { <exprs from above> }
2985 InitListExpr *ILE =
2986 new (Context) InitListExpr(*Context, SourceLocation(),
2987 &InitExprs[0], InitExprs.size(),
2988 SourceLocation());
2989 TypeSourceInfo *superTInfo
2990 = Context->getTrivialTypeSourceInfo(superType);
2991 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2992 superType, VK_RValue, ILE,
2993 false);
2994 }
2995 MsgExprs.push_back(SuperRep);
2996 break;
2997 }
2998
2999 case ObjCMessageExpr::Instance: {
3000 // Remove all type-casts because it may contain objc-style types; e.g.
3001 // Foo<Proto> *.
3002 Expr *recExpr = Exp->getInstanceReceiver();
3003 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3004 recExpr = CE->getSubExpr();
3005 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3006 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3007 ? CK_BlockPointerToObjCPointerCast
3008 : CK_CPointerToObjCPointerCast;
3009
3010 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3011 CK, recExpr);
3012 MsgExprs.push_back(recExpr);
3013 break;
3014 }
3015 }
3016
3017 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3018 SmallVector<Expr*, 8> SelExprs;
3019 QualType argType = Context->getPointerType(Context->CharTy);
3020 SelExprs.push_back(StringLiteral::Create(*Context,
3021 Exp->getSelector().getAsString(),
3022 StringLiteral::Ascii, false,
3023 argType, SourceLocation()));
3024 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3025 &SelExprs[0], SelExprs.size(),
3026 StartLoc,
3027 EndLoc);
3028 MsgExprs.push_back(SelExp);
3029
3030 // Now push any user supplied arguments.
3031 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3032 Expr *userExpr = Exp->getArg(i);
3033 // Make all implicit casts explicit...ICE comes in handy:-)
3034 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3035 // Reuse the ICE type, it is exactly what the doctor ordered.
3036 QualType type = ICE->getType();
3037 if (needToScanForQualifiers(type))
3038 type = Context->getObjCIdType();
3039 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3040 (void)convertBlockPointerToFunctionPointer(type);
3041 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3042 CastKind CK;
3043 if (SubExpr->getType()->isIntegralType(*Context) &&
3044 type->isBooleanType()) {
3045 CK = CK_IntegralToBoolean;
3046 } else if (type->isObjCObjectPointerType()) {
3047 if (SubExpr->getType()->isBlockPointerType()) {
3048 CK = CK_BlockPointerToObjCPointerCast;
3049 } else if (SubExpr->getType()->isPointerType()) {
3050 CK = CK_CPointerToObjCPointerCast;
3051 } else {
3052 CK = CK_BitCast;
3053 }
3054 } else {
3055 CK = CK_BitCast;
3056 }
3057
3058 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3059 }
3060 // Make id<P...> cast into an 'id' cast.
3061 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3062 if (CE->getType()->isObjCQualifiedIdType()) {
3063 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3064 userExpr = CE->getSubExpr();
3065 CastKind CK;
3066 if (userExpr->getType()->isIntegralType(*Context)) {
3067 CK = CK_IntegralToPointer;
3068 } else if (userExpr->getType()->isBlockPointerType()) {
3069 CK = CK_BlockPointerToObjCPointerCast;
3070 } else if (userExpr->getType()->isPointerType()) {
3071 CK = CK_CPointerToObjCPointerCast;
3072 } else {
3073 CK = CK_BitCast;
3074 }
3075 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3076 CK, userExpr);
3077 }
3078 }
3079 MsgExprs.push_back(userExpr);
3080 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3081 // out the argument in the original expression (since we aren't deleting
3082 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3083 //Exp->setArg(i, 0);
3084 }
3085 // Generate the funky cast.
3086 CastExpr *cast;
3087 SmallVector<QualType, 8> ArgTypes;
3088 QualType returnType;
3089
3090 // Push 'id' and 'SEL', the 2 implicit arguments.
3091 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3092 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3093 else
3094 ArgTypes.push_back(Context->getObjCIdType());
3095 ArgTypes.push_back(Context->getObjCSelType());
3096 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3097 // Push any user argument types.
3098 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3099 E = OMD->param_end(); PI != E; ++PI) {
3100 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3101 ? Context->getObjCIdType()
3102 : (*PI)->getType();
3103 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3104 (void)convertBlockPointerToFunctionPointer(t);
3105 ArgTypes.push_back(t);
3106 }
3107 returnType = Exp->getType();
3108 convertToUnqualifiedObjCType(returnType);
3109 (void)convertBlockPointerToFunctionPointer(returnType);
3110 } else {
3111 returnType = Context->getObjCIdType();
3112 }
3113 // Get the type, we will need to reference it in a couple spots.
3114 QualType msgSendType = MsgSendFlavor->getType();
3115
3116 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003117 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003118 VK_LValue, SourceLocation());
3119
3120 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3121 // If we don't do this cast, we get the following bizarre warning/note:
3122 // xx.m:13: warning: function called through a non-compatible type
3123 // xx.m:13: note: if this code is reached, the program will abort
3124 cast = NoTypeInfoCStyleCastExpr(Context,
3125 Context->getPointerType(Context->VoidTy),
3126 CK_BitCast, DRE);
3127
3128 // Now do the "normal" pointer to function cast.
3129 QualType castType =
3130 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3131 // If we don't have a method decl, force a variadic cast.
3132 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3133 castType = Context->getPointerType(castType);
3134 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3135 cast);
3136
3137 // Don't forget the parens to enforce the proper binding.
3138 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3139
3140 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3141 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3142 MsgExprs.size(),
3143 FT->getResultType(), VK_RValue,
3144 EndLoc);
3145 Stmt *ReplacingStmt = CE;
3146 if (MsgSendStretFlavor) {
3147 // We have the method which returns a struct/union. Must also generate
3148 // call to objc_msgSend_stret and hang both varieties on a conditional
3149 // expression which dictate which one to envoke depending on size of
3150 // method's return type.
3151
3152 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003153 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3154 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003155 VK_LValue, SourceLocation());
3156 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3157 cast = NoTypeInfoCStyleCastExpr(Context,
3158 Context->getPointerType(Context->VoidTy),
3159 CK_BitCast, STDRE);
3160 // Now do the "normal" pointer to function cast.
3161 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3162 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3163 castType = Context->getPointerType(castType);
3164 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3165 cast);
3166
3167 // Don't forget the parens to enforce the proper binding.
3168 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3169
3170 FT = msgSendType->getAs<FunctionType>();
3171 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3172 MsgExprs.size(),
3173 FT->getResultType(), VK_RValue,
3174 SourceLocation());
3175
3176 // Build sizeof(returnType)
3177 UnaryExprOrTypeTraitExpr *sizeofExpr =
3178 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3179 Context->getTrivialTypeSourceInfo(returnType),
3180 Context->getSizeType(), SourceLocation(),
3181 SourceLocation());
3182 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3183 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3184 // For X86 it is more complicated and some kind of target specific routine
3185 // is needed to decide what to do.
3186 unsigned IntSize =
3187 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3188 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3189 llvm::APInt(IntSize, 8),
3190 Context->IntTy,
3191 SourceLocation());
3192 BinaryOperator *lessThanExpr =
3193 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3194 VK_RValue, OK_Ordinary, SourceLocation());
3195 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3196 ConditionalOperator *CondExpr =
3197 new (Context) ConditionalOperator(lessThanExpr,
3198 SourceLocation(), CE,
3199 SourceLocation(), STCE,
3200 returnType, VK_RValue, OK_Ordinary);
3201 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3202 CondExpr);
3203 }
3204 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3205 return ReplacingStmt;
3206}
3207
3208Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3209 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3210 Exp->getLocEnd());
3211
3212 // Now do the actual rewrite.
3213 ReplaceStmt(Exp, ReplacingStmt);
3214
3215 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3216 return ReplacingStmt;
3217}
3218
3219// typedef struct objc_object Protocol;
3220QualType RewriteModernObjC::getProtocolType() {
3221 if (!ProtocolTypeDecl) {
3222 TypeSourceInfo *TInfo
3223 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3224 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3225 SourceLocation(), SourceLocation(),
3226 &Context->Idents.get("Protocol"),
3227 TInfo);
3228 }
3229 return Context->getTypeDeclType(ProtocolTypeDecl);
3230}
3231
3232/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3233/// a synthesized/forward data reference (to the protocol's metadata).
3234/// The forward references (and metadata) are generated in
3235/// RewriteModernObjC::HandleTranslationUnit().
3236Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003237 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3238 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003239 IdentifierInfo *ID = &Context->Idents.get(Name);
3240 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3241 SourceLocation(), ID, getProtocolType(), 0,
3242 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003243 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3244 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003245 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3246 Context->getPointerType(DRE->getType()),
3247 VK_RValue, OK_Ordinary, SourceLocation());
3248 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3249 CK_BitCast,
3250 DerefExpr);
3251 ReplaceStmt(Exp, castExpr);
3252 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3253 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3254 return castExpr;
3255
3256}
3257
3258bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3259 const char *endBuf) {
3260 while (startBuf < endBuf) {
3261 if (*startBuf == '#') {
3262 // Skip whitespace.
3263 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3264 ;
3265 if (!strncmp(startBuf, "if", strlen("if")) ||
3266 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3267 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3268 !strncmp(startBuf, "define", strlen("define")) ||
3269 !strncmp(startBuf, "undef", strlen("undef")) ||
3270 !strncmp(startBuf, "else", strlen("else")) ||
3271 !strncmp(startBuf, "elif", strlen("elif")) ||
3272 !strncmp(startBuf, "endif", strlen("endif")) ||
3273 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3274 !strncmp(startBuf, "include", strlen("include")) ||
3275 !strncmp(startBuf, "import", strlen("import")) ||
3276 !strncmp(startBuf, "include_next", strlen("include_next")))
3277 return true;
3278 }
3279 startBuf++;
3280 }
3281 return false;
3282}
3283
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003284/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003285/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003286bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3287 std::string &Result) {
3288 if (Type->isArrayType()) {
3289 QualType ElemTy = Context->getBaseElementType(Type);
3290 return RewriteObjCFieldDeclType(ElemTy, Result);
3291 }
3292 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003293 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3294 if (RD->isCompleteDefinition()) {
3295 if (RD->isStruct())
3296 Result += "\n\tstruct ";
3297 else if (RD->isUnion())
3298 Result += "\n\tunion ";
3299 else
3300 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003301
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003302 Result += RD->getName();
3303 if (TagsDefinedInIvarDecls.count(RD)) {
3304 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003305 Result += " ";
3306 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003307 }
3308 TagsDefinedInIvarDecls.insert(RD);
3309 Result += " {\n";
3310 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003311 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003312 FieldDecl *FD = *i;
3313 RewriteObjCFieldDecl(FD, Result);
3314 }
3315 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003316 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003317 }
3318 }
3319 else if (Type->isEnumeralType()) {
3320 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3321 if (ED->isCompleteDefinition()) {
3322 Result += "\n\tenum ";
3323 Result += ED->getName();
3324 if (TagsDefinedInIvarDecls.count(ED)) {
3325 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003326 Result += " ";
3327 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003328 }
3329 TagsDefinedInIvarDecls.insert(ED);
3330
3331 Result += " {\n";
3332 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3333 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3334 Result += "\t"; Result += EC->getName(); Result += " = ";
3335 llvm::APSInt Val = EC->getInitVal();
3336 Result += Val.toString(10);
3337 Result += ",\n";
3338 }
3339 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003340 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003341 }
3342 }
3343
3344 Result += "\t";
3345 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003346 return false;
3347}
3348
3349
3350/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3351/// It handles elaborated types, as well as enum types in the process.
3352void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3353 std::string &Result) {
3354 QualType Type = fieldDecl->getType();
3355 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003356
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003357 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3358 if (!EleboratedType)
3359 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003360 Result += Name;
3361 if (fieldDecl->isBitField()) {
3362 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3363 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003364 else if (EleboratedType && Type->isArrayType()) {
3365 CanQualType CType = Context->getCanonicalType(Type);
3366 while (isa<ArrayType>(CType)) {
3367 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3368 Result += "[";
3369 llvm::APInt Dim = CAT->getSize();
3370 Result += utostr(Dim.getZExtValue());
3371 Result += "]";
3372 }
3373 CType = CType->getAs<ArrayType>()->getElementType();
3374 }
3375 }
3376
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003377 Result += ";\n";
3378}
3379
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003380/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3381/// an objective-c class with ivars.
3382void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3383 std::string &Result) {
3384 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3385 assert(CDecl->getName() != "" &&
3386 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003387 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003388 SmallVector<ObjCIvarDecl *, 8> IVars;
3389 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003390 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003391 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003392
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003393 SourceLocation LocStart = CDecl->getLocStart();
3394 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003395
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003396 const char *startBuf = SM->getCharacterData(LocStart);
3397 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003398
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003399 // If no ivars and no root or if its root, directly or indirectly,
3400 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003401 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003402 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3403 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3404 ReplaceText(LocStart, endBuf-startBuf, Result);
3405 return;
3406 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003407
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003408 Result += "\nstruct ";
3409 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003410 Result += "_IMPL {\n";
3411
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003412 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003413 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3414 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3415 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003416 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003417 TagsDefinedInIvarDecls.clear();
3418 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3419 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003420
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003421 Result += "};\n";
3422 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3423 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003424 // Mark this struct as having been generated.
3425 if (!ObjCSynthesizedStructs.insert(CDecl))
3426 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003427}
3428
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003429static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3430 ObjCIvarDecl *IvarDecl, std::string &Result) {
3431 Result += "OBJC_IVAR_$_";
3432 Result += IDecl->getName();
3433 Result += "$";
3434 Result += IvarDecl->getName();
3435}
3436
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003437/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3438/// have been referenced in an ivar access expression.
3439void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3440 std::string &Result) {
3441 // write out ivar offset symbols which have been referenced in an ivar
3442 // access expression.
3443 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3444 if (Ivars.empty())
3445 return;
3446 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3447 e = Ivars.end(); i != e; i++) {
3448 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003449 Result += "\n";
3450 if (LangOpts.MicrosoftExt)
3451 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003452 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003453 if (LangOpts.MicrosoftExt &&
3454 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003455 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3456 Result += "__declspec(dllimport) ";
3457
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003458 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003459 WriteInternalIvarName(CDecl, IvarDecl, Result);
3460 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003461 }
3462}
3463
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003464//===----------------------------------------------------------------------===//
3465// Meta Data Emission
3466//===----------------------------------------------------------------------===//
3467
3468
3469/// RewriteImplementations - This routine rewrites all method implementations
3470/// and emits meta-data.
3471
3472void RewriteModernObjC::RewriteImplementations() {
3473 int ClsDefCount = ClassImplementation.size();
3474 int CatDefCount = CategoryImplementation.size();
3475
3476 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003477 for (int i = 0; i < ClsDefCount; i++) {
3478 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3479 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3480 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003481 assert(false &&
3482 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003483 RewriteImplementationDecl(OIMP);
3484 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003485
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003486 for (int i = 0; i < CatDefCount; i++) {
3487 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3488 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3489 if (CDecl->isImplicitInterfaceDecl())
3490 assert(false &&
3491 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003492 RewriteImplementationDecl(CIMP);
3493 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003494}
3495
3496void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3497 const std::string &Name,
3498 ValueDecl *VD, bool def) {
3499 assert(BlockByRefDeclNo.count(VD) &&
3500 "RewriteByRefString: ByRef decl missing");
3501 if (def)
3502 ResultStr += "struct ";
3503 ResultStr += "__Block_byref_" + Name +
3504 "_" + utostr(BlockByRefDeclNo[VD]) ;
3505}
3506
3507static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3508 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3509 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3510 return false;
3511}
3512
3513std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3514 StringRef funcName,
3515 std::string Tag) {
3516 const FunctionType *AFT = CE->getFunctionType();
3517 QualType RT = AFT->getResultType();
3518 std::string StructRef = "struct " + Tag;
3519 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003520 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003521
3522 BlockDecl *BD = CE->getBlockDecl();
3523
3524 if (isa<FunctionNoProtoType>(AFT)) {
3525 // No user-supplied arguments. Still need to pass in a pointer to the
3526 // block (to reference imported block decl refs).
3527 S += "(" + StructRef + " *__cself)";
3528 } else if (BD->param_empty()) {
3529 S += "(" + StructRef + " *__cself)";
3530 } else {
3531 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3532 assert(FT && "SynthesizeBlockFunc: No function proto");
3533 S += '(';
3534 // first add the implicit argument.
3535 S += StructRef + " *__cself, ";
3536 std::string ParamStr;
3537 for (BlockDecl::param_iterator AI = BD->param_begin(),
3538 E = BD->param_end(); AI != E; ++AI) {
3539 if (AI != BD->param_begin()) S += ", ";
3540 ParamStr = (*AI)->getNameAsString();
3541 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003542 (void)convertBlockPointerToFunctionPointer(QT);
3543 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003544 S += ParamStr;
3545 }
3546 if (FT->isVariadic()) {
3547 if (!BD->param_empty()) S += ", ";
3548 S += "...";
3549 }
3550 S += ')';
3551 }
3552 S += " {\n";
3553
3554 // Create local declarations to avoid rewriting all closure decl ref exprs.
3555 // First, emit a declaration for all "by ref" decls.
3556 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3557 E = BlockByRefDecls.end(); I != E; ++I) {
3558 S += " ";
3559 std::string Name = (*I)->getNameAsString();
3560 std::string TypeString;
3561 RewriteByRefString(TypeString, Name, (*I));
3562 TypeString += " *";
3563 Name = TypeString + Name;
3564 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3565 }
3566 // Next, emit a declaration for all "by copy" declarations.
3567 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3568 E = BlockByCopyDecls.end(); I != E; ++I) {
3569 S += " ";
3570 // Handle nested closure invocation. For example:
3571 //
3572 // void (^myImportedClosure)(void);
3573 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3574 //
3575 // void (^anotherClosure)(void);
3576 // anotherClosure = ^(void) {
3577 // myImportedClosure(); // import and invoke the closure
3578 // };
3579 //
3580 if (isTopLevelBlockPointerType((*I)->getType())) {
3581 RewriteBlockPointerTypeVariable(S, (*I));
3582 S += " = (";
3583 RewriteBlockPointerType(S, (*I)->getType());
3584 S += ")";
3585 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3586 }
3587 else {
3588 std::string Name = (*I)->getNameAsString();
3589 QualType QT = (*I)->getType();
3590 if (HasLocalVariableExternalStorage(*I))
3591 QT = Context->getPointerType(QT);
3592 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3593 S += Name + " = __cself->" +
3594 (*I)->getNameAsString() + "; // bound by copy\n";
3595 }
3596 }
3597 std::string RewrittenStr = RewrittenBlockExprs[CE];
3598 const char *cstr = RewrittenStr.c_str();
3599 while (*cstr++ != '{') ;
3600 S += cstr;
3601 S += "\n";
3602 return S;
3603}
3604
3605std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3606 StringRef funcName,
3607 std::string Tag) {
3608 std::string StructRef = "struct " + Tag;
3609 std::string S = "static void __";
3610
3611 S += funcName;
3612 S += "_block_copy_" + utostr(i);
3613 S += "(" + StructRef;
3614 S += "*dst, " + StructRef;
3615 S += "*src) {";
3616 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3617 E = ImportedBlockDecls.end(); I != E; ++I) {
3618 ValueDecl *VD = (*I);
3619 S += "_Block_object_assign((void*)&dst->";
3620 S += (*I)->getNameAsString();
3621 S += ", (void*)src->";
3622 S += (*I)->getNameAsString();
3623 if (BlockByRefDeclsPtrSet.count((*I)))
3624 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3625 else if (VD->getType()->isBlockPointerType())
3626 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3627 else
3628 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3629 }
3630 S += "}\n";
3631
3632 S += "\nstatic void __";
3633 S += funcName;
3634 S += "_block_dispose_" + utostr(i);
3635 S += "(" + StructRef;
3636 S += "*src) {";
3637 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3638 E = ImportedBlockDecls.end(); I != E; ++I) {
3639 ValueDecl *VD = (*I);
3640 S += "_Block_object_dispose((void*)src->";
3641 S += (*I)->getNameAsString();
3642 if (BlockByRefDeclsPtrSet.count((*I)))
3643 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3644 else if (VD->getType()->isBlockPointerType())
3645 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3646 else
3647 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3648 }
3649 S += "}\n";
3650 return S;
3651}
3652
3653std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3654 std::string Desc) {
3655 std::string S = "\nstruct " + Tag;
3656 std::string Constructor = " " + Tag;
3657
3658 S += " {\n struct __block_impl impl;\n";
3659 S += " struct " + Desc;
3660 S += "* Desc;\n";
3661
3662 Constructor += "(void *fp, "; // Invoke function pointer.
3663 Constructor += "struct " + Desc; // Descriptor pointer.
3664 Constructor += " *desc";
3665
3666 if (BlockDeclRefs.size()) {
3667 // Output all "by copy" declarations.
3668 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3669 E = BlockByCopyDecls.end(); I != E; ++I) {
3670 S += " ";
3671 std::string FieldName = (*I)->getNameAsString();
3672 std::string ArgName = "_" + FieldName;
3673 // Handle nested closure invocation. For example:
3674 //
3675 // void (^myImportedBlock)(void);
3676 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3677 //
3678 // void (^anotherBlock)(void);
3679 // anotherBlock = ^(void) {
3680 // myImportedBlock(); // import and invoke the closure
3681 // };
3682 //
3683 if (isTopLevelBlockPointerType((*I)->getType())) {
3684 S += "struct __block_impl *";
3685 Constructor += ", void *" + ArgName;
3686 } else {
3687 QualType QT = (*I)->getType();
3688 if (HasLocalVariableExternalStorage(*I))
3689 QT = Context->getPointerType(QT);
3690 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3691 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3692 Constructor += ", " + ArgName;
3693 }
3694 S += FieldName + ";\n";
3695 }
3696 // Output all "by ref" declarations.
3697 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3698 E = BlockByRefDecls.end(); I != E; ++I) {
3699 S += " ";
3700 std::string FieldName = (*I)->getNameAsString();
3701 std::string ArgName = "_" + FieldName;
3702 {
3703 std::string TypeString;
3704 RewriteByRefString(TypeString, FieldName, (*I));
3705 TypeString += " *";
3706 FieldName = TypeString + FieldName;
3707 ArgName = TypeString + ArgName;
3708 Constructor += ", " + ArgName;
3709 }
3710 S += FieldName + "; // by ref\n";
3711 }
3712 // Finish writing the constructor.
3713 Constructor += ", int flags=0)";
3714 // Initialize all "by copy" arguments.
3715 bool firsTime = true;
3716 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3717 E = BlockByCopyDecls.end(); I != E; ++I) {
3718 std::string Name = (*I)->getNameAsString();
3719 if (firsTime) {
3720 Constructor += " : ";
3721 firsTime = false;
3722 }
3723 else
3724 Constructor += ", ";
3725 if (isTopLevelBlockPointerType((*I)->getType()))
3726 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3727 else
3728 Constructor += Name + "(_" + Name + ")";
3729 }
3730 // Initialize all "by ref" arguments.
3731 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3732 E = BlockByRefDecls.end(); I != E; ++I) {
3733 std::string Name = (*I)->getNameAsString();
3734 if (firsTime) {
3735 Constructor += " : ";
3736 firsTime = false;
3737 }
3738 else
3739 Constructor += ", ";
3740 Constructor += Name + "(_" + Name + "->__forwarding)";
3741 }
3742
3743 Constructor += " {\n";
3744 if (GlobalVarDecl)
3745 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3746 else
3747 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3748 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3749
3750 Constructor += " Desc = desc;\n";
3751 } else {
3752 // Finish writing the constructor.
3753 Constructor += ", int flags=0) {\n";
3754 if (GlobalVarDecl)
3755 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3756 else
3757 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3758 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3759 Constructor += " Desc = desc;\n";
3760 }
3761 Constructor += " ";
3762 Constructor += "}\n";
3763 S += Constructor;
3764 S += "};\n";
3765 return S;
3766}
3767
3768std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3769 std::string ImplTag, int i,
3770 StringRef FunName,
3771 unsigned hasCopy) {
3772 std::string S = "\nstatic struct " + DescTag;
3773
3774 S += " {\n unsigned long reserved;\n";
3775 S += " unsigned long Block_size;\n";
3776 if (hasCopy) {
3777 S += " void (*copy)(struct ";
3778 S += ImplTag; S += "*, struct ";
3779 S += ImplTag; S += "*);\n";
3780
3781 S += " void (*dispose)(struct ";
3782 S += ImplTag; S += "*);\n";
3783 }
3784 S += "} ";
3785
3786 S += DescTag + "_DATA = { 0, sizeof(struct ";
3787 S += ImplTag + ")";
3788 if (hasCopy) {
3789 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3790 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3791 }
3792 S += "};\n";
3793 return S;
3794}
3795
3796void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3797 StringRef FunName) {
3798 // Insert declaration for the function in which block literal is used.
3799 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3800 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3801 bool RewriteSC = (GlobalVarDecl &&
3802 !Blocks.empty() &&
3803 GlobalVarDecl->getStorageClass() == SC_Static &&
3804 GlobalVarDecl->getType().getCVRQualifiers());
3805 if (RewriteSC) {
3806 std::string SC(" void __");
3807 SC += GlobalVarDecl->getNameAsString();
3808 SC += "() {}";
3809 InsertText(FunLocStart, SC);
3810 }
3811
3812 // Insert closures that were part of the function.
3813 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3814 CollectBlockDeclRefInfo(Blocks[i]);
3815 // Need to copy-in the inner copied-in variables not actually used in this
3816 // block.
3817 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003818 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003819 ValueDecl *VD = Exp->getDecl();
3820 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003821 if (!VD->hasAttr<BlocksAttr>()) {
3822 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3823 BlockByCopyDeclsPtrSet.insert(VD);
3824 BlockByCopyDecls.push_back(VD);
3825 }
3826 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003827 }
John McCallf4b88a42012-03-10 09:33:50 +00003828
3829 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003830 BlockByRefDeclsPtrSet.insert(VD);
3831 BlockByRefDecls.push_back(VD);
3832 }
John McCallf4b88a42012-03-10 09:33:50 +00003833
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003834 // imported objects in the inner blocks not used in the outer
3835 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003836 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003837 VD->getType()->isBlockPointerType())
3838 ImportedBlockDecls.insert(VD);
3839 }
3840
3841 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3842 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3843
3844 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3845
3846 InsertText(FunLocStart, CI);
3847
3848 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3849
3850 InsertText(FunLocStart, CF);
3851
3852 if (ImportedBlockDecls.size()) {
3853 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3854 InsertText(FunLocStart, HF);
3855 }
3856 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3857 ImportedBlockDecls.size() > 0);
3858 InsertText(FunLocStart, BD);
3859
3860 BlockDeclRefs.clear();
3861 BlockByRefDecls.clear();
3862 BlockByRefDeclsPtrSet.clear();
3863 BlockByCopyDecls.clear();
3864 BlockByCopyDeclsPtrSet.clear();
3865 ImportedBlockDecls.clear();
3866 }
3867 if (RewriteSC) {
3868 // Must insert any 'const/volatile/static here. Since it has been
3869 // removed as result of rewriting of block literals.
3870 std::string SC;
3871 if (GlobalVarDecl->getStorageClass() == SC_Static)
3872 SC = "static ";
3873 if (GlobalVarDecl->getType().isConstQualified())
3874 SC += "const ";
3875 if (GlobalVarDecl->getType().isVolatileQualified())
3876 SC += "volatile ";
3877 if (GlobalVarDecl->getType().isRestrictQualified())
3878 SC += "restrict ";
3879 InsertText(FunLocStart, SC);
3880 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003881 if (GlobalConstructionExp) {
3882 // extra fancy dance for global literal expression.
3883
3884 // Always the latest block expression on the block stack.
3885 std::string Tag = "__";
3886 Tag += FunName;
3887 Tag += "_block_impl_";
3888 Tag += utostr(Blocks.size()-1);
3889 std::string globalBuf = "static ";
3890 globalBuf += Tag; globalBuf += " ";
3891 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003892
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003893 llvm::raw_string_ostream constructorExprBuf(SStr);
3894 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3895 PrintingPolicy(LangOpts));
3896 globalBuf += constructorExprBuf.str();
3897 globalBuf += ";\n";
3898 InsertText(FunLocStart, globalBuf);
3899 GlobalConstructionExp = 0;
3900 }
3901
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003902 Blocks.clear();
3903 InnerDeclRefsCount.clear();
3904 InnerDeclRefs.clear();
3905 RewrittenBlockExprs.clear();
3906}
3907
3908void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3909 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3910 StringRef FuncName = FD->getName();
3911
3912 SynthesizeBlockLiterals(FunLocStart, FuncName);
3913}
3914
3915static void BuildUniqueMethodName(std::string &Name,
3916 ObjCMethodDecl *MD) {
3917 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3918 Name = IFace->getName();
3919 Name += "__" + MD->getSelector().getAsString();
3920 // Convert colons to underscores.
3921 std::string::size_type loc = 0;
3922 while ((loc = Name.find(":", loc)) != std::string::npos)
3923 Name.replace(loc, 1, "_");
3924}
3925
3926void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3927 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3928 //SourceLocation FunLocStart = MD->getLocStart();
3929 SourceLocation FunLocStart = MD->getLocStart();
3930 std::string FuncName;
3931 BuildUniqueMethodName(FuncName, MD);
3932 SynthesizeBlockLiterals(FunLocStart, FuncName);
3933}
3934
3935void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3936 for (Stmt::child_range CI = S->children(); CI; ++CI)
3937 if (*CI) {
3938 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3939 GetBlockDeclRefExprs(CBE->getBody());
3940 else
3941 GetBlockDeclRefExprs(*CI);
3942 }
3943 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003944 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3945 if (DRE->refersToEnclosingLocal() &&
3946 HasLocalVariableExternalStorage(DRE->getDecl())) {
3947 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003948 }
3949
3950 return;
3951}
3952
3953void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003954 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003955 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3956 for (Stmt::child_range CI = S->children(); CI; ++CI)
3957 if (*CI) {
3958 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3959 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3960 GetInnerBlockDeclRefExprs(CBE->getBody(),
3961 InnerBlockDeclRefs,
3962 InnerContexts);
3963 }
3964 else
3965 GetInnerBlockDeclRefExprs(*CI,
3966 InnerBlockDeclRefs,
3967 InnerContexts);
3968
3969 }
3970 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003971 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3972 if (DRE->refersToEnclosingLocal()) {
3973 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3974 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3975 InnerBlockDeclRefs.push_back(DRE);
3976 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3977 if (Var->isFunctionOrMethodVarDecl())
3978 ImportedLocalExternalDecls.insert(Var);
3979 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003980 }
3981
3982 return;
3983}
3984
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003985/// convertObjCTypeToCStyleType - This routine converts such objc types
3986/// as qualified objects, and blocks to their closest c/c++ types that
3987/// it can. It returns true if input type was modified.
3988bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3989 QualType oldT = T;
3990 convertBlockPointerToFunctionPointer(T);
3991 if (T->isFunctionPointerType()) {
3992 QualType PointeeTy;
3993 if (const PointerType* PT = T->getAs<PointerType>()) {
3994 PointeeTy = PT->getPointeeType();
3995 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3996 T = convertFunctionTypeOfBlocks(FT);
3997 T = Context->getPointerType(T);
3998 }
3999 }
4000 }
4001
4002 convertToUnqualifiedObjCType(T);
4003 return T != oldT;
4004}
4005
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004006/// convertFunctionTypeOfBlocks - This routine converts a function type
4007/// whose result type may be a block pointer or whose argument type(s)
4008/// might be block pointers to an equivalent function type replacing
4009/// all block pointers to function pointers.
4010QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4011 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4012 // FTP will be null for closures that don't take arguments.
4013 // Generate a funky cast.
4014 SmallVector<QualType, 8> ArgTypes;
4015 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004016 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004017
4018 if (FTP) {
4019 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4020 E = FTP->arg_type_end(); I && (I != E); ++I) {
4021 QualType t = *I;
4022 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004023 if (convertObjCTypeToCStyleType(t))
4024 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004025 ArgTypes.push_back(t);
4026 }
4027 }
4028 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004029 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004030 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4031 else FuncType = QualType(FT, 0);
4032 return FuncType;
4033}
4034
4035Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4036 // Navigate to relevant type information.
4037 const BlockPointerType *CPT = 0;
4038
4039 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4040 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004041 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4042 CPT = MExpr->getType()->getAs<BlockPointerType>();
4043 }
4044 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4045 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4046 }
4047 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4048 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4049 else if (const ConditionalOperator *CEXPR =
4050 dyn_cast<ConditionalOperator>(BlockExp)) {
4051 Expr *LHSExp = CEXPR->getLHS();
4052 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4053 Expr *RHSExp = CEXPR->getRHS();
4054 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4055 Expr *CONDExp = CEXPR->getCond();
4056 ConditionalOperator *CondExpr =
4057 new (Context) ConditionalOperator(CONDExp,
4058 SourceLocation(), cast<Expr>(LHSStmt),
4059 SourceLocation(), cast<Expr>(RHSStmt),
4060 Exp->getType(), VK_RValue, OK_Ordinary);
4061 return CondExpr;
4062 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4063 CPT = IRE->getType()->getAs<BlockPointerType>();
4064 } else if (const PseudoObjectExpr *POE
4065 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4066 CPT = POE->getType()->castAs<BlockPointerType>();
4067 } else {
4068 assert(1 && "RewriteBlockClass: Bad type");
4069 }
4070 assert(CPT && "RewriteBlockClass: Bad type");
4071 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4072 assert(FT && "RewriteBlockClass: Bad type");
4073 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4074 // FTP will be null for closures that don't take arguments.
4075
4076 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4077 SourceLocation(), SourceLocation(),
4078 &Context->Idents.get("__block_impl"));
4079 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4080
4081 // Generate a funky cast.
4082 SmallVector<QualType, 8> ArgTypes;
4083
4084 // Push the block argument type.
4085 ArgTypes.push_back(PtrBlock);
4086 if (FTP) {
4087 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4088 E = FTP->arg_type_end(); I && (I != E); ++I) {
4089 QualType t = *I;
4090 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4091 if (!convertBlockPointerToFunctionPointer(t))
4092 convertToUnqualifiedObjCType(t);
4093 ArgTypes.push_back(t);
4094 }
4095 }
4096 // Now do the pointer to function cast.
4097 QualType PtrToFuncCastType
4098 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4099
4100 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4101
4102 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4103 CK_BitCast,
4104 const_cast<Expr*>(BlockExp));
4105 // Don't forget the parens to enforce the proper binding.
4106 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4107 BlkCast);
4108 //PE->dump();
4109
4110 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4111 SourceLocation(),
4112 &Context->Idents.get("FuncPtr"),
4113 Context->VoidPtrTy, 0,
4114 /*BitWidth=*/0, /*Mutable=*/true,
4115 /*HasInit=*/false);
4116 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4117 FD->getType(), VK_LValue,
4118 OK_Ordinary);
4119
4120
4121 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4122 CK_BitCast, ME);
4123 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4124
4125 SmallVector<Expr*, 8> BlkExprs;
4126 // Add the implicit argument.
4127 BlkExprs.push_back(BlkCast);
4128 // Add the user arguments.
4129 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4130 E = Exp->arg_end(); I != E; ++I) {
4131 BlkExprs.push_back(*I);
4132 }
4133 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4134 BlkExprs.size(),
4135 Exp->getType(), VK_RValue,
4136 SourceLocation());
4137 return CE;
4138}
4139
4140// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004141// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004142// For example:
4143//
4144// int main() {
4145// __block Foo *f;
4146// __block int i;
4147//
4148// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004149// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004150// i = 77;
4151// };
4152//}
John McCallf4b88a42012-03-10 09:33:50 +00004153Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004154 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4155 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004156 ValueDecl *VD = DeclRefExp->getDecl();
4157 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004158
4159 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4160 SourceLocation(),
4161 &Context->Idents.get("__forwarding"),
4162 Context->VoidPtrTy, 0,
4163 /*BitWidth=*/0, /*Mutable=*/true,
4164 /*HasInit=*/false);
4165 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4166 FD, SourceLocation(),
4167 FD->getType(), VK_LValue,
4168 OK_Ordinary);
4169
4170 StringRef Name = VD->getName();
4171 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4172 &Context->Idents.get(Name),
4173 Context->VoidPtrTy, 0,
4174 /*BitWidth=*/0, /*Mutable=*/true,
4175 /*HasInit=*/false);
4176 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4177 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4178
4179
4180
4181 // Need parens to enforce precedence.
4182 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4183 DeclRefExp->getExprLoc(),
4184 ME);
4185 ReplaceStmt(DeclRefExp, PE);
4186 return PE;
4187}
4188
4189// Rewrites the imported local variable V with external storage
4190// (static, extern, etc.) as *V
4191//
4192Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4193 ValueDecl *VD = DRE->getDecl();
4194 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4195 if (!ImportedLocalExternalDecls.count(Var))
4196 return DRE;
4197 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4198 VK_LValue, OK_Ordinary,
4199 DRE->getLocation());
4200 // Need parens to enforce precedence.
4201 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4202 Exp);
4203 ReplaceStmt(DRE, PE);
4204 return PE;
4205}
4206
4207void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4208 SourceLocation LocStart = CE->getLParenLoc();
4209 SourceLocation LocEnd = CE->getRParenLoc();
4210
4211 // Need to avoid trying to rewrite synthesized casts.
4212 if (LocStart.isInvalid())
4213 return;
4214 // Need to avoid trying to rewrite casts contained in macros.
4215 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4216 return;
4217
4218 const char *startBuf = SM->getCharacterData(LocStart);
4219 const char *endBuf = SM->getCharacterData(LocEnd);
4220 QualType QT = CE->getType();
4221 const Type* TypePtr = QT->getAs<Type>();
4222 if (isa<TypeOfExprType>(TypePtr)) {
4223 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4224 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4225 std::string TypeAsString = "(";
4226 RewriteBlockPointerType(TypeAsString, QT);
4227 TypeAsString += ")";
4228 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4229 return;
4230 }
4231 // advance the location to startArgList.
4232 const char *argPtr = startBuf;
4233
4234 while (*argPtr++ && (argPtr < endBuf)) {
4235 switch (*argPtr) {
4236 case '^':
4237 // Replace the '^' with '*'.
4238 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4239 ReplaceText(LocStart, 1, "*");
4240 break;
4241 }
4242 }
4243 return;
4244}
4245
4246void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4247 SourceLocation DeclLoc = FD->getLocation();
4248 unsigned parenCount = 0;
4249
4250 // We have 1 or more arguments that have closure pointers.
4251 const char *startBuf = SM->getCharacterData(DeclLoc);
4252 const char *startArgList = strchr(startBuf, '(');
4253
4254 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4255
4256 parenCount++;
4257 // advance the location to startArgList.
4258 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4259 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4260
4261 const char *argPtr = startArgList;
4262
4263 while (*argPtr++ && parenCount) {
4264 switch (*argPtr) {
4265 case '^':
4266 // Replace the '^' with '*'.
4267 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4268 ReplaceText(DeclLoc, 1, "*");
4269 break;
4270 case '(':
4271 parenCount++;
4272 break;
4273 case ')':
4274 parenCount--;
4275 break;
4276 }
4277 }
4278 return;
4279}
4280
4281bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4282 const FunctionProtoType *FTP;
4283 const PointerType *PT = QT->getAs<PointerType>();
4284 if (PT) {
4285 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4286 } else {
4287 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4288 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4289 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4290 }
4291 if (FTP) {
4292 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4293 E = FTP->arg_type_end(); I != E; ++I)
4294 if (isTopLevelBlockPointerType(*I))
4295 return true;
4296 }
4297 return false;
4298}
4299
4300bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4301 const FunctionProtoType *FTP;
4302 const PointerType *PT = QT->getAs<PointerType>();
4303 if (PT) {
4304 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4305 } else {
4306 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4307 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4308 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4309 }
4310 if (FTP) {
4311 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4312 E = FTP->arg_type_end(); I != E; ++I) {
4313 if ((*I)->isObjCQualifiedIdType())
4314 return true;
4315 if ((*I)->isObjCObjectPointerType() &&
4316 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4317 return true;
4318 }
4319
4320 }
4321 return false;
4322}
4323
4324void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4325 const char *&RParen) {
4326 const char *argPtr = strchr(Name, '(');
4327 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4328
4329 LParen = argPtr; // output the start.
4330 argPtr++; // skip past the left paren.
4331 unsigned parenCount = 1;
4332
4333 while (*argPtr && parenCount) {
4334 switch (*argPtr) {
4335 case '(': parenCount++; break;
4336 case ')': parenCount--; break;
4337 default: break;
4338 }
4339 if (parenCount) argPtr++;
4340 }
4341 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4342 RParen = argPtr; // output the end
4343}
4344
4345void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4346 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4347 RewriteBlockPointerFunctionArgs(FD);
4348 return;
4349 }
4350 // Handle Variables and Typedefs.
4351 SourceLocation DeclLoc = ND->getLocation();
4352 QualType DeclT;
4353 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4354 DeclT = VD->getType();
4355 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4356 DeclT = TDD->getUnderlyingType();
4357 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4358 DeclT = FD->getType();
4359 else
4360 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4361
4362 const char *startBuf = SM->getCharacterData(DeclLoc);
4363 const char *endBuf = startBuf;
4364 // scan backward (from the decl location) for the end of the previous decl.
4365 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4366 startBuf--;
4367 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4368 std::string buf;
4369 unsigned OrigLength=0;
4370 // *startBuf != '^' if we are dealing with a pointer to function that
4371 // may take block argument types (which will be handled below).
4372 if (*startBuf == '^') {
4373 // Replace the '^' with '*', computing a negative offset.
4374 buf = '*';
4375 startBuf++;
4376 OrigLength++;
4377 }
4378 while (*startBuf != ')') {
4379 buf += *startBuf;
4380 startBuf++;
4381 OrigLength++;
4382 }
4383 buf += ')';
4384 OrigLength++;
4385
4386 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4387 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4388 // Replace the '^' with '*' for arguments.
4389 // Replace id<P> with id/*<>*/
4390 DeclLoc = ND->getLocation();
4391 startBuf = SM->getCharacterData(DeclLoc);
4392 const char *argListBegin, *argListEnd;
4393 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4394 while (argListBegin < argListEnd) {
4395 if (*argListBegin == '^')
4396 buf += '*';
4397 else if (*argListBegin == '<') {
4398 buf += "/*";
4399 buf += *argListBegin++;
4400 OrigLength++;;
4401 while (*argListBegin != '>') {
4402 buf += *argListBegin++;
4403 OrigLength++;
4404 }
4405 buf += *argListBegin;
4406 buf += "*/";
4407 }
4408 else
4409 buf += *argListBegin;
4410 argListBegin++;
4411 OrigLength++;
4412 }
4413 buf += ')';
4414 OrigLength++;
4415 }
4416 ReplaceText(Start, OrigLength, buf);
4417
4418 return;
4419}
4420
4421
4422/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4423/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4424/// struct Block_byref_id_object *src) {
4425/// _Block_object_assign (&_dest->object, _src->object,
4426/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4427/// [|BLOCK_FIELD_IS_WEAK]) // object
4428/// _Block_object_assign(&_dest->object, _src->object,
4429/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4430/// [|BLOCK_FIELD_IS_WEAK]) // block
4431/// }
4432/// And:
4433/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4434/// _Block_object_dispose(_src->object,
4435/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4436/// [|BLOCK_FIELD_IS_WEAK]) // object
4437/// _Block_object_dispose(_src->object,
4438/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4439/// [|BLOCK_FIELD_IS_WEAK]) // block
4440/// }
4441
4442std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4443 int flag) {
4444 std::string S;
4445 if (CopyDestroyCache.count(flag))
4446 return S;
4447 CopyDestroyCache.insert(flag);
4448 S = "static void __Block_byref_id_object_copy_";
4449 S += utostr(flag);
4450 S += "(void *dst, void *src) {\n";
4451
4452 // offset into the object pointer is computed as:
4453 // void * + void* + int + int + void* + void *
4454 unsigned IntSize =
4455 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4456 unsigned VoidPtrSize =
4457 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4458
4459 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4460 S += " _Block_object_assign((char*)dst + ";
4461 S += utostr(offset);
4462 S += ", *(void * *) ((char*)src + ";
4463 S += utostr(offset);
4464 S += "), ";
4465 S += utostr(flag);
4466 S += ");\n}\n";
4467
4468 S += "static void __Block_byref_id_object_dispose_";
4469 S += utostr(flag);
4470 S += "(void *src) {\n";
4471 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4472 S += utostr(offset);
4473 S += "), ";
4474 S += utostr(flag);
4475 S += ");\n}\n";
4476 return S;
4477}
4478
4479/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4480/// the declaration into:
4481/// struct __Block_byref_ND {
4482/// void *__isa; // NULL for everything except __weak pointers
4483/// struct __Block_byref_ND *__forwarding;
4484/// int32_t __flags;
4485/// int32_t __size;
4486/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4487/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4488/// typex ND;
4489/// };
4490///
4491/// It then replaces declaration of ND variable with:
4492/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4493/// __size=sizeof(struct __Block_byref_ND),
4494/// ND=initializer-if-any};
4495///
4496///
4497void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4498 // Insert declaration for the function in which block literal is
4499 // used.
4500 if (CurFunctionDeclToDeclareForBlock)
4501 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4502 int flag = 0;
4503 int isa = 0;
4504 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4505 if (DeclLoc.isInvalid())
4506 // If type location is missing, it is because of missing type (a warning).
4507 // Use variable's location which is good for this case.
4508 DeclLoc = ND->getLocation();
4509 const char *startBuf = SM->getCharacterData(DeclLoc);
4510 SourceLocation X = ND->getLocEnd();
4511 X = SM->getExpansionLoc(X);
4512 const char *endBuf = SM->getCharacterData(X);
4513 std::string Name(ND->getNameAsString());
4514 std::string ByrefType;
4515 RewriteByRefString(ByrefType, Name, ND, true);
4516 ByrefType += " {\n";
4517 ByrefType += " void *__isa;\n";
4518 RewriteByRefString(ByrefType, Name, ND);
4519 ByrefType += " *__forwarding;\n";
4520 ByrefType += " int __flags;\n";
4521 ByrefType += " int __size;\n";
4522 // Add void *__Block_byref_id_object_copy;
4523 // void *__Block_byref_id_object_dispose; if needed.
4524 QualType Ty = ND->getType();
4525 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4526 if (HasCopyAndDispose) {
4527 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4528 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4529 }
4530
4531 QualType T = Ty;
4532 (void)convertBlockPointerToFunctionPointer(T);
4533 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4534
4535 ByrefType += " " + Name + ";\n";
4536 ByrefType += "};\n";
4537 // Insert this type in global scope. It is needed by helper function.
4538 SourceLocation FunLocStart;
4539 if (CurFunctionDef)
4540 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4541 else {
4542 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4543 FunLocStart = CurMethodDef->getLocStart();
4544 }
4545 InsertText(FunLocStart, ByrefType);
4546 if (Ty.isObjCGCWeak()) {
4547 flag |= BLOCK_FIELD_IS_WEAK;
4548 isa = 1;
4549 }
4550
4551 if (HasCopyAndDispose) {
4552 flag = BLOCK_BYREF_CALLER;
4553 QualType Ty = ND->getType();
4554 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4555 if (Ty->isBlockPointerType())
4556 flag |= BLOCK_FIELD_IS_BLOCK;
4557 else
4558 flag |= BLOCK_FIELD_IS_OBJECT;
4559 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4560 if (!HF.empty())
4561 InsertText(FunLocStart, HF);
4562 }
4563
4564 // struct __Block_byref_ND ND =
4565 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4566 // initializer-if-any};
4567 bool hasInit = (ND->getInit() != 0);
4568 unsigned flags = 0;
4569 if (HasCopyAndDispose)
4570 flags |= BLOCK_HAS_COPY_DISPOSE;
4571 Name = ND->getNameAsString();
4572 ByrefType.clear();
4573 RewriteByRefString(ByrefType, Name, ND);
4574 std::string ForwardingCastType("(");
4575 ForwardingCastType += ByrefType + " *)";
4576 if (!hasInit) {
4577 ByrefType += " " + Name + " = {(void*)";
4578 ByrefType += utostr(isa);
4579 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4580 ByrefType += utostr(flags);
4581 ByrefType += ", ";
4582 ByrefType += "sizeof(";
4583 RewriteByRefString(ByrefType, Name, ND);
4584 ByrefType += ")";
4585 if (HasCopyAndDispose) {
4586 ByrefType += ", __Block_byref_id_object_copy_";
4587 ByrefType += utostr(flag);
4588 ByrefType += ", __Block_byref_id_object_dispose_";
4589 ByrefType += utostr(flag);
4590 }
4591 ByrefType += "};\n";
4592 unsigned nameSize = Name.size();
4593 // for block or function pointer declaration. Name is aleady
4594 // part of the declaration.
4595 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4596 nameSize = 1;
4597 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4598 }
4599 else {
4600 SourceLocation startLoc;
4601 Expr *E = ND->getInit();
4602 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4603 startLoc = ECE->getLParenLoc();
4604 else
4605 startLoc = E->getLocStart();
4606 startLoc = SM->getExpansionLoc(startLoc);
4607 endBuf = SM->getCharacterData(startLoc);
4608 ByrefType += " " + Name;
4609 ByrefType += " = {(void*)";
4610 ByrefType += utostr(isa);
4611 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4612 ByrefType += utostr(flags);
4613 ByrefType += ", ";
4614 ByrefType += "sizeof(";
4615 RewriteByRefString(ByrefType, Name, ND);
4616 ByrefType += "), ";
4617 if (HasCopyAndDispose) {
4618 ByrefType += "__Block_byref_id_object_copy_";
4619 ByrefType += utostr(flag);
4620 ByrefType += ", __Block_byref_id_object_dispose_";
4621 ByrefType += utostr(flag);
4622 ByrefType += ", ";
4623 }
4624 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4625
4626 // Complete the newly synthesized compound expression by inserting a right
4627 // curly brace before the end of the declaration.
4628 // FIXME: This approach avoids rewriting the initializer expression. It
4629 // also assumes there is only one declarator. For example, the following
4630 // isn't currently supported by this routine (in general):
4631 //
4632 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4633 //
4634 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4635 const char *semiBuf = strchr(startInitializerBuf, ';');
4636 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4637 SourceLocation semiLoc =
4638 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4639
4640 InsertText(semiLoc, "}");
4641 }
4642 return;
4643}
4644
4645void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4646 // Add initializers for any closure decl refs.
4647 GetBlockDeclRefExprs(Exp->getBody());
4648 if (BlockDeclRefs.size()) {
4649 // Unique all "by copy" declarations.
4650 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004651 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004652 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4653 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4654 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4655 }
4656 }
4657 // Unique all "by ref" declarations.
4658 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004659 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004660 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4661 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4662 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4663 }
4664 }
4665 // Find any imported blocks...they will need special attention.
4666 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004667 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004668 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4669 BlockDeclRefs[i]->getType()->isBlockPointerType())
4670 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4671 }
4672}
4673
4674FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4675 IdentifierInfo *ID = &Context->Idents.get(name);
4676 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4677 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4678 SourceLocation(), ID, FType, 0, SC_Extern,
4679 SC_None, false, false);
4680}
4681
4682Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004683 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004684
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004685 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004686
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004687 Blocks.push_back(Exp);
4688
4689 CollectBlockDeclRefInfo(Exp);
4690
4691 // Add inner imported variables now used in current block.
4692 int countOfInnerDecls = 0;
4693 if (!InnerBlockDeclRefs.empty()) {
4694 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004695 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004696 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004697 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004698 // We need to save the copied-in variables in nested
4699 // blocks because it is needed at the end for some of the API generations.
4700 // See SynthesizeBlockLiterals routine.
4701 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4702 BlockDeclRefs.push_back(Exp);
4703 BlockByCopyDeclsPtrSet.insert(VD);
4704 BlockByCopyDecls.push_back(VD);
4705 }
John McCallf4b88a42012-03-10 09:33:50 +00004706 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004707 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4708 BlockDeclRefs.push_back(Exp);
4709 BlockByRefDeclsPtrSet.insert(VD);
4710 BlockByRefDecls.push_back(VD);
4711 }
4712 }
4713 // Find any imported blocks...they will need special attention.
4714 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004715 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004716 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4717 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4718 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4719 }
4720 InnerDeclRefsCount.push_back(countOfInnerDecls);
4721
4722 std::string FuncName;
4723
4724 if (CurFunctionDef)
4725 FuncName = CurFunctionDef->getNameAsString();
4726 else if (CurMethodDef)
4727 BuildUniqueMethodName(FuncName, CurMethodDef);
4728 else if (GlobalVarDecl)
4729 FuncName = std::string(GlobalVarDecl->getNameAsString());
4730
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004731 bool GlobalBlockExpr =
4732 block->getDeclContext()->getRedeclContext()->isFileContext();
4733
4734 if (GlobalBlockExpr && !GlobalVarDecl) {
4735 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4736 GlobalBlockExpr = false;
4737 }
4738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004739 std::string BlockNumber = utostr(Blocks.size()-1);
4740
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004741 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4742
4743 // Get a pointer to the function type so we can cast appropriately.
4744 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4745 QualType FType = Context->getPointerType(BFT);
4746
4747 FunctionDecl *FD;
4748 Expr *NewRep;
4749
4750 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004751 std::string Tag;
4752
4753 if (GlobalBlockExpr)
4754 Tag = "__global_";
4755 else
4756 Tag = "__";
4757 Tag += FuncName + "_block_impl_" + BlockNumber;
4758
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004759 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004760 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004761 SourceLocation());
4762
4763 SmallVector<Expr*, 4> InitExprs;
4764
4765 // Initialize the block function.
4766 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004767 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4768 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004769 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4770 CK_BitCast, Arg);
4771 InitExprs.push_back(castExpr);
4772
4773 // Initialize the block descriptor.
4774 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4775
4776 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4777 SourceLocation(), SourceLocation(),
4778 &Context->Idents.get(DescData.c_str()),
4779 Context->VoidPtrTy, 0,
4780 SC_Static, SC_None);
4781 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004782 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004783 Context->VoidPtrTy,
4784 VK_LValue,
4785 SourceLocation()),
4786 UO_AddrOf,
4787 Context->getPointerType(Context->VoidPtrTy),
4788 VK_RValue, OK_Ordinary,
4789 SourceLocation());
4790 InitExprs.push_back(DescRefExpr);
4791
4792 // Add initializers for any closure decl refs.
4793 if (BlockDeclRefs.size()) {
4794 Expr *Exp;
4795 // Output all "by copy" declarations.
4796 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4797 E = BlockByCopyDecls.end(); I != E; ++I) {
4798 if (isObjCType((*I)->getType())) {
4799 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4800 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004801 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4802 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004803 if (HasLocalVariableExternalStorage(*I)) {
4804 QualType QT = (*I)->getType();
4805 QT = Context->getPointerType(QT);
4806 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4807 OK_Ordinary, SourceLocation());
4808 }
4809 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4810 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004811 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4812 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004813 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4814 CK_BitCast, Arg);
4815 } else {
4816 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004817 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4818 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004819 if (HasLocalVariableExternalStorage(*I)) {
4820 QualType QT = (*I)->getType();
4821 QT = Context->getPointerType(QT);
4822 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4823 OK_Ordinary, SourceLocation());
4824 }
4825
4826 }
4827 InitExprs.push_back(Exp);
4828 }
4829 // Output all "by ref" declarations.
4830 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4831 E = BlockByRefDecls.end(); I != E; ++I) {
4832 ValueDecl *ND = (*I);
4833 std::string Name(ND->getNameAsString());
4834 std::string RecName;
4835 RewriteByRefString(RecName, Name, ND, true);
4836 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4837 + sizeof("struct"));
4838 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4839 SourceLocation(), SourceLocation(),
4840 II);
4841 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4842 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4843
4844 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004845 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004846 SourceLocation());
4847 bool isNestedCapturedVar = false;
4848 if (block)
4849 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4850 ce = block->capture_end(); ci != ce; ++ci) {
4851 const VarDecl *variable = ci->getVariable();
4852 if (variable == ND && ci->isNested()) {
4853 assert (ci->isByRef() &&
4854 "SynthBlockInitExpr - captured block variable is not byref");
4855 isNestedCapturedVar = true;
4856 break;
4857 }
4858 }
4859 // captured nested byref variable has its address passed. Do not take
4860 // its address again.
4861 if (!isNestedCapturedVar)
4862 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4863 Context->getPointerType(Exp->getType()),
4864 VK_RValue, OK_Ordinary, SourceLocation());
4865 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4866 InitExprs.push_back(Exp);
4867 }
4868 }
4869 if (ImportedBlockDecls.size()) {
4870 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4871 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4872 unsigned IntSize =
4873 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4874 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4875 Context->IntTy, SourceLocation());
4876 InitExprs.push_back(FlagExp);
4877 }
4878 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4879 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004880
4881 if (GlobalBlockExpr) {
4882 assert (GlobalConstructionExp == 0 &&
4883 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4884 GlobalConstructionExp = NewRep;
4885 NewRep = DRE;
4886 }
4887
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004888 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4889 Context->getPointerType(NewRep->getType()),
4890 VK_RValue, OK_Ordinary, SourceLocation());
4891 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4892 NewRep);
4893 BlockDeclRefs.clear();
4894 BlockByRefDecls.clear();
4895 BlockByRefDeclsPtrSet.clear();
4896 BlockByCopyDecls.clear();
4897 BlockByCopyDeclsPtrSet.clear();
4898 ImportedBlockDecls.clear();
4899 return NewRep;
4900}
4901
4902bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4903 if (const ObjCForCollectionStmt * CS =
4904 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4905 return CS->getElement() == DS;
4906 return false;
4907}
4908
4909//===----------------------------------------------------------------------===//
4910// Function Body / Expression rewriting
4911//===----------------------------------------------------------------------===//
4912
4913Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4914 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4915 isa<DoStmt>(S) || isa<ForStmt>(S))
4916 Stmts.push_back(S);
4917 else if (isa<ObjCForCollectionStmt>(S)) {
4918 Stmts.push_back(S);
4919 ObjCBcLabelNo.push_back(++BcLabelCount);
4920 }
4921
4922 // Pseudo-object operations and ivar references need special
4923 // treatment because we're going to recursively rewrite them.
4924 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4925 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4926 return RewritePropertyOrImplicitSetter(PseudoOp);
4927 } else {
4928 return RewritePropertyOrImplicitGetter(PseudoOp);
4929 }
4930 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4931 return RewriteObjCIvarRefExpr(IvarRefExpr);
4932 }
4933
4934 SourceRange OrigStmtRange = S->getSourceRange();
4935
4936 // Perform a bottom up rewrite of all children.
4937 for (Stmt::child_range CI = S->children(); CI; ++CI)
4938 if (*CI) {
4939 Stmt *childStmt = (*CI);
4940 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4941 if (newStmt) {
4942 *CI = newStmt;
4943 }
4944 }
4945
4946 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004947 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004948 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4949 InnerContexts.insert(BE->getBlockDecl());
4950 ImportedLocalExternalDecls.clear();
4951 GetInnerBlockDeclRefExprs(BE->getBody(),
4952 InnerBlockDeclRefs, InnerContexts);
4953 // Rewrite the block body in place.
4954 Stmt *SaveCurrentBody = CurrentBody;
4955 CurrentBody = BE->getBody();
4956 PropParentMap = 0;
4957 // block literal on rhs of a property-dot-sytax assignment
4958 // must be replaced by its synthesize ast so getRewrittenText
4959 // works as expected. In this case, what actually ends up on RHS
4960 // is the blockTranscribed which is the helper function for the
4961 // block literal; as in: self.c = ^() {[ace ARR];};
4962 bool saveDisableReplaceStmt = DisableReplaceStmt;
4963 DisableReplaceStmt = false;
4964 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4965 DisableReplaceStmt = saveDisableReplaceStmt;
4966 CurrentBody = SaveCurrentBody;
4967 PropParentMap = 0;
4968 ImportedLocalExternalDecls.clear();
4969 // Now we snarf the rewritten text and stash it away for later use.
4970 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4971 RewrittenBlockExprs[BE] = Str;
4972
4973 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4974
4975 //blockTranscribed->dump();
4976 ReplaceStmt(S, blockTranscribed);
4977 return blockTranscribed;
4978 }
4979 // Handle specific things.
4980 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4981 return RewriteAtEncode(AtEncode);
4982
4983 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4984 return RewriteAtSelector(AtSelector);
4985
4986 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4987 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00004988
4989 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
4990 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00004991
4992 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
4993 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00004994
4995 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
4996 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004997
4998 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4999#if 0
5000 // Before we rewrite it, put the original message expression in a comment.
5001 SourceLocation startLoc = MessExpr->getLocStart();
5002 SourceLocation endLoc = MessExpr->getLocEnd();
5003
5004 const char *startBuf = SM->getCharacterData(startLoc);
5005 const char *endBuf = SM->getCharacterData(endLoc);
5006
5007 std::string messString;
5008 messString += "// ";
5009 messString.append(startBuf, endBuf-startBuf+1);
5010 messString += "\n";
5011
5012 // FIXME: Missing definition of
5013 // InsertText(clang::SourceLocation, char const*, unsigned int).
5014 // InsertText(startLoc, messString.c_str(), messString.size());
5015 // Tried this, but it didn't work either...
5016 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5017#endif
5018 return RewriteMessageExpr(MessExpr);
5019 }
5020
5021 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5022 return RewriteObjCTryStmt(StmtTry);
5023
5024 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5025 return RewriteObjCSynchronizedStmt(StmtTry);
5026
5027 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5028 return RewriteObjCThrowStmt(StmtThrow);
5029
5030 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5031 return RewriteObjCProtocolExpr(ProtocolExp);
5032
5033 if (ObjCForCollectionStmt *StmtForCollection =
5034 dyn_cast<ObjCForCollectionStmt>(S))
5035 return RewriteObjCForCollectionStmt(StmtForCollection,
5036 OrigStmtRange.getEnd());
5037 if (BreakStmt *StmtBreakStmt =
5038 dyn_cast<BreakStmt>(S))
5039 return RewriteBreakStmt(StmtBreakStmt);
5040 if (ContinueStmt *StmtContinueStmt =
5041 dyn_cast<ContinueStmt>(S))
5042 return RewriteContinueStmt(StmtContinueStmt);
5043
5044 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5045 // and cast exprs.
5046 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5047 // FIXME: What we're doing here is modifying the type-specifier that
5048 // precedes the first Decl. In the future the DeclGroup should have
5049 // a separate type-specifier that we can rewrite.
5050 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5051 // the context of an ObjCForCollectionStmt. For example:
5052 // NSArray *someArray;
5053 // for (id <FooProtocol> index in someArray) ;
5054 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5055 // and it depends on the original text locations/positions.
5056 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5057 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5058
5059 // Blocks rewrite rules.
5060 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5061 DI != DE; ++DI) {
5062 Decl *SD = *DI;
5063 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5064 if (isTopLevelBlockPointerType(ND->getType()))
5065 RewriteBlockPointerDecl(ND);
5066 else if (ND->getType()->isFunctionPointerType())
5067 CheckFunctionPointerDecl(ND->getType(), ND);
5068 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5069 if (VD->hasAttr<BlocksAttr>()) {
5070 static unsigned uniqueByrefDeclCount = 0;
5071 assert(!BlockByRefDeclNo.count(ND) &&
5072 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5073 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5074 RewriteByRefVar(VD);
5075 }
5076 else
5077 RewriteTypeOfDecl(VD);
5078 }
5079 }
5080 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5081 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5082 RewriteBlockPointerDecl(TD);
5083 else if (TD->getUnderlyingType()->isFunctionPointerType())
5084 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5085 }
5086 }
5087 }
5088
5089 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5090 RewriteObjCQualifiedInterfaceTypes(CE);
5091
5092 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5093 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5094 assert(!Stmts.empty() && "Statement stack is empty");
5095 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5096 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5097 && "Statement stack mismatch");
5098 Stmts.pop_back();
5099 }
5100 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005101 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5102 ValueDecl *VD = DRE->getDecl();
5103 if (VD->hasAttr<BlocksAttr>())
5104 return RewriteBlockDeclRefExpr(DRE);
5105 if (HasLocalVariableExternalStorage(VD))
5106 return RewriteLocalVariableExternalStorage(DRE);
5107 }
5108
5109 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5110 if (CE->getCallee()->getType()->isBlockPointerType()) {
5111 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5112 ReplaceStmt(S, BlockCall);
5113 return BlockCall;
5114 }
5115 }
5116 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5117 RewriteCastExpr(CE);
5118 }
5119#if 0
5120 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5121 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5122 ICE->getSubExpr(),
5123 SourceLocation());
5124 // Get the new text.
5125 std::string SStr;
5126 llvm::raw_string_ostream Buf(SStr);
5127 Replacement->printPretty(Buf, *Context);
5128 const std::string &Str = Buf.str();
5129
5130 printf("CAST = %s\n", &Str[0]);
5131 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5132 delete S;
5133 return Replacement;
5134 }
5135#endif
5136 // Return this stmt unmodified.
5137 return S;
5138}
5139
5140void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5141 for (RecordDecl::field_iterator i = RD->field_begin(),
5142 e = RD->field_end(); i != e; ++i) {
5143 FieldDecl *FD = *i;
5144 if (isTopLevelBlockPointerType(FD->getType()))
5145 RewriteBlockPointerDecl(FD);
5146 if (FD->getType()->isObjCQualifiedIdType() ||
5147 FD->getType()->isObjCQualifiedInterfaceType())
5148 RewriteObjCQualifiedInterfaceTypes(FD);
5149 }
5150}
5151
5152/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5153/// main file of the input.
5154void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5155 switch (D->getKind()) {
5156 case Decl::Function: {
5157 FunctionDecl *FD = cast<FunctionDecl>(D);
5158 if (FD->isOverloadedOperator())
5159 return;
5160
5161 // Since function prototypes don't have ParmDecl's, we check the function
5162 // prototype. This enables us to rewrite function declarations and
5163 // definitions using the same code.
5164 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5165
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005166 if (!FD->isThisDeclarationADefinition())
5167 break;
5168
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005169 // FIXME: If this should support Obj-C++, support CXXTryStmt
5170 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5171 CurFunctionDef = FD;
5172 CurFunctionDeclToDeclareForBlock = FD;
5173 CurrentBody = Body;
5174 Body =
5175 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5176 FD->setBody(Body);
5177 CurrentBody = 0;
5178 if (PropParentMap) {
5179 delete PropParentMap;
5180 PropParentMap = 0;
5181 }
5182 // This synthesizes and inserts the block "impl" struct, invoke function,
5183 // and any copy/dispose helper functions.
5184 InsertBlockLiteralsWithinFunction(FD);
5185 CurFunctionDef = 0;
5186 CurFunctionDeclToDeclareForBlock = 0;
5187 }
5188 break;
5189 }
5190 case Decl::ObjCMethod: {
5191 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5192 if (CompoundStmt *Body = MD->getCompoundBody()) {
5193 CurMethodDef = MD;
5194 CurrentBody = Body;
5195 Body =
5196 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5197 MD->setBody(Body);
5198 CurrentBody = 0;
5199 if (PropParentMap) {
5200 delete PropParentMap;
5201 PropParentMap = 0;
5202 }
5203 InsertBlockLiteralsWithinMethod(MD);
5204 CurMethodDef = 0;
5205 }
5206 break;
5207 }
5208 case Decl::ObjCImplementation: {
5209 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5210 ClassImplementation.push_back(CI);
5211 break;
5212 }
5213 case Decl::ObjCCategoryImpl: {
5214 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5215 CategoryImplementation.push_back(CI);
5216 break;
5217 }
5218 case Decl::Var: {
5219 VarDecl *VD = cast<VarDecl>(D);
5220 RewriteObjCQualifiedInterfaceTypes(VD);
5221 if (isTopLevelBlockPointerType(VD->getType()))
5222 RewriteBlockPointerDecl(VD);
5223 else if (VD->getType()->isFunctionPointerType()) {
5224 CheckFunctionPointerDecl(VD->getType(), VD);
5225 if (VD->getInit()) {
5226 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5227 RewriteCastExpr(CE);
5228 }
5229 }
5230 } else if (VD->getType()->isRecordType()) {
5231 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5232 if (RD->isCompleteDefinition())
5233 RewriteRecordBody(RD);
5234 }
5235 if (VD->getInit()) {
5236 GlobalVarDecl = VD;
5237 CurrentBody = VD->getInit();
5238 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5239 CurrentBody = 0;
5240 if (PropParentMap) {
5241 delete PropParentMap;
5242 PropParentMap = 0;
5243 }
5244 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5245 GlobalVarDecl = 0;
5246
5247 // This is needed for blocks.
5248 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5249 RewriteCastExpr(CE);
5250 }
5251 }
5252 break;
5253 }
5254 case Decl::TypeAlias:
5255 case Decl::Typedef: {
5256 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5257 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5258 RewriteBlockPointerDecl(TD);
5259 else if (TD->getUnderlyingType()->isFunctionPointerType())
5260 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5261 }
5262 break;
5263 }
5264 case Decl::CXXRecord:
5265 case Decl::Record: {
5266 RecordDecl *RD = cast<RecordDecl>(D);
5267 if (RD->isCompleteDefinition())
5268 RewriteRecordBody(RD);
5269 break;
5270 }
5271 default:
5272 break;
5273 }
5274 // Nothing yet.
5275}
5276
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005277/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5278/// protocol reference symbols in the for of:
5279/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5280static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5281 ObjCProtocolDecl *PDecl,
5282 std::string &Result) {
5283 // Also output .objc_protorefs$B section and its meta-data.
5284 if (Context->getLangOpts().MicrosoftExt)
5285 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5286 Result += "struct _protocol_t *";
5287 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5288 Result += PDecl->getNameAsString();
5289 Result += " = &";
5290 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5291 Result += ";\n";
5292}
5293
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005294void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5295 if (Diags.hasErrorOccurred())
5296 return;
5297
5298 RewriteInclude();
5299
5300 // Here's a great place to add any extra declarations that may be needed.
5301 // Write out meta data for each @protocol(<expr>).
5302 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005303 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005304 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005305 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5306 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005307
5308 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005309 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5310 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5311 // Write struct declaration for the class matching its ivar declarations.
5312 // Note that for modern abi, this is postponed until the end of TU
5313 // because class extensions and the implementation might declare their own
5314 // private ivars.
5315 RewriteInterfaceDecl(CDecl);
5316 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005317
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005318 if (ClassImplementation.size() || CategoryImplementation.size())
5319 RewriteImplementations();
5320
5321 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5322 // we are done.
5323 if (const RewriteBuffer *RewriteBuf =
5324 Rewrite.getRewriteBufferFor(MainFileID)) {
5325 //printf("Changed:\n");
5326 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5327 } else {
5328 llvm::errs() << "No changes\n";
5329 }
5330
5331 if (ClassImplementation.size() || CategoryImplementation.size() ||
5332 ProtocolExprDecls.size()) {
5333 // Rewrite Objective-c meta data*
5334 std::string ResultStr;
5335 RewriteMetaDataIntoBuffer(ResultStr);
5336 // Emit metadata.
5337 *OutFile << ResultStr;
5338 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005339 // Emit ImageInfo;
5340 {
5341 std::string ResultStr;
5342 WriteImageInfo(ResultStr);
5343 *OutFile << ResultStr;
5344 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005345 OutFile->flush();
5346}
5347
5348void RewriteModernObjC::Initialize(ASTContext &context) {
5349 InitializeCommon(context);
5350
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005351 Preamble += "#ifndef __OBJC2__\n";
5352 Preamble += "#define __OBJC2__\n";
5353 Preamble += "#endif\n";
5354
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005355 // declaring objc_selector outside the parameter list removes a silly
5356 // scope related warning...
5357 if (IsHeader)
5358 Preamble = "#pragma once\n";
5359 Preamble += "struct objc_selector; struct objc_class;\n";
5360 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5361 Preamble += "struct objc_object *superClass; ";
5362 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005363 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005364 // These are currently generated.
5365 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005366 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005367 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5368 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005369 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5370 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005371 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005372 // These are generated but not necessary for functionality.
5373 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5374 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005375 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5376 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005377 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005378
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005379 // These need be generated for performance. Currently they are not,
5380 // using API calls instead.
5381 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5382 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5383 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5384
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005385 // Add a constructor for creating temporary objects.
5386 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5387 ": ";
5388 Preamble += "object(o), superClass(s) {} ";
5389 }
5390 Preamble += "};\n";
5391 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5392 Preamble += "typedef struct objc_object Protocol;\n";
5393 Preamble += "#define _REWRITER_typedef_Protocol\n";
5394 Preamble += "#endif\n";
5395 if (LangOpts.MicrosoftExt) {
5396 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5397 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005398 }
5399 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005400 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005401
5402 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5403 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5404 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5405 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5406 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5407
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005408 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5409 Preamble += "(const char *);\n";
5410 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5411 Preamble += "(struct objc_class *);\n";
5412 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5413 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005414 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005415 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005416 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5417 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005418 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5419 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5420 Preamble += "struct __objcFastEnumerationState {\n\t";
5421 Preamble += "unsigned long state;\n\t";
5422 Preamble += "void **itemsPtr;\n\t";
5423 Preamble += "unsigned long *mutationsPtr;\n\t";
5424 Preamble += "unsigned long extra[5];\n};\n";
5425 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5426 Preamble += "#define __FASTENUMERATIONSTATE\n";
5427 Preamble += "#endif\n";
5428 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5429 Preamble += "struct __NSConstantStringImpl {\n";
5430 Preamble += " int *isa;\n";
5431 Preamble += " int flags;\n";
5432 Preamble += " char *str;\n";
5433 Preamble += " long length;\n";
5434 Preamble += "};\n";
5435 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5436 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5437 Preamble += "#else\n";
5438 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5439 Preamble += "#endif\n";
5440 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5441 Preamble += "#endif\n";
5442 // Blocks preamble.
5443 Preamble += "#ifndef BLOCK_IMPL\n";
5444 Preamble += "#define BLOCK_IMPL\n";
5445 Preamble += "struct __block_impl {\n";
5446 Preamble += " void *isa;\n";
5447 Preamble += " int Flags;\n";
5448 Preamble += " int Reserved;\n";
5449 Preamble += " void *FuncPtr;\n";
5450 Preamble += "};\n";
5451 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5452 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5453 Preamble += "extern \"C\" __declspec(dllexport) "
5454 "void _Block_object_assign(void *, const void *, const int);\n";
5455 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5456 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5457 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5458 Preamble += "#else\n";
5459 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5460 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5461 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5462 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5463 Preamble += "#endif\n";
5464 Preamble += "#endif\n";
5465 if (LangOpts.MicrosoftExt) {
5466 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5467 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5468 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5469 Preamble += "#define __attribute__(X)\n";
5470 Preamble += "#endif\n";
5471 Preamble += "#define __weak\n";
5472 }
5473 else {
5474 Preamble += "#define __block\n";
5475 Preamble += "#define __weak\n";
5476 }
5477 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5478 // as this avoids warning in any 64bit/32bit compilation model.
5479 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5480}
5481
5482/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5483/// ivar offset.
5484void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5485 std::string &Result) {
5486 if (ivar->isBitField()) {
5487 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5488 // place all bitfields at offset 0.
5489 Result += "0";
5490 } else {
5491 Result += "__OFFSETOFIVAR__(struct ";
5492 Result += ivar->getContainingInterface()->getNameAsString();
5493 if (LangOpts.MicrosoftExt)
5494 Result += "_IMPL";
5495 Result += ", ";
5496 Result += ivar->getNameAsString();
5497 Result += ")";
5498 }
5499}
5500
5501/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5502/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005503/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005504/// char *attributes;
5505/// }
5506
5507/// struct _prop_list_t {
5508/// uint32_t entsize; // sizeof(struct _prop_t)
5509/// uint32_t count_of_properties;
5510/// struct _prop_t prop_list[count_of_properties];
5511/// }
5512
5513/// struct _protocol_t;
5514
5515/// struct _protocol_list_t {
5516/// long protocol_count; // Note, this is 32/64 bit
5517/// struct _protocol_t * protocol_list[protocol_count];
5518/// }
5519
5520/// struct _objc_method {
5521/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005522/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005523/// char *_imp;
5524/// }
5525
5526/// struct _method_list_t {
5527/// uint32_t entsize; // sizeof(struct _objc_method)
5528/// uint32_t method_count;
5529/// struct _objc_method method_list[method_count];
5530/// }
5531
5532/// struct _protocol_t {
5533/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005534/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005535/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005536/// const struct method_list_t *instance_methods;
5537/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005538/// const struct method_list_t *optionalInstanceMethods;
5539/// const struct method_list_t *optionalClassMethods;
5540/// const struct _prop_list_t * properties;
5541/// const uint32_t size; // sizeof(struct _protocol_t)
5542/// const uint32_t flags; // = 0
5543/// const char ** extendedMethodTypes;
5544/// }
5545
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005546/// struct _ivar_t {
5547/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005548/// const char *name;
5549/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005550/// uint32_t alignment;
5551/// uint32_t size;
5552/// }
5553
5554/// struct _ivar_list_t {
5555/// uint32 entsize; // sizeof(struct _ivar_t)
5556/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005557/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005558/// }
5559
5560/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005561/// uint32_t flags;
5562/// uint32_t instanceStart;
5563/// uint32_t instanceSize;
5564/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005565/// const uint8_t *ivarLayout;
5566/// const char *name;
5567/// const struct _method_list_t *baseMethods;
5568/// const struct _protocol_list_t *baseProtocols;
5569/// const struct _ivar_list_t *ivars;
5570/// const uint8_t *weakIvarLayout;
5571/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005572/// }
5573
5574/// struct _class_t {
5575/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005576/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005577/// void *cache;
5578/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005579/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005580/// }
5581
5582/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005583/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005584/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005585/// const struct _method_list_t *instance_methods;
5586/// const struct _method_list_t *class_methods;
5587/// const struct _protocol_list_t *protocols;
5588/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005589/// }
5590
5591/// MessageRefTy - LLVM for:
5592/// struct _message_ref_t {
5593/// IMP messenger;
5594/// SEL name;
5595/// };
5596
5597/// SuperMessageRefTy - LLVM for:
5598/// struct _super_message_ref_t {
5599/// SUPER_IMP messenger;
5600/// SEL name;
5601/// };
5602
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005603static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005604 static bool meta_data_declared = false;
5605 if (meta_data_declared)
5606 return;
5607
5608 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005609 Result += "\tconst char *name;\n";
5610 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005611 Result += "};\n";
5612
5613 Result += "\nstruct _protocol_t;\n";
5614
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005615 Result += "\nstruct _objc_method {\n";
5616 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005617 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005618 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005619 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005620
5621 Result += "\nstruct _protocol_t {\n";
5622 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005623 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005624 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005625 Result += "\tconst struct method_list_t *instance_methods;\n";
5626 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005627 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5628 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5629 Result += "\tconst struct _prop_list_t * properties;\n";
5630 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5631 Result += "\tconst unsigned int flags; // = 0\n";
5632 Result += "\tconst char ** extendedMethodTypes;\n";
5633 Result += "};\n";
5634
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005635 Result += "\nstruct _ivar_t {\n";
5636 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005637 Result += "\tconst char *name;\n";
5638 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005639 Result += "\tunsigned int alignment;\n";
5640 Result += "\tunsigned int size;\n";
5641 Result += "};\n";
5642
5643 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005644 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005645 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005646 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005647 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5648 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005649 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005650 Result += "\tconst unsigned char *ivarLayout;\n";
5651 Result += "\tconst char *name;\n";
5652 Result += "\tconst struct _method_list_t *baseMethods;\n";
5653 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5654 Result += "\tconst struct _ivar_list_t *ivars;\n";
5655 Result += "\tconst unsigned char *weakIvarLayout;\n";
5656 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005657 Result += "};\n";
5658
5659 Result += "\nstruct _class_t {\n";
5660 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005661 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005662 Result += "\tvoid *cache;\n";
5663 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005664 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005665 Result += "};\n";
5666
5667 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005668 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005669 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005670 Result += "\tconst struct _method_list_t *instance_methods;\n";
5671 Result += "\tconst struct _method_list_t *class_methods;\n";
5672 Result += "\tconst struct _protocol_list_t *protocols;\n";
5673 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005674 Result += "};\n";
5675
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005676 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005677 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005678 meta_data_declared = true;
5679}
5680
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005681static void Write_protocol_list_t_TypeDecl(std::string &Result,
5682 long super_protocol_count) {
5683 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5684 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5685 Result += "\tstruct _protocol_t *super_protocols[";
5686 Result += utostr(super_protocol_count); Result += "];\n";
5687 Result += "}";
5688}
5689
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005690static void Write_method_list_t_TypeDecl(std::string &Result,
5691 unsigned int method_count) {
5692 Result += "struct /*_method_list_t*/"; Result += " {\n";
5693 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5694 Result += "\tunsigned int method_count;\n";
5695 Result += "\tstruct _objc_method method_list[";
5696 Result += utostr(method_count); Result += "];\n";
5697 Result += "}";
5698}
5699
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005700static void Write__prop_list_t_TypeDecl(std::string &Result,
5701 unsigned int property_count) {
5702 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5703 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5704 Result += "\tunsigned int count_of_properties;\n";
5705 Result += "\tstruct _prop_t prop_list[";
5706 Result += utostr(property_count); Result += "];\n";
5707 Result += "}";
5708}
5709
Fariborz Jahanianae932952012-02-10 20:47:10 +00005710static void Write__ivar_list_t_TypeDecl(std::string &Result,
5711 unsigned int ivar_count) {
5712 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5713 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5714 Result += "\tunsigned int count;\n";
5715 Result += "\tstruct _ivar_t ivar_list[";
5716 Result += utostr(ivar_count); Result += "];\n";
5717 Result += "}";
5718}
5719
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005720static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5721 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5722 StringRef VarName,
5723 StringRef ProtocolName) {
5724 if (SuperProtocols.size() > 0) {
5725 Result += "\nstatic ";
5726 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5727 Result += " "; Result += VarName;
5728 Result += ProtocolName;
5729 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5730 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5731 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5732 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5733 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5734 Result += SuperPD->getNameAsString();
5735 if (i == e-1)
5736 Result += "\n};\n";
5737 else
5738 Result += ",\n";
5739 }
5740 }
5741}
5742
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005743static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5744 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005745 ArrayRef<ObjCMethodDecl *> Methods,
5746 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005747 StringRef TopLevelDeclName,
5748 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005749 if (Methods.size() > 0) {
5750 Result += "\nstatic ";
5751 Write_method_list_t_TypeDecl(Result, Methods.size());
5752 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005753 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005754 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5755 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5756 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5757 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5758 ObjCMethodDecl *MD = Methods[i];
5759 if (i == 0)
5760 Result += "\t{{(struct objc_selector *)\"";
5761 else
5762 Result += "\t{(struct objc_selector *)\"";
5763 Result += (MD)->getSelector().getAsString(); Result += "\"";
5764 Result += ", ";
5765 std::string MethodTypeString;
5766 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5767 Result += "\""; Result += MethodTypeString; Result += "\"";
5768 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005769 if (!MethodImpl)
5770 Result += "0";
5771 else {
5772 Result += "(void *)";
5773 Result += RewriteObj.MethodInternalNames[MD];
5774 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005775 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005776 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005777 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005778 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005779 }
5780 Result += "};\n";
5781 }
5782}
5783
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005784static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005785 ASTContext *Context, std::string &Result,
5786 ArrayRef<ObjCPropertyDecl *> Properties,
5787 const Decl *Container,
5788 StringRef VarName,
5789 StringRef ProtocolName) {
5790 if (Properties.size() > 0) {
5791 Result += "\nstatic ";
5792 Write__prop_list_t_TypeDecl(Result, Properties.size());
5793 Result += " "; Result += VarName;
5794 Result += ProtocolName;
5795 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5796 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5797 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5798 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5799 ObjCPropertyDecl *PropDecl = Properties[i];
5800 if (i == 0)
5801 Result += "\t{{\"";
5802 else
5803 Result += "\t{\"";
5804 Result += PropDecl->getName(); Result += "\",";
5805 std::string PropertyTypeString, QuotePropertyTypeString;
5806 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5807 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5808 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5809 if (i == e-1)
5810 Result += "}}\n";
5811 else
5812 Result += "},\n";
5813 }
5814 Result += "};\n";
5815 }
5816}
5817
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005818// Metadata flags
5819enum MetaDataDlags {
5820 CLS = 0x0,
5821 CLS_META = 0x1,
5822 CLS_ROOT = 0x2,
5823 OBJC2_CLS_HIDDEN = 0x10,
5824 CLS_EXCEPTION = 0x20,
5825
5826 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5827 CLS_HAS_IVAR_RELEASER = 0x40,
5828 /// class was compiled with -fobjc-arr
5829 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5830};
5831
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005832static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5833 unsigned int flags,
5834 const std::string &InstanceStart,
5835 const std::string &InstanceSize,
5836 ArrayRef<ObjCMethodDecl *>baseMethods,
5837 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5838 ArrayRef<ObjCIvarDecl *>ivars,
5839 ArrayRef<ObjCPropertyDecl *>Properties,
5840 StringRef VarName,
5841 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005842 Result += "\nstatic struct _class_ro_t ";
5843 Result += VarName; Result += ClassName;
5844 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5845 Result += "\t";
5846 Result += llvm::utostr(flags); Result += ", ";
5847 Result += InstanceStart; Result += ", ";
5848 Result += InstanceSize; Result += ", \n";
5849 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005850 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5851 if (Triple.getArch() == llvm::Triple::x86_64)
5852 // uint32_t const reserved; // only when building for 64bit targets
5853 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005854 // const uint8_t * const ivarLayout;
5855 Result += "0, \n\t";
5856 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005857 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005858 if (baseMethods.size() > 0) {
5859 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005860 if (metaclass)
5861 Result += "_OBJC_$_CLASS_METHODS_";
5862 else
5863 Result += "_OBJC_$_INSTANCE_METHODS_";
5864 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005865 Result += ",\n\t";
5866 }
5867 else
5868 Result += "0, \n\t";
5869
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005870 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005871 Result += "(const struct _objc_protocol_list *)&";
5872 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5873 Result += ",\n\t";
5874 }
5875 else
5876 Result += "0, \n\t";
5877
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005878 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005879 Result += "(const struct _ivar_list_t *)&";
5880 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5881 Result += ",\n\t";
5882 }
5883 else
5884 Result += "0, \n\t";
5885
5886 // weakIvarLayout
5887 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005888 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005889 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005890 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005891 Result += ",\n";
5892 }
5893 else
5894 Result += "0, \n";
5895
5896 Result += "};\n";
5897}
5898
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005899static void Write_class_t(ASTContext *Context, std::string &Result,
5900 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005901 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5902 bool rootClass = (!CDecl->getSuperClass());
5903 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005904
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005905 if (!rootClass) {
5906 // Find the Root class
5907 RootClass = CDecl->getSuperClass();
5908 while (RootClass->getSuperClass()) {
5909 RootClass = RootClass->getSuperClass();
5910 }
5911 }
5912
5913 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005914 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005915 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005916 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005917 if (CDecl->getImplementation())
5918 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005919 else
5920 Result += "__declspec(dllimport) ";
5921
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005922 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005923 Result += CDecl->getNameAsString();
5924 Result += ";\n";
5925 }
5926 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005927 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005928 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005929 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005930 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005931 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005932 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005933 else
5934 Result += "__declspec(dllimport) ";
5935
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005936 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005937 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005938 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005939 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005940
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005941 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005942 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005943 if (RootClass->getImplementation())
5944 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005945 else
5946 Result += "__declspec(dllimport) ";
5947
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005948 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005949 Result += VarName;
5950 Result += RootClass->getNameAsString();
5951 Result += ";\n";
5952 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005953 }
5954
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005955 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
5956 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005957 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5958 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005959 if (metaclass) {
5960 if (!rootClass) {
5961 Result += "0, // &"; Result += VarName;
5962 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005963 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005964 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005965 Result += CDecl->getSuperClass()->getNameAsString();
5966 Result += ",\n\t";
5967 }
5968 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005969 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005970 Result += CDecl->getNameAsString();
5971 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005972 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005973 Result += ",\n\t";
5974 }
5975 }
5976 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005977 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005978 Result += CDecl->getNameAsString();
5979 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005980 if (!rootClass) {
5981 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005982 Result += CDecl->getSuperClass()->getNameAsString();
5983 Result += ",\n\t";
5984 }
5985 else
5986 Result += "0,\n\t";
5987 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005988 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5989 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5990 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005991 Result += "&_OBJC_METACLASS_RO_$_";
5992 else
5993 Result += "&_OBJC_CLASS_RO_$_";
5994 Result += CDecl->getNameAsString();
5995 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005996
5997 // Add static function to initialize some of the meta-data fields.
5998 // avoid doing it twice.
5999 if (metaclass)
6000 return;
6001
6002 const ObjCInterfaceDecl *SuperClass =
6003 rootClass ? CDecl : CDecl->getSuperClass();
6004
6005 Result += "static void OBJC_CLASS_SETUP_$_";
6006 Result += CDecl->getNameAsString();
6007 Result += "(void ) {\n";
6008 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6009 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006010 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006011
6012 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006013 Result += ".superclass = ";
6014 if (rootClass)
6015 Result += "&OBJC_CLASS_$_";
6016 else
6017 Result += "&OBJC_METACLASS_$_";
6018
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006019 Result += SuperClass->getNameAsString(); Result += ";\n";
6020
6021 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6022 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6023
6024 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6025 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6026 Result += CDecl->getNameAsString(); Result += ";\n";
6027
6028 if (!rootClass) {
6029 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6030 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6031 Result += SuperClass->getNameAsString(); Result += ";\n";
6032 }
6033
6034 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6035 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6036 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006037}
6038
Fariborz Jahanian61186122012-02-17 18:40:41 +00006039static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6040 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006041 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006042 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006043 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6044 ArrayRef<ObjCMethodDecl *> ClassMethods,
6045 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6046 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006047 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006048 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006049 // must declare an extern class object in case this class is not implemented
6050 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006051 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006052 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006053 if (ClassDecl->getImplementation())
6054 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006055 else
6056 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006057
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006058 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006059 Result += "OBJC_CLASS_$_"; Result += ClassName;
6060 Result += ";\n";
6061
Fariborz Jahanian61186122012-02-17 18:40:41 +00006062 Result += "\nstatic struct _category_t ";
6063 Result += "_OBJC_$_CATEGORY_";
6064 Result += ClassName; Result += "_$_"; Result += CatName;
6065 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6066 Result += "{\n";
6067 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006068 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006069 Result += ",\n";
6070 if (InstanceMethods.size() > 0) {
6071 Result += "\t(const struct _method_list_t *)&";
6072 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6073 Result += ClassName; Result += "_$_"; Result += CatName;
6074 Result += ",\n";
6075 }
6076 else
6077 Result += "\t0,\n";
6078
6079 if (ClassMethods.size() > 0) {
6080 Result += "\t(const struct _method_list_t *)&";
6081 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6082 Result += ClassName; Result += "_$_"; Result += CatName;
6083 Result += ",\n";
6084 }
6085 else
6086 Result += "\t0,\n";
6087
6088 if (RefedProtocols.size() > 0) {
6089 Result += "\t(const struct _protocol_list_t *)&";
6090 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6091 Result += ClassName; Result += "_$_"; Result += CatName;
6092 Result += ",\n";
6093 }
6094 else
6095 Result += "\t0,\n";
6096
6097 if (ClassProperties.size() > 0) {
6098 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6099 Result += ClassName; Result += "_$_"; Result += CatName;
6100 Result += ",\n";
6101 }
6102 else
6103 Result += "\t0,\n";
6104
6105 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006106
6107 // Add static function to initialize the class pointer in the category structure.
6108 Result += "static void OBJC_CATEGORY_SETUP_$_";
6109 Result += ClassDecl->getNameAsString();
6110 Result += "_$_";
6111 Result += CatName;
6112 Result += "(void ) {\n";
6113 Result += "\t_OBJC_$_CATEGORY_";
6114 Result += ClassDecl->getNameAsString();
6115 Result += "_$_";
6116 Result += CatName;
6117 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6118 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006119}
6120
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006121static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6122 ASTContext *Context, std::string &Result,
6123 ArrayRef<ObjCMethodDecl *> Methods,
6124 StringRef VarName,
6125 StringRef ProtocolName) {
6126 if (Methods.size() == 0)
6127 return;
6128
6129 Result += "\nstatic const char *";
6130 Result += VarName; Result += ProtocolName;
6131 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6132 Result += "{\n";
6133 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6134 ObjCMethodDecl *MD = Methods[i];
6135 std::string MethodTypeString, QuoteMethodTypeString;
6136 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6137 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6138 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6139 if (i == e-1)
6140 Result += "\n};\n";
6141 else {
6142 Result += ",\n";
6143 }
6144 }
6145}
6146
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006147static void Write_IvarOffsetVar(ASTContext *Context,
6148 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006149 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006150 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006151 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6152 // this is what happens:
6153 /**
6154 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6155 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6156 Class->getVisibility() == HiddenVisibility)
6157 Visibility shoud be: HiddenVisibility;
6158 else
6159 Visibility shoud be: DefaultVisibility;
6160 */
6161
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006162 Result += "\n";
6163 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6164 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006165 if (Context->getLangOpts().MicrosoftExt)
6166 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6167
6168 if (!Context->getLangOpts().MicrosoftExt ||
6169 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006170 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006171 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006172 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006173 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006174 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006175 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6176 Result += " = ";
6177 if (IvarDecl->isBitField()) {
6178 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6179 // place all bitfields at offset 0.
6180 Result += "0;\n";
6181 }
6182 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006183 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006184 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006185 Result += "_IMPL, ";
6186 Result += IvarDecl->getName(); Result += ");\n";
6187 }
6188 }
6189}
6190
Fariborz Jahanianae932952012-02-10 20:47:10 +00006191static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6192 ASTContext *Context, std::string &Result,
6193 ArrayRef<ObjCIvarDecl *> Ivars,
6194 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006195 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006196 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006197 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006198
Fariborz Jahanianae932952012-02-10 20:47:10 +00006199 Result += "\nstatic ";
6200 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6201 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006202 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006203 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6204 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6205 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6206 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6207 ObjCIvarDecl *IvarDecl = Ivars[i];
6208 if (i == 0)
6209 Result += "\t{{";
6210 else
6211 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006212 Result += "(unsigned long int *)&";
6213 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006214 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006215
6216 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6217 std::string IvarTypeString, QuoteIvarTypeString;
6218 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6219 IvarDecl);
6220 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6221 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6222
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006223 // FIXME. this alignment represents the host alignment and need be changed to
6224 // represent the target alignment.
6225 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6226 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006227 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006228 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6229 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006230 if (i == e-1)
6231 Result += "}}\n";
6232 else
6233 Result += "},\n";
6234 }
6235 Result += "};\n";
6236 }
6237}
6238
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006239/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006240void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6241 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006242
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006243 // Do not synthesize the protocol more than once.
6244 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6245 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006246 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006247
6248 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6249 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006250 // Must write out all protocol definitions in current qualifier list,
6251 // and in their nested qualifiers before writing out current definition.
6252 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6253 E = PDecl->protocol_end(); I != E; ++I)
6254 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006255
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006256 // Construct method lists.
6257 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6258 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6259 for (ObjCProtocolDecl::instmeth_iterator
6260 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6261 I != E; ++I) {
6262 ObjCMethodDecl *MD = *I;
6263 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6264 OptInstanceMethods.push_back(MD);
6265 } else {
6266 InstanceMethods.push_back(MD);
6267 }
6268 }
6269
6270 for (ObjCProtocolDecl::classmeth_iterator
6271 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6272 I != E; ++I) {
6273 ObjCMethodDecl *MD = *I;
6274 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6275 OptClassMethods.push_back(MD);
6276 } else {
6277 ClassMethods.push_back(MD);
6278 }
6279 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006280 std::vector<ObjCMethodDecl *> AllMethods;
6281 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6282 AllMethods.push_back(InstanceMethods[i]);
6283 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6284 AllMethods.push_back(ClassMethods[i]);
6285 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6286 AllMethods.push_back(OptInstanceMethods[i]);
6287 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6288 AllMethods.push_back(OptClassMethods[i]);
6289
6290 Write__extendedMethodTypes_initializer(*this, Context, Result,
6291 AllMethods,
6292 "_OBJC_PROTOCOL_METHOD_TYPES_",
6293 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006294 // Protocol's super protocol list
6295 std::vector<ObjCProtocolDecl *> SuperProtocols;
6296 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6297 E = PDecl->protocol_end(); I != E; ++I)
6298 SuperProtocols.push_back(*I);
6299
6300 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6301 "_OBJC_PROTOCOL_REFS_",
6302 PDecl->getNameAsString());
6303
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006304 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006305 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006306 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006307
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006308 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006309 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006310 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006311
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006312 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006313 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006314 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006315
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006316 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006317 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006318 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006319
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006320 // Protocol's property metadata.
6321 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6322 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6323 E = PDecl->prop_end(); I != E; ++I)
6324 ProtocolProperties.push_back(*I);
6325
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006326 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006327 /* Container */0,
6328 "_OBJC_PROTOCOL_PROPERTIES_",
6329 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006330
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006331 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006332 Result += "\n";
6333 if (LangOpts.MicrosoftExt)
6334 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006335 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006336 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006337 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6338 Result += "\t0,\n"; // id is; is null
6339 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006340 if (SuperProtocols.size() > 0) {
6341 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6342 Result += PDecl->getNameAsString(); Result += ",\n";
6343 }
6344 else
6345 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006346 if (InstanceMethods.size() > 0) {
6347 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6348 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006349 }
6350 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006351 Result += "\t0,\n";
6352
6353 if (ClassMethods.size() > 0) {
6354 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6355 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006356 }
6357 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006358 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006359
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006360 if (OptInstanceMethods.size() > 0) {
6361 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6362 Result += PDecl->getNameAsString(); Result += ",\n";
6363 }
6364 else
6365 Result += "\t0,\n";
6366
6367 if (OptClassMethods.size() > 0) {
6368 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6369 Result += PDecl->getNameAsString(); Result += ",\n";
6370 }
6371 else
6372 Result += "\t0,\n";
6373
6374 if (ProtocolProperties.size() > 0) {
6375 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6376 Result += PDecl->getNameAsString(); Result += ",\n";
6377 }
6378 else
6379 Result += "\t0,\n";
6380
6381 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6382 Result += "\t0,\n";
6383
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006384 if (AllMethods.size() > 0) {
6385 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6386 Result += PDecl->getNameAsString();
6387 Result += "\n};\n";
6388 }
6389 else
6390 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006391
6392 // Use this protocol meta-data to build protocol list table in section
6393 // .objc_protolist$B
6394 // Unspecified visibility means 'private extern'.
6395 if (LangOpts.MicrosoftExt)
6396 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6397 Result += "struct _protocol_t *";
6398 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6399 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6400 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006401
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006402 // Mark this protocol as having been generated.
6403 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6404 llvm_unreachable("protocol already synthesized");
6405
6406}
6407
6408void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6409 const ObjCList<ObjCProtocolDecl> &Protocols,
6410 StringRef prefix, StringRef ClassName,
6411 std::string &Result) {
6412 if (Protocols.empty()) return;
6413
6414 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006415 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006416
6417 // Output the top lovel protocol meta-data for the class.
6418 /* struct _objc_protocol_list {
6419 struct _objc_protocol_list *next;
6420 int protocol_count;
6421 struct _objc_protocol *class_protocols[];
6422 }
6423 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006424 Result += "\n";
6425 if (LangOpts.MicrosoftExt)
6426 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6427 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006428 Result += "\tstruct _objc_protocol_list *next;\n";
6429 Result += "\tint protocol_count;\n";
6430 Result += "\tstruct _objc_protocol *class_protocols[";
6431 Result += utostr(Protocols.size());
6432 Result += "];\n} _OBJC_";
6433 Result += prefix;
6434 Result += "_PROTOCOLS_";
6435 Result += ClassName;
6436 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6437 "{\n\t0, ";
6438 Result += utostr(Protocols.size());
6439 Result += "\n";
6440
6441 Result += "\t,{&_OBJC_PROTOCOL_";
6442 Result += Protocols[0]->getNameAsString();
6443 Result += " \n";
6444
6445 for (unsigned i = 1; i != Protocols.size(); i++) {
6446 Result += "\t ,&_OBJC_PROTOCOL_";
6447 Result += Protocols[i]->getNameAsString();
6448 Result += "\n";
6449 }
6450 Result += "\t }\n};\n";
6451}
6452
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006453/// hasObjCExceptionAttribute - Return true if this class or any super
6454/// class has the __objc_exception__ attribute.
6455/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6456static bool hasObjCExceptionAttribute(ASTContext &Context,
6457 const ObjCInterfaceDecl *OID) {
6458 if (OID->hasAttr<ObjCExceptionAttr>())
6459 return true;
6460 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6461 return hasObjCExceptionAttribute(Context, Super);
6462 return false;
6463}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006464
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006465void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6466 std::string &Result) {
6467 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6468
6469 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006470 if (CDecl->isImplicitInterfaceDecl())
6471 assert(false &&
6472 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006473
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006474 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006475 SmallVector<ObjCIvarDecl *, 8> IVars;
6476
6477 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6478 IVD; IVD = IVD->getNextIvar()) {
6479 // Ignore unnamed bit-fields.
6480 if (!IVD->getDeclName())
6481 continue;
6482 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006483 }
6484
Fariborz Jahanianae932952012-02-10 20:47:10 +00006485 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006486 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006487 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006488
6489 // Build _objc_method_list for class's instance methods if needed
6490 SmallVector<ObjCMethodDecl *, 32>
6491 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6492
6493 // If any of our property implementations have associated getters or
6494 // setters, produce metadata for them as well.
6495 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6496 PropEnd = IDecl->propimpl_end();
6497 Prop != PropEnd; ++Prop) {
6498 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6499 continue;
6500 if (!(*Prop)->getPropertyIvarDecl())
6501 continue;
6502 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6503 if (!PD)
6504 continue;
6505 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6506 if (!Getter->isDefined())
6507 InstanceMethods.push_back(Getter);
6508 if (PD->isReadOnly())
6509 continue;
6510 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6511 if (!Setter->isDefined())
6512 InstanceMethods.push_back(Setter);
6513 }
6514
6515 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6516 "_OBJC_$_INSTANCE_METHODS_",
6517 IDecl->getNameAsString(), true);
6518
6519 SmallVector<ObjCMethodDecl *, 32>
6520 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6521
6522 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6523 "_OBJC_$_CLASS_METHODS_",
6524 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006525
6526 // Protocols referenced in class declaration?
6527 // Protocol's super protocol list
6528 std::vector<ObjCProtocolDecl *> RefedProtocols;
6529 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6530 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6531 E = Protocols.end();
6532 I != E; ++I) {
6533 RefedProtocols.push_back(*I);
6534 // Must write out all protocol definitions in current qualifier list,
6535 // and in their nested qualifiers before writing out current definition.
6536 RewriteObjCProtocolMetaData(*I, Result);
6537 }
6538
6539 Write_protocol_list_initializer(Context, Result,
6540 RefedProtocols,
6541 "_OBJC_CLASS_PROTOCOLS_$_",
6542 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006543
6544 // Protocol's property metadata.
6545 std::vector<ObjCPropertyDecl *> ClassProperties;
6546 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6547 E = CDecl->prop_end(); I != E; ++I)
6548 ClassProperties.push_back(*I);
6549
6550 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006551 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006552 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006553 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006554
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006555
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006556 // Data for initializing _class_ro_t metaclass meta-data
6557 uint32_t flags = CLS_META;
6558 std::string InstanceSize;
6559 std::string InstanceStart;
6560
6561
6562 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6563 if (classIsHidden)
6564 flags |= OBJC2_CLS_HIDDEN;
6565
6566 if (!CDecl->getSuperClass())
6567 // class is root
6568 flags |= CLS_ROOT;
6569 InstanceSize = "sizeof(struct _class_t)";
6570 InstanceStart = InstanceSize;
6571 Write__class_ro_t_initializer(Context, Result, flags,
6572 InstanceStart, InstanceSize,
6573 ClassMethods,
6574 0,
6575 0,
6576 0,
6577 "_OBJC_METACLASS_RO_$_",
6578 CDecl->getNameAsString());
6579
6580
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006581 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006582 flags = CLS;
6583 if (classIsHidden)
6584 flags |= OBJC2_CLS_HIDDEN;
6585
6586 if (hasObjCExceptionAttribute(*Context, CDecl))
6587 flags |= CLS_EXCEPTION;
6588
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006589 if (!CDecl->getSuperClass())
6590 // class is root
6591 flags |= CLS_ROOT;
6592
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006593 InstanceSize.clear();
6594 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006595 if (!ObjCSynthesizedStructs.count(CDecl)) {
6596 InstanceSize = "0";
6597 InstanceStart = "0";
6598 }
6599 else {
6600 InstanceSize = "sizeof(struct ";
6601 InstanceSize += CDecl->getNameAsString();
6602 InstanceSize += "_IMPL)";
6603
6604 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6605 if (IVD) {
6606 InstanceStart += "__OFFSETOFIVAR__(struct ";
6607 InstanceStart += CDecl->getNameAsString();
6608 InstanceStart += "_IMPL, ";
6609 InstanceStart += IVD->getNameAsString();
6610 InstanceStart += ")";
6611 }
6612 else
6613 InstanceStart = InstanceSize;
6614 }
6615 Write__class_ro_t_initializer(Context, Result, flags,
6616 InstanceStart, InstanceSize,
6617 InstanceMethods,
6618 RefedProtocols,
6619 IVars,
6620 ClassProperties,
6621 "_OBJC_CLASS_RO_$_",
6622 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006623
6624 Write_class_t(Context, Result,
6625 "OBJC_METACLASS_$_",
6626 CDecl, /*metaclass*/true);
6627
6628 Write_class_t(Context, Result,
6629 "OBJC_CLASS_$_",
6630 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006631
6632 if (ImplementationIsNonLazy(IDecl))
6633 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006634
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006635}
6636
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006637void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6638 int ClsDefCount = ClassImplementation.size();
6639 if (!ClsDefCount)
6640 return;
6641 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6642 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6643 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6644 for (int i = 0; i < ClsDefCount; i++) {
6645 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6646 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6647 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6648 Result += CDecl->getName(); Result += ",\n";
6649 }
6650 Result += "};\n";
6651}
6652
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006653void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6654 int ClsDefCount = ClassImplementation.size();
6655 int CatDefCount = CategoryImplementation.size();
6656
6657 // For each implemented class, write out all its meta data.
6658 for (int i = 0; i < ClsDefCount; i++)
6659 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6660
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006661 RewriteClassSetupInitHook(Result);
6662
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006663 // For each implemented category, write out all its meta data.
6664 for (int i = 0; i < CatDefCount; i++)
6665 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6666
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006667 RewriteCategorySetupInitHook(Result);
6668
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006669 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006670 if (LangOpts.MicrosoftExt)
6671 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006672 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6673 Result += llvm::utostr(ClsDefCount); Result += "]";
6674 Result +=
6675 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6676 "regular,no_dead_strip\")))= {\n";
6677 for (int i = 0; i < ClsDefCount; i++) {
6678 Result += "\t&OBJC_CLASS_$_";
6679 Result += ClassImplementation[i]->getNameAsString();
6680 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006681 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006682 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006683
6684 if (!DefinedNonLazyClasses.empty()) {
6685 if (LangOpts.MicrosoftExt)
6686 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6687 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6688 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6689 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6690 Result += ",\n";
6691 }
6692 Result += "};\n";
6693 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006694 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006695
6696 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006697 if (LangOpts.MicrosoftExt)
6698 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006699 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6700 Result += llvm::utostr(CatDefCount); Result += "]";
6701 Result +=
6702 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6703 "regular,no_dead_strip\")))= {\n";
6704 for (int i = 0; i < CatDefCount; i++) {
6705 Result += "\t&_OBJC_$_CATEGORY_";
6706 Result +=
6707 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6708 Result += "_$_";
6709 Result += CategoryImplementation[i]->getNameAsString();
6710 Result += ",\n";
6711 }
6712 Result += "};\n";
6713 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006714
6715 if (!DefinedNonLazyCategories.empty()) {
6716 if (LangOpts.MicrosoftExt)
6717 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6718 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6719 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6720 Result += "\t&_OBJC_$_CATEGORY_";
6721 Result +=
6722 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6723 Result += "_$_";
6724 Result += DefinedNonLazyCategories[i]->getNameAsString();
6725 Result += ",\n";
6726 }
6727 Result += "};\n";
6728 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006729}
6730
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006731void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6732 if (LangOpts.MicrosoftExt)
6733 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6734
6735 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6736 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006737 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006738}
6739
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006740/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6741/// implementation.
6742void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6743 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006744 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006745 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6746 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006747 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006748 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6749 CDecl = CDecl->getNextClassCategory())
6750 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6751 break;
6752
6753 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006754 FullCategoryName += "_$_";
6755 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006756
6757 // Build _objc_method_list for class's instance methods if needed
6758 SmallVector<ObjCMethodDecl *, 32>
6759 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6760
6761 // If any of our property implementations have associated getters or
6762 // setters, produce metadata for them as well.
6763 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6764 PropEnd = IDecl->propimpl_end();
6765 Prop != PropEnd; ++Prop) {
6766 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6767 continue;
6768 if (!(*Prop)->getPropertyIvarDecl())
6769 continue;
6770 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6771 if (!PD)
6772 continue;
6773 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6774 InstanceMethods.push_back(Getter);
6775 if (PD->isReadOnly())
6776 continue;
6777 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6778 InstanceMethods.push_back(Setter);
6779 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006780
Fariborz Jahanian61186122012-02-17 18:40:41 +00006781 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6782 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6783 FullCategoryName, true);
6784
6785 SmallVector<ObjCMethodDecl *, 32>
6786 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6787
6788 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6789 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6790 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006791
6792 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006793 // Protocol's super protocol list
6794 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006795 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6796 E = CDecl->protocol_end();
6797
6798 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006799 RefedProtocols.push_back(*I);
6800 // Must write out all protocol definitions in current qualifier list,
6801 // and in their nested qualifiers before writing out current definition.
6802 RewriteObjCProtocolMetaData(*I, Result);
6803 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006804
Fariborz Jahanian61186122012-02-17 18:40:41 +00006805 Write_protocol_list_initializer(Context, Result,
6806 RefedProtocols,
6807 "_OBJC_CATEGORY_PROTOCOLS_$_",
6808 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006809
Fariborz Jahanian61186122012-02-17 18:40:41 +00006810 // Protocol's property metadata.
6811 std::vector<ObjCPropertyDecl *> ClassProperties;
6812 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6813 E = CDecl->prop_end(); I != E; ++I)
6814 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006815
Fariborz Jahanian61186122012-02-17 18:40:41 +00006816 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6817 /* Container */0,
6818 "_OBJC_$_PROP_LIST_",
6819 FullCategoryName);
6820
6821 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006822 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006823 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006824 InstanceMethods,
6825 ClassMethods,
6826 RefedProtocols,
6827 ClassProperties);
6828
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006829 // Determine if this category is also "non-lazy".
6830 if (ImplementationIsNonLazy(IDecl))
6831 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006832
6833}
6834
6835void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
6836 int CatDefCount = CategoryImplementation.size();
6837 if (!CatDefCount)
6838 return;
6839 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6840 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6841 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
6842 for (int i = 0; i < CatDefCount; i++) {
6843 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
6844 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
6845 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6846 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
6847 Result += ClassDecl->getName();
6848 Result += "_$_";
6849 Result += CatDecl->getName();
6850 Result += ",\n";
6851 }
6852 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006853}
6854
6855// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6856/// class methods.
6857template<typename MethodIterator>
6858void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6859 MethodIterator MethodEnd,
6860 bool IsInstanceMethod,
6861 StringRef prefix,
6862 StringRef ClassName,
6863 std::string &Result) {
6864 if (MethodBegin == MethodEnd) return;
6865
6866 if (!objc_impl_method) {
6867 /* struct _objc_method {
6868 SEL _cmd;
6869 char *method_types;
6870 void *_imp;
6871 }
6872 */
6873 Result += "\nstruct _objc_method {\n";
6874 Result += "\tSEL _cmd;\n";
6875 Result += "\tchar *method_types;\n";
6876 Result += "\tvoid *_imp;\n";
6877 Result += "};\n";
6878
6879 objc_impl_method = true;
6880 }
6881
6882 // Build _objc_method_list for class's methods if needed
6883
6884 /* struct {
6885 struct _objc_method_list *next_method;
6886 int method_count;
6887 struct _objc_method method_list[];
6888 }
6889 */
6890 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006891 Result += "\n";
6892 if (LangOpts.MicrosoftExt) {
6893 if (IsInstanceMethod)
6894 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6895 else
6896 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6897 }
6898 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006899 Result += "\tstruct _objc_method_list *next_method;\n";
6900 Result += "\tint method_count;\n";
6901 Result += "\tstruct _objc_method method_list[";
6902 Result += utostr(NumMethods);
6903 Result += "];\n} _OBJC_";
6904 Result += prefix;
6905 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6906 Result += "_METHODS_";
6907 Result += ClassName;
6908 Result += " __attribute__ ((used, section (\"__OBJC, __";
6909 Result += IsInstanceMethod ? "inst" : "cls";
6910 Result += "_meth\")))= ";
6911 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6912
6913 Result += "\t,{{(SEL)\"";
6914 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6915 std::string MethodTypeString;
6916 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6917 Result += "\", \"";
6918 Result += MethodTypeString;
6919 Result += "\", (void *)";
6920 Result += MethodInternalNames[*MethodBegin];
6921 Result += "}\n";
6922 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6923 Result += "\t ,{(SEL)\"";
6924 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6925 std::string MethodTypeString;
6926 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6927 Result += "\", \"";
6928 Result += MethodTypeString;
6929 Result += "\", (void *)";
6930 Result += MethodInternalNames[*MethodBegin];
6931 Result += "}\n";
6932 }
6933 Result += "\t }\n};\n";
6934}
6935
6936Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6937 SourceRange OldRange = IV->getSourceRange();
6938 Expr *BaseExpr = IV->getBase();
6939
6940 // Rewrite the base, but without actually doing replaces.
6941 {
6942 DisableReplaceStmtScope S(*this);
6943 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6944 IV->setBase(BaseExpr);
6945 }
6946
6947 ObjCIvarDecl *D = IV->getDecl();
6948
6949 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006950
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006951 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6952 const ObjCInterfaceType *iFaceDecl =
6953 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6954 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6955 // lookup which class implements the instance variable.
6956 ObjCInterfaceDecl *clsDeclared = 0;
6957 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6958 clsDeclared);
6959 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6960
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006961 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006962 std::string IvarOffsetName;
6963 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6964
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006965 ReferencedIvars[clsDeclared].insert(D);
6966
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006967 // cast offset to "char *".
6968 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6969 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006970 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006971 BaseExpr);
6972 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6973 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6974 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006975 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6976 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006977 SourceLocation());
6978 BinaryOperator *addExpr =
6979 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6980 Context->getPointerType(Context->CharTy),
6981 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006982 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006983 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6984 SourceLocation(),
6985 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006986 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006987 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006988 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006989
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006990 castExpr = NoTypeInfoCStyleCastExpr(Context,
6991 castT,
6992 CK_BitCast,
6993 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006994 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006995 VK_LValue, OK_Ordinary,
6996 SourceLocation());
6997 PE = new (Context) ParenExpr(OldRange.getBegin(),
6998 OldRange.getEnd(),
6999 Exp);
7000
7001 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007002 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007003
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007004 ReplaceStmtWithRange(IV, Replacement, OldRange);
7005 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007006}