blob: 0c57ae0812abd6fe98f93f845f9f9f95b519f2f4 [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 Jahanian8e86b2d2012-04-04 17:16:15 +0000676 // FIXME. This will not work in all situations and leaving it out
677 // is harmless.
678 // RewriteLinkageSpec(LSD);
679
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000680 // Recurse into linkage specifications
681 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
682 DIEnd = LSD->decls_end();
683 DI != DIEnd; ) {
684 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
685 if (!IFace->isThisDeclarationADefinition()) {
686 SmallVector<Decl *, 8> DG;
687 SourceLocation StartLoc = IFace->getLocStart();
688 do {
689 if (isa<ObjCInterfaceDecl>(*DI) &&
690 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
691 StartLoc == (*DI)->getLocStart())
692 DG.push_back(*DI);
693 else
694 break;
695
696 ++DI;
697 } while (DI != DIEnd);
698 RewriteForwardClassDecl(DG);
699 continue;
700 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000701 else {
702 // Keep track of all interface declarations seen.
703 ObjCInterfacesSeen.push_back(IFace);
704 ++DI;
705 continue;
706 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000707 }
708
709 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
710 if (!Proto->isThisDeclarationADefinition()) {
711 SmallVector<Decl *, 8> DG;
712 SourceLocation StartLoc = Proto->getLocStart();
713 do {
714 if (isa<ObjCProtocolDecl>(*DI) &&
715 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
716 StartLoc == (*DI)->getLocStart())
717 DG.push_back(*DI);
718 else
719 break;
720
721 ++DI;
722 } while (DI != DIEnd);
723 RewriteForwardProtocolDecl(DG);
724 continue;
725 }
726 }
727
728 HandleTopLevelSingleDecl(*DI);
729 ++DI;
730 }
731 }
732 // If we have a decl in the main file, see if we should rewrite it.
733 if (SM->isFromMainFile(Loc))
734 return HandleDeclInMainFile(D);
735}
736
737//===----------------------------------------------------------------------===//
738// Syntactic (non-AST) Rewriting Code
739//===----------------------------------------------------------------------===//
740
741void RewriteModernObjC::RewriteInclude() {
742 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
743 StringRef MainBuf = SM->getBufferData(MainFileID);
744 const char *MainBufStart = MainBuf.begin();
745 const char *MainBufEnd = MainBuf.end();
746 size_t ImportLen = strlen("import");
747
748 // Loop over the whole file, looking for includes.
749 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
750 if (*BufPtr == '#') {
751 if (++BufPtr == MainBufEnd)
752 return;
753 while (*BufPtr == ' ' || *BufPtr == '\t')
754 if (++BufPtr == MainBufEnd)
755 return;
756 if (!strncmp(BufPtr, "import", ImportLen)) {
757 // replace import with include
758 SourceLocation ImportLoc =
759 LocStart.getLocWithOffset(BufPtr-MainBufStart);
760 ReplaceText(ImportLoc, ImportLen, "include");
761 BufPtr += ImportLen;
762 }
763 }
764 }
765}
766
767static std::string getIvarAccessString(ObjCIvarDecl *OID) {
768 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
769 std::string S;
770 S = "((struct ";
771 S += ClassDecl->getIdentifier()->getName();
772 S += "_IMPL *)self)->";
773 S += OID->getName();
774 return S;
775}
776
777void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
778 ObjCImplementationDecl *IMD,
779 ObjCCategoryImplDecl *CID) {
780 static bool objcGetPropertyDefined = false;
781 static bool objcSetPropertyDefined = false;
782 SourceLocation startLoc = PID->getLocStart();
783 InsertText(startLoc, "// ");
784 const char *startBuf = SM->getCharacterData(startLoc);
785 assert((*startBuf == '@') && "bogus @synthesize location");
786 const char *semiBuf = strchr(startBuf, ';');
787 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
788 SourceLocation onePastSemiLoc =
789 startLoc.getLocWithOffset(semiBuf-startBuf+1);
790
791 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
792 return; // FIXME: is this correct?
793
794 // Generate the 'getter' function.
795 ObjCPropertyDecl *PD = PID->getPropertyDecl();
796 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
797
798 if (!OID)
799 return;
800 unsigned Attributes = PD->getPropertyAttributes();
801 if (!PD->getGetterMethodDecl()->isDefined()) {
802 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
803 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
804 ObjCPropertyDecl::OBJC_PR_copy));
805 std::string Getr;
806 if (GenGetProperty && !objcGetPropertyDefined) {
807 objcGetPropertyDefined = true;
808 // FIXME. Is this attribute correct in all cases?
809 Getr = "\nextern \"C\" __declspec(dllimport) "
810 "id objc_getProperty(id, SEL, long, bool);\n";
811 }
812 RewriteObjCMethodDecl(OID->getContainingInterface(),
813 PD->getGetterMethodDecl(), Getr);
814 Getr += "{ ";
815 // Synthesize an explicit cast to gain access to the ivar.
816 // See objc-act.c:objc_synthesize_new_getter() for details.
817 if (GenGetProperty) {
818 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
819 Getr += "typedef ";
820 const FunctionType *FPRetType = 0;
821 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
822 FPRetType);
823 Getr += " _TYPE";
824 if (FPRetType) {
825 Getr += ")"; // close the precedence "scope" for "*".
826
827 // Now, emit the argument types (if any).
828 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
829 Getr += "(";
830 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
831 if (i) Getr += ", ";
832 std::string ParamStr = FT->getArgType(i).getAsString(
833 Context->getPrintingPolicy());
834 Getr += ParamStr;
835 }
836 if (FT->isVariadic()) {
837 if (FT->getNumArgs()) Getr += ", ";
838 Getr += "...";
839 }
840 Getr += ")";
841 } else
842 Getr += "()";
843 }
844 Getr += ";\n";
845 Getr += "return (_TYPE)";
846 Getr += "objc_getProperty(self, _cmd, ";
847 RewriteIvarOffsetComputation(OID, Getr);
848 Getr += ", 1)";
849 }
850 else
851 Getr += "return " + getIvarAccessString(OID);
852 Getr += "; }";
853 InsertText(onePastSemiLoc, Getr);
854 }
855
856 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
857 return;
858
859 // Generate the 'setter' function.
860 std::string Setr;
861 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
862 ObjCPropertyDecl::OBJC_PR_copy);
863 if (GenSetProperty && !objcSetPropertyDefined) {
864 objcSetPropertyDefined = true;
865 // FIXME. Is this attribute correct in all cases?
866 Setr = "\nextern \"C\" __declspec(dllimport) "
867 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
868 }
869
870 RewriteObjCMethodDecl(OID->getContainingInterface(),
871 PD->getSetterMethodDecl(), Setr);
872 Setr += "{ ";
873 // Synthesize an explicit cast to initialize the ivar.
874 // See objc-act.c:objc_synthesize_new_setter() for details.
875 if (GenSetProperty) {
876 Setr += "objc_setProperty (self, _cmd, ";
877 RewriteIvarOffsetComputation(OID, Setr);
878 Setr += ", (id)";
879 Setr += PD->getName();
880 Setr += ", ";
881 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
882 Setr += "0, ";
883 else
884 Setr += "1, ";
885 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
886 Setr += "1)";
887 else
888 Setr += "0)";
889 }
890 else {
891 Setr += getIvarAccessString(OID) + " = ";
892 Setr += PD->getName();
893 }
894 Setr += "; }";
895 InsertText(onePastSemiLoc, Setr);
896}
897
898static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
899 std::string &typedefString) {
900 typedefString += "#ifndef _REWRITER_typedef_";
901 typedefString += ForwardDecl->getNameAsString();
902 typedefString += "\n";
903 typedefString += "#define _REWRITER_typedef_";
904 typedefString += ForwardDecl->getNameAsString();
905 typedefString += "\n";
906 typedefString += "typedef struct objc_object ";
907 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000908 // typedef struct { } _objc_exc_Classname;
909 typedefString += ";\ntypedef struct {} _objc_exc_";
910 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000911 typedefString += ";\n#endif\n";
912}
913
914void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
915 const std::string &typedefString) {
916 SourceLocation startLoc = ClassDecl->getLocStart();
917 const char *startBuf = SM->getCharacterData(startLoc);
918 const char *semiPtr = strchr(startBuf, ';');
919 // Replace the @class with typedefs corresponding to the classes.
920 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
921}
922
923void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
924 std::string typedefString;
925 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
926 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
927 if (I == D.begin()) {
928 // Translate to typedef's that forward reference structs with the same name
929 // as the class. As a convenience, we include the original declaration
930 // as a comment.
931 typedefString += "// @class ";
932 typedefString += ForwardDecl->getNameAsString();
933 typedefString += ";\n";
934 }
935 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
936 }
937 DeclGroupRef::iterator I = D.begin();
938 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
939}
940
941void RewriteModernObjC::RewriteForwardClassDecl(
942 const llvm::SmallVector<Decl*, 8> &D) {
943 std::string typedefString;
944 for (unsigned i = 0; i < D.size(); i++) {
945 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
946 if (i == 0) {
947 typedefString += "// @class ";
948 typedefString += ForwardDecl->getNameAsString();
949 typedefString += ";\n";
950 }
951 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
952 }
953 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
954}
955
956void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
957 // When method is a synthesized one, such as a getter/setter there is
958 // nothing to rewrite.
959 if (Method->isImplicit())
960 return;
961 SourceLocation LocStart = Method->getLocStart();
962 SourceLocation LocEnd = Method->getLocEnd();
963
964 if (SM->getExpansionLineNumber(LocEnd) >
965 SM->getExpansionLineNumber(LocStart)) {
966 InsertText(LocStart, "#if 0\n");
967 ReplaceText(LocEnd, 1, ";\n#endif\n");
968 } else {
969 InsertText(LocStart, "// ");
970 }
971}
972
973void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
974 SourceLocation Loc = prop->getAtLoc();
975
976 ReplaceText(Loc, 0, "// ");
977 // FIXME: handle properties that are declared across multiple lines.
978}
979
980void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
981 SourceLocation LocStart = CatDecl->getLocStart();
982
983 // FIXME: handle category headers that are declared across multiple lines.
984 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000985 if (CatDecl->getIvarLBraceLoc().isValid())
986 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000987 for (ObjCCategoryDecl::ivar_iterator
988 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
989 ObjCIvarDecl *Ivar = (*I);
990 SourceLocation LocStart = Ivar->getLocStart();
991 ReplaceText(LocStart, 0, "// ");
992 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000993 if (CatDecl->getIvarRBraceLoc().isValid())
994 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
995
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000996 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
997 E = CatDecl->prop_end(); I != E; ++I)
998 RewriteProperty(*I);
999
1000 for (ObjCCategoryDecl::instmeth_iterator
1001 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1002 I != E; ++I)
1003 RewriteMethodDeclaration(*I);
1004 for (ObjCCategoryDecl::classmeth_iterator
1005 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1006 I != E; ++I)
1007 RewriteMethodDeclaration(*I);
1008
1009 // Lastly, comment out the @end.
1010 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1011 strlen("@end"), "/* @end */");
1012}
1013
1014void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1015 SourceLocation LocStart = PDecl->getLocStart();
1016 assert(PDecl->isThisDeclarationADefinition());
1017
1018 // FIXME: handle protocol headers that are declared across multiple lines.
1019 ReplaceText(LocStart, 0, "// ");
1020
1021 for (ObjCProtocolDecl::instmeth_iterator
1022 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1023 I != E; ++I)
1024 RewriteMethodDeclaration(*I);
1025 for (ObjCProtocolDecl::classmeth_iterator
1026 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1027 I != E; ++I)
1028 RewriteMethodDeclaration(*I);
1029
1030 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1031 E = PDecl->prop_end(); I != E; ++I)
1032 RewriteProperty(*I);
1033
1034 // Lastly, comment out the @end.
1035 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1036 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1037
1038 // Must comment out @optional/@required
1039 const char *startBuf = SM->getCharacterData(LocStart);
1040 const char *endBuf = SM->getCharacterData(LocEnd);
1041 for (const char *p = startBuf; p < endBuf; p++) {
1042 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1043 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1044 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1045
1046 }
1047 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1048 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1049 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1050
1051 }
1052 }
1053}
1054
1055void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1056 SourceLocation LocStart = (*D.begin())->getLocStart();
1057 if (LocStart.isInvalid())
1058 llvm_unreachable("Invalid SourceLocation");
1059 // FIXME: handle forward protocol that are declared across multiple lines.
1060 ReplaceText(LocStart, 0, "// ");
1061}
1062
1063void
1064RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1065 SourceLocation LocStart = DG[0]->getLocStart();
1066 if (LocStart.isInvalid())
1067 llvm_unreachable("Invalid SourceLocation");
1068 // FIXME: handle forward protocol that are declared across multiple lines.
1069 ReplaceText(LocStart, 0, "// ");
1070}
1071
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001072void
1073RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1074 SourceLocation LocStart = LSD->getExternLoc();
1075 if (LocStart.isInvalid())
1076 llvm_unreachable("Invalid extern SourceLocation");
1077
1078 ReplaceText(LocStart, 0, "// ");
1079 if (!LSD->hasBraces())
1080 return;
1081 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1082 SourceLocation LocRBrace = LSD->getRBraceLoc();
1083 if (LocRBrace.isInvalid())
1084 llvm_unreachable("Invalid rbrace SourceLocation");
1085 ReplaceText(LocRBrace, 0, "// ");
1086}
1087
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001088void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1089 const FunctionType *&FPRetType) {
1090 if (T->isObjCQualifiedIdType())
1091 ResultStr += "id";
1092 else if (T->isFunctionPointerType() ||
1093 T->isBlockPointerType()) {
1094 // needs special handling, since pointer-to-functions have special
1095 // syntax (where a decaration models use).
1096 QualType retType = T;
1097 QualType PointeeTy;
1098 if (const PointerType* PT = retType->getAs<PointerType>())
1099 PointeeTy = PT->getPointeeType();
1100 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1101 PointeeTy = BPT->getPointeeType();
1102 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1103 ResultStr += FPRetType->getResultType().getAsString(
1104 Context->getPrintingPolicy());
1105 ResultStr += "(*";
1106 }
1107 } else
1108 ResultStr += T.getAsString(Context->getPrintingPolicy());
1109}
1110
1111void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1112 ObjCMethodDecl *OMD,
1113 std::string &ResultStr) {
1114 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1115 const FunctionType *FPRetType = 0;
1116 ResultStr += "\nstatic ";
1117 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1118 ResultStr += " ";
1119
1120 // Unique method name
1121 std::string NameStr;
1122
1123 if (OMD->isInstanceMethod())
1124 NameStr += "_I_";
1125 else
1126 NameStr += "_C_";
1127
1128 NameStr += IDecl->getNameAsString();
1129 NameStr += "_";
1130
1131 if (ObjCCategoryImplDecl *CID =
1132 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1133 NameStr += CID->getNameAsString();
1134 NameStr += "_";
1135 }
1136 // Append selector names, replacing ':' with '_'
1137 {
1138 std::string selString = OMD->getSelector().getAsString();
1139 int len = selString.size();
1140 for (int i = 0; i < len; i++)
1141 if (selString[i] == ':')
1142 selString[i] = '_';
1143 NameStr += selString;
1144 }
1145 // Remember this name for metadata emission
1146 MethodInternalNames[OMD] = NameStr;
1147 ResultStr += NameStr;
1148
1149 // Rewrite arguments
1150 ResultStr += "(";
1151
1152 // invisible arguments
1153 if (OMD->isInstanceMethod()) {
1154 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1155 selfTy = Context->getPointerType(selfTy);
1156 if (!LangOpts.MicrosoftExt) {
1157 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1158 ResultStr += "struct ";
1159 }
1160 // When rewriting for Microsoft, explicitly omit the structure name.
1161 ResultStr += IDecl->getNameAsString();
1162 ResultStr += " *";
1163 }
1164 else
1165 ResultStr += Context->getObjCClassType().getAsString(
1166 Context->getPrintingPolicy());
1167
1168 ResultStr += " self, ";
1169 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1170 ResultStr += " _cmd";
1171
1172 // Method arguments.
1173 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1174 E = OMD->param_end(); PI != E; ++PI) {
1175 ParmVarDecl *PDecl = *PI;
1176 ResultStr += ", ";
1177 if (PDecl->getType()->isObjCQualifiedIdType()) {
1178 ResultStr += "id ";
1179 ResultStr += PDecl->getNameAsString();
1180 } else {
1181 std::string Name = PDecl->getNameAsString();
1182 QualType QT = PDecl->getType();
1183 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001184 (void)convertBlockPointerToFunctionPointer(QT);
1185 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001186 ResultStr += Name;
1187 }
1188 }
1189 if (OMD->isVariadic())
1190 ResultStr += ", ...";
1191 ResultStr += ") ";
1192
1193 if (FPRetType) {
1194 ResultStr += ")"; // close the precedence "scope" for "*".
1195
1196 // Now, emit the argument types (if any).
1197 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1198 ResultStr += "(";
1199 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1200 if (i) ResultStr += ", ";
1201 std::string ParamStr = FT->getArgType(i).getAsString(
1202 Context->getPrintingPolicy());
1203 ResultStr += ParamStr;
1204 }
1205 if (FT->isVariadic()) {
1206 if (FT->getNumArgs()) ResultStr += ", ";
1207 ResultStr += "...";
1208 }
1209 ResultStr += ")";
1210 } else {
1211 ResultStr += "()";
1212 }
1213 }
1214}
1215void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1216 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1217 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1218
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001219 if (IMD) {
1220 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001221 if (IMD->getIvarLBraceLoc().isValid())
1222 InsertText(IMD->getIvarLBraceLoc(), "// ");
1223 for (ObjCImplementationDecl::ivar_iterator
1224 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1225 ObjCIvarDecl *Ivar = (*I);
1226 SourceLocation LocStart = Ivar->getLocStart();
1227 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001228 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001229 if (IMD->getIvarRBraceLoc().isValid())
1230 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001231 }
1232 else
1233 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001234
1235 for (ObjCCategoryImplDecl::instmeth_iterator
1236 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1237 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1238 I != E; ++I) {
1239 std::string ResultStr;
1240 ObjCMethodDecl *OMD = *I;
1241 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1242 SourceLocation LocStart = OMD->getLocStart();
1243 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1244
1245 const char *startBuf = SM->getCharacterData(LocStart);
1246 const char *endBuf = SM->getCharacterData(LocEnd);
1247 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1248 }
1249
1250 for (ObjCCategoryImplDecl::classmeth_iterator
1251 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1252 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1253 I != E; ++I) {
1254 std::string ResultStr;
1255 ObjCMethodDecl *OMD = *I;
1256 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1257 SourceLocation LocStart = OMD->getLocStart();
1258 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1259
1260 const char *startBuf = SM->getCharacterData(LocStart);
1261 const char *endBuf = SM->getCharacterData(LocEnd);
1262 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1263 }
1264 for (ObjCCategoryImplDecl::propimpl_iterator
1265 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1266 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1267 I != E; ++I) {
1268 RewritePropertyImplDecl(*I, IMD, CID);
1269 }
1270
1271 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1272}
1273
1274void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001275 // Do not synthesize more than once.
1276 if (ObjCSynthesizedStructs.count(ClassDecl))
1277 return;
1278 // Make sure super class's are written before current class is written.
1279 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1280 while (SuperClass) {
1281 RewriteInterfaceDecl(SuperClass);
1282 SuperClass = SuperClass->getSuperClass();
1283 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001284 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001285 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001286 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001287 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001288 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1289
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001290 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001291 // Mark this typedef as having been written into its c++ equivalent.
1292 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001293
1294 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001295 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001296 RewriteProperty(*I);
1297 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001298 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001299 I != E; ++I)
1300 RewriteMethodDeclaration(*I);
1301 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001302 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001303 I != E; ++I)
1304 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001305
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001306 // Lastly, comment out the @end.
1307 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1308 "/* @end */");
1309 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001310}
1311
1312Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1313 SourceRange OldRange = PseudoOp->getSourceRange();
1314
1315 // We just magically know some things about the structure of this
1316 // expression.
1317 ObjCMessageExpr *OldMsg =
1318 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1319 PseudoOp->getNumSemanticExprs() - 1));
1320
1321 // Because the rewriter doesn't allow us to rewrite rewritten code,
1322 // we need to suppress rewriting the sub-statements.
1323 Expr *Base, *RHS;
1324 {
1325 DisableReplaceStmtScope S(*this);
1326
1327 // Rebuild the base expression if we have one.
1328 Base = 0;
1329 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1330 Base = OldMsg->getInstanceReceiver();
1331 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1332 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1333 }
1334
1335 // Rebuild the RHS.
1336 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1337 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1338 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1339 }
1340
1341 // TODO: avoid this copy.
1342 SmallVector<SourceLocation, 1> SelLocs;
1343 OldMsg->getSelectorLocs(SelLocs);
1344
1345 ObjCMessageExpr *NewMsg = 0;
1346 switch (OldMsg->getReceiverKind()) {
1347 case ObjCMessageExpr::Class:
1348 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1349 OldMsg->getValueKind(),
1350 OldMsg->getLeftLoc(),
1351 OldMsg->getClassReceiverTypeInfo(),
1352 OldMsg->getSelector(),
1353 SelLocs,
1354 OldMsg->getMethodDecl(),
1355 RHS,
1356 OldMsg->getRightLoc(),
1357 OldMsg->isImplicit());
1358 break;
1359
1360 case ObjCMessageExpr::Instance:
1361 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1362 OldMsg->getValueKind(),
1363 OldMsg->getLeftLoc(),
1364 Base,
1365 OldMsg->getSelector(),
1366 SelLocs,
1367 OldMsg->getMethodDecl(),
1368 RHS,
1369 OldMsg->getRightLoc(),
1370 OldMsg->isImplicit());
1371 break;
1372
1373 case ObjCMessageExpr::SuperClass:
1374 case ObjCMessageExpr::SuperInstance:
1375 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1376 OldMsg->getValueKind(),
1377 OldMsg->getLeftLoc(),
1378 OldMsg->getSuperLoc(),
1379 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1380 OldMsg->getSuperType(),
1381 OldMsg->getSelector(),
1382 SelLocs,
1383 OldMsg->getMethodDecl(),
1384 RHS,
1385 OldMsg->getRightLoc(),
1386 OldMsg->isImplicit());
1387 break;
1388 }
1389
1390 Stmt *Replacement = SynthMessageExpr(NewMsg);
1391 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1392 return Replacement;
1393}
1394
1395Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1396 SourceRange OldRange = PseudoOp->getSourceRange();
1397
1398 // We just magically know some things about the structure of this
1399 // expression.
1400 ObjCMessageExpr *OldMsg =
1401 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1402
1403 // Because the rewriter doesn't allow us to rewrite rewritten code,
1404 // we need to suppress rewriting the sub-statements.
1405 Expr *Base = 0;
1406 {
1407 DisableReplaceStmtScope S(*this);
1408
1409 // Rebuild the base expression if we have one.
1410 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1411 Base = OldMsg->getInstanceReceiver();
1412 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1413 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1414 }
1415 }
1416
1417 // Intentionally empty.
1418 SmallVector<SourceLocation, 1> SelLocs;
1419 SmallVector<Expr*, 1> Args;
1420
1421 ObjCMessageExpr *NewMsg = 0;
1422 switch (OldMsg->getReceiverKind()) {
1423 case ObjCMessageExpr::Class:
1424 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1425 OldMsg->getValueKind(),
1426 OldMsg->getLeftLoc(),
1427 OldMsg->getClassReceiverTypeInfo(),
1428 OldMsg->getSelector(),
1429 SelLocs,
1430 OldMsg->getMethodDecl(),
1431 Args,
1432 OldMsg->getRightLoc(),
1433 OldMsg->isImplicit());
1434 break;
1435
1436 case ObjCMessageExpr::Instance:
1437 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1438 OldMsg->getValueKind(),
1439 OldMsg->getLeftLoc(),
1440 Base,
1441 OldMsg->getSelector(),
1442 SelLocs,
1443 OldMsg->getMethodDecl(),
1444 Args,
1445 OldMsg->getRightLoc(),
1446 OldMsg->isImplicit());
1447 break;
1448
1449 case ObjCMessageExpr::SuperClass:
1450 case ObjCMessageExpr::SuperInstance:
1451 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1452 OldMsg->getValueKind(),
1453 OldMsg->getLeftLoc(),
1454 OldMsg->getSuperLoc(),
1455 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1456 OldMsg->getSuperType(),
1457 OldMsg->getSelector(),
1458 SelLocs,
1459 OldMsg->getMethodDecl(),
1460 Args,
1461 OldMsg->getRightLoc(),
1462 OldMsg->isImplicit());
1463 break;
1464 }
1465
1466 Stmt *Replacement = SynthMessageExpr(NewMsg);
1467 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1468 return Replacement;
1469}
1470
1471/// SynthCountByEnumWithState - To print:
1472/// ((unsigned int (*)
1473/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1474/// (void *)objc_msgSend)((id)l_collection,
1475/// sel_registerName(
1476/// "countByEnumeratingWithState:objects:count:"),
1477/// &enumState,
1478/// (id *)__rw_items, (unsigned int)16)
1479///
1480void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1481 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1482 "id *, unsigned int))(void *)objc_msgSend)";
1483 buf += "\n\t\t";
1484 buf += "((id)l_collection,\n\t\t";
1485 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1486 buf += "\n\t\t";
1487 buf += "&enumState, "
1488 "(id *)__rw_items, (unsigned int)16)";
1489}
1490
1491/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1492/// statement to exit to its outer synthesized loop.
1493///
1494Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1495 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1496 return S;
1497 // replace break with goto __break_label
1498 std::string buf;
1499
1500 SourceLocation startLoc = S->getLocStart();
1501 buf = "goto __break_label_";
1502 buf += utostr(ObjCBcLabelNo.back());
1503 ReplaceText(startLoc, strlen("break"), buf);
1504
1505 return 0;
1506}
1507
1508/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1509/// statement to continue with its inner synthesized loop.
1510///
1511Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1512 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1513 return S;
1514 // replace continue with goto __continue_label
1515 std::string buf;
1516
1517 SourceLocation startLoc = S->getLocStart();
1518 buf = "goto __continue_label_";
1519 buf += utostr(ObjCBcLabelNo.back());
1520 ReplaceText(startLoc, strlen("continue"), buf);
1521
1522 return 0;
1523}
1524
1525/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1526/// It rewrites:
1527/// for ( type elem in collection) { stmts; }
1528
1529/// Into:
1530/// {
1531/// type elem;
1532/// struct __objcFastEnumerationState enumState = { 0 };
1533/// id __rw_items[16];
1534/// id l_collection = (id)collection;
1535/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1536/// objects:__rw_items count:16];
1537/// if (limit) {
1538/// unsigned long startMutations = *enumState.mutationsPtr;
1539/// do {
1540/// unsigned long counter = 0;
1541/// do {
1542/// if (startMutations != *enumState.mutationsPtr)
1543/// objc_enumerationMutation(l_collection);
1544/// elem = (type)enumState.itemsPtr[counter++];
1545/// stmts;
1546/// __continue_label: ;
1547/// } while (counter < limit);
1548/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1549/// objects:__rw_items count:16]);
1550/// elem = nil;
1551/// __break_label: ;
1552/// }
1553/// else
1554/// elem = nil;
1555/// }
1556///
1557Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1558 SourceLocation OrigEnd) {
1559 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1560 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1561 "ObjCForCollectionStmt Statement stack mismatch");
1562 assert(!ObjCBcLabelNo.empty() &&
1563 "ObjCForCollectionStmt - Label No stack empty");
1564
1565 SourceLocation startLoc = S->getLocStart();
1566 const char *startBuf = SM->getCharacterData(startLoc);
1567 StringRef elementName;
1568 std::string elementTypeAsString;
1569 std::string buf;
1570 buf = "\n{\n\t";
1571 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1572 // type elem;
1573 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1574 QualType ElementType = cast<ValueDecl>(D)->getType();
1575 if (ElementType->isObjCQualifiedIdType() ||
1576 ElementType->isObjCQualifiedInterfaceType())
1577 // Simply use 'id' for all qualified types.
1578 elementTypeAsString = "id";
1579 else
1580 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1581 buf += elementTypeAsString;
1582 buf += " ";
1583 elementName = D->getName();
1584 buf += elementName;
1585 buf += ";\n\t";
1586 }
1587 else {
1588 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1589 elementName = DR->getDecl()->getName();
1590 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1591 if (VD->getType()->isObjCQualifiedIdType() ||
1592 VD->getType()->isObjCQualifiedInterfaceType())
1593 // Simply use 'id' for all qualified types.
1594 elementTypeAsString = "id";
1595 else
1596 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1597 }
1598
1599 // struct __objcFastEnumerationState enumState = { 0 };
1600 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1601 // id __rw_items[16];
1602 buf += "id __rw_items[16];\n\t";
1603 // id l_collection = (id)
1604 buf += "id l_collection = (id)";
1605 // Find start location of 'collection' the hard way!
1606 const char *startCollectionBuf = startBuf;
1607 startCollectionBuf += 3; // skip 'for'
1608 startCollectionBuf = strchr(startCollectionBuf, '(');
1609 startCollectionBuf++; // skip '('
1610 // find 'in' and skip it.
1611 while (*startCollectionBuf != ' ' ||
1612 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1613 (*(startCollectionBuf+3) != ' ' &&
1614 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1615 startCollectionBuf++;
1616 startCollectionBuf += 3;
1617
1618 // Replace: "for (type element in" with string constructed thus far.
1619 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1620 // Replace ')' in for '(' type elem in collection ')' with ';'
1621 SourceLocation rightParenLoc = S->getRParenLoc();
1622 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1623 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1624 buf = ";\n\t";
1625
1626 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1627 // objects:__rw_items count:16];
1628 // which is synthesized into:
1629 // unsigned int limit =
1630 // ((unsigned int (*)
1631 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1632 // (void *)objc_msgSend)((id)l_collection,
1633 // sel_registerName(
1634 // "countByEnumeratingWithState:objects:count:"),
1635 // (struct __objcFastEnumerationState *)&state,
1636 // (id *)__rw_items, (unsigned int)16);
1637 buf += "unsigned long limit =\n\t\t";
1638 SynthCountByEnumWithState(buf);
1639 buf += ";\n\t";
1640 /// if (limit) {
1641 /// unsigned long startMutations = *enumState.mutationsPtr;
1642 /// do {
1643 /// unsigned long counter = 0;
1644 /// do {
1645 /// if (startMutations != *enumState.mutationsPtr)
1646 /// objc_enumerationMutation(l_collection);
1647 /// elem = (type)enumState.itemsPtr[counter++];
1648 buf += "if (limit) {\n\t";
1649 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1650 buf += "do {\n\t\t";
1651 buf += "unsigned long counter = 0;\n\t\t";
1652 buf += "do {\n\t\t\t";
1653 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1654 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1655 buf += elementName;
1656 buf += " = (";
1657 buf += elementTypeAsString;
1658 buf += ")enumState.itemsPtr[counter++];";
1659 // Replace ')' in for '(' type elem in collection ')' with all of these.
1660 ReplaceText(lparenLoc, 1, buf);
1661
1662 /// __continue_label: ;
1663 /// } while (counter < limit);
1664 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1665 /// objects:__rw_items count:16]);
1666 /// elem = nil;
1667 /// __break_label: ;
1668 /// }
1669 /// else
1670 /// elem = nil;
1671 /// }
1672 ///
1673 buf = ";\n\t";
1674 buf += "__continue_label_";
1675 buf += utostr(ObjCBcLabelNo.back());
1676 buf += ": ;";
1677 buf += "\n\t\t";
1678 buf += "} while (counter < limit);\n\t";
1679 buf += "} while (limit = ";
1680 SynthCountByEnumWithState(buf);
1681 buf += ");\n\t";
1682 buf += elementName;
1683 buf += " = ((";
1684 buf += elementTypeAsString;
1685 buf += ")0);\n\t";
1686 buf += "__break_label_";
1687 buf += utostr(ObjCBcLabelNo.back());
1688 buf += ": ;\n\t";
1689 buf += "}\n\t";
1690 buf += "else\n\t\t";
1691 buf += elementName;
1692 buf += " = ((";
1693 buf += elementTypeAsString;
1694 buf += ")0);\n\t";
1695 buf += "}\n";
1696
1697 // Insert all these *after* the statement body.
1698 // FIXME: If this should support Obj-C++, support CXXTryStmt
1699 if (isa<CompoundStmt>(S->getBody())) {
1700 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1701 InsertText(endBodyLoc, buf);
1702 } else {
1703 /* Need to treat single statements specially. For example:
1704 *
1705 * for (A *a in b) if (stuff()) break;
1706 * for (A *a in b) xxxyy;
1707 *
1708 * The following code simply scans ahead to the semi to find the actual end.
1709 */
1710 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1711 const char *semiBuf = strchr(stmtBuf, ';');
1712 assert(semiBuf && "Can't find ';'");
1713 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1714 InsertText(endBodyLoc, buf);
1715 }
1716 Stmts.pop_back();
1717 ObjCBcLabelNo.pop_back();
1718 return 0;
1719}
1720
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001721static void Write_RethrowObject(std::string &buf) {
1722 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1723 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1724 buf += "\tid rethrow;\n";
1725 buf += "\t} _fin_force_rethow(_rethrow);";
1726}
1727
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001728/// RewriteObjCSynchronizedStmt -
1729/// This routine rewrites @synchronized(expr) stmt;
1730/// into:
1731/// objc_sync_enter(expr);
1732/// @try stmt @finally { objc_sync_exit(expr); }
1733///
1734Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1735 // Get the start location and compute the semi location.
1736 SourceLocation startLoc = S->getLocStart();
1737 const char *startBuf = SM->getCharacterData(startLoc);
1738
1739 assert((*startBuf == '@') && "bogus @synchronized location");
1740
1741 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001742 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001743
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001744 const char *lparenBuf = startBuf;
1745 while (*lparenBuf != '(') lparenBuf++;
1746 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001747
1748 buf = "; objc_sync_enter(_sync_obj);\n";
1749 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1750 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1751 buf += "\n\tid sync_exit;";
1752 buf += "\n\t} _sync_exit(_sync_obj);\n";
1753
1754 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1755 // the sync expression is typically a message expression that's already
1756 // been rewritten! (which implies the SourceLocation's are invalid).
1757 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1758 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1759 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1760 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1761
1762 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1763 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1764 assert (*LBraceLocBuf == '{');
1765 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001766
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001767 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001768 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1769 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001770
1771 buf = "} catch (id e) {_rethrow = e;}\n";
1772 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001773 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001774 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001775
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001776 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001777
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001778 return 0;
1779}
1780
1781void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1782{
1783 // Perform a bottom up traversal of all children.
1784 for (Stmt::child_range CI = S->children(); CI; ++CI)
1785 if (*CI)
1786 WarnAboutReturnGotoStmts(*CI);
1787
1788 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1789 Diags.Report(Context->getFullLoc(S->getLocStart()),
1790 TryFinallyContainsReturnDiag);
1791 }
1792 return;
1793}
1794
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001795Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001796 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001797 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001798 std::string buf;
1799
1800 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001801 if (noCatch)
1802 buf = "{ id volatile _rethrow = 0;\n";
1803 else {
1804 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1805 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001806 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001807 // Get the start location and compute the semi location.
1808 SourceLocation startLoc = S->getLocStart();
1809 const char *startBuf = SM->getCharacterData(startLoc);
1810
1811 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001812 if (finalStmt)
1813 ReplaceText(startLoc, 1, buf);
1814 else
1815 // @try -> try
1816 ReplaceText(startLoc, 1, "");
1817
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001818 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1819 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001820 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001821
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001822 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001823 bool AtRemoved = false;
1824 if (catchDecl) {
1825 QualType t = catchDecl->getType();
1826 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1827 // Should be a pointer to a class.
1828 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1829 if (IDecl) {
1830 std::string Result;
1831 startBuf = SM->getCharacterData(startLoc);
1832 assert((*startBuf == '@') && "bogus @catch location");
1833 SourceLocation rParenLoc = Catch->getRParenLoc();
1834 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1835
1836 // _objc_exc_Foo *_e as argument to catch.
1837 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1838 Result += " *_"; Result += catchDecl->getNameAsString();
1839 Result += ")";
1840 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1841 // Foo *e = (Foo *)_e;
1842 Result.clear();
1843 Result = "{ ";
1844 Result += IDecl->getNameAsString();
1845 Result += " *"; Result += catchDecl->getNameAsString();
1846 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1847 Result += "_"; Result += catchDecl->getNameAsString();
1848
1849 Result += "; ";
1850 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1851 ReplaceText(lBraceLoc, 1, Result);
1852 AtRemoved = true;
1853 }
1854 }
1855 }
1856 if (!AtRemoved)
1857 // @catch -> catch
1858 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001859
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001860 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001861 if (finalStmt) {
1862 buf.clear();
1863 if (noCatch)
1864 buf = "catch (id e) {_rethrow = e;}\n";
1865 else
1866 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1867
1868 SourceLocation startFinalLoc = finalStmt->getLocStart();
1869 ReplaceText(startFinalLoc, 8, buf);
1870 Stmt *body = finalStmt->getFinallyBody();
1871 SourceLocation startFinalBodyLoc = body->getLocStart();
1872 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001873 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001874 ReplaceText(startFinalBodyLoc, 1, buf);
1875
1876 SourceLocation endFinalBodyLoc = body->getLocEnd();
1877 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001878 // Now check for any return/continue/go statements within the @try.
1879 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001880 }
1881
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001882 return 0;
1883}
1884
1885// This can't be done with ReplaceStmt(S, ThrowExpr), since
1886// the throw expression is typically a message expression that's already
1887// been rewritten! (which implies the SourceLocation's are invalid).
1888Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1889 // Get the start location and compute the semi location.
1890 SourceLocation startLoc = S->getLocStart();
1891 const char *startBuf = SM->getCharacterData(startLoc);
1892
1893 assert((*startBuf == '@') && "bogus @throw location");
1894
1895 std::string buf;
1896 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1897 if (S->getThrowExpr())
1898 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001899 else
1900 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001901
1902 // handle "@ throw" correctly.
1903 const char *wBuf = strchr(startBuf, 'w');
1904 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1905 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1906
1907 const char *semiBuf = strchr(startBuf, ';');
1908 assert((*semiBuf == ';') && "@throw: can't find ';'");
1909 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001910 if (S->getThrowExpr())
1911 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001912 return 0;
1913}
1914
1915Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1916 // Create a new string expression.
1917 QualType StrType = Context->getPointerType(Context->CharTy);
1918 std::string StrEncoding;
1919 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1920 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1921 StringLiteral::Ascii, false,
1922 StrType, SourceLocation());
1923 ReplaceStmt(Exp, Replacement);
1924
1925 // Replace this subexpr in the parent.
1926 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1927 return Replacement;
1928}
1929
1930Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1931 if (!SelGetUidFunctionDecl)
1932 SynthSelGetUidFunctionDecl();
1933 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1934 // Create a call to sel_registerName("selName").
1935 SmallVector<Expr*, 8> SelExprs;
1936 QualType argType = Context->getPointerType(Context->CharTy);
1937 SelExprs.push_back(StringLiteral::Create(*Context,
1938 Exp->getSelector().getAsString(),
1939 StringLiteral::Ascii, false,
1940 argType, SourceLocation()));
1941 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1942 &SelExprs[0], SelExprs.size());
1943 ReplaceStmt(Exp, SelExp);
1944 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1945 return SelExp;
1946}
1947
1948CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1949 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1950 SourceLocation EndLoc) {
1951 // Get the type, we will need to reference it in a couple spots.
1952 QualType msgSendType = FD->getType();
1953
1954 // Create a reference to the objc_msgSend() declaration.
1955 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001956 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001957
1958 // Now, we cast the reference to a pointer to the objc_msgSend type.
1959 QualType pToFunc = Context->getPointerType(msgSendType);
1960 ImplicitCastExpr *ICE =
1961 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1962 DRE, 0, VK_RValue);
1963
1964 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1965
1966 CallExpr *Exp =
1967 new (Context) CallExpr(*Context, ICE, args, nargs,
1968 FT->getCallResultType(*Context),
1969 VK_RValue, EndLoc);
1970 return Exp;
1971}
1972
1973static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1974 const char *&startRef, const char *&endRef) {
1975 while (startBuf < endBuf) {
1976 if (*startBuf == '<')
1977 startRef = startBuf; // mark the start.
1978 if (*startBuf == '>') {
1979 if (startRef && *startRef == '<') {
1980 endRef = startBuf; // mark the end.
1981 return true;
1982 }
1983 return false;
1984 }
1985 startBuf++;
1986 }
1987 return false;
1988}
1989
1990static void scanToNextArgument(const char *&argRef) {
1991 int angle = 0;
1992 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1993 if (*argRef == '<')
1994 angle++;
1995 else if (*argRef == '>')
1996 angle--;
1997 argRef++;
1998 }
1999 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2000}
2001
2002bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2003 if (T->isObjCQualifiedIdType())
2004 return true;
2005 if (const PointerType *PT = T->getAs<PointerType>()) {
2006 if (PT->getPointeeType()->isObjCQualifiedIdType())
2007 return true;
2008 }
2009 if (T->isObjCObjectPointerType()) {
2010 T = T->getPointeeType();
2011 return T->isObjCQualifiedInterfaceType();
2012 }
2013 if (T->isArrayType()) {
2014 QualType ElemTy = Context->getBaseElementType(T);
2015 return needToScanForQualifiers(ElemTy);
2016 }
2017 return false;
2018}
2019
2020void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2021 QualType Type = E->getType();
2022 if (needToScanForQualifiers(Type)) {
2023 SourceLocation Loc, EndLoc;
2024
2025 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2026 Loc = ECE->getLParenLoc();
2027 EndLoc = ECE->getRParenLoc();
2028 } else {
2029 Loc = E->getLocStart();
2030 EndLoc = E->getLocEnd();
2031 }
2032 // This will defend against trying to rewrite synthesized expressions.
2033 if (Loc.isInvalid() || EndLoc.isInvalid())
2034 return;
2035
2036 const char *startBuf = SM->getCharacterData(Loc);
2037 const char *endBuf = SM->getCharacterData(EndLoc);
2038 const char *startRef = 0, *endRef = 0;
2039 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2040 // Get the locations of the startRef, endRef.
2041 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2042 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2043 // Comment out the protocol references.
2044 InsertText(LessLoc, "/*");
2045 InsertText(GreaterLoc, "*/");
2046 }
2047 }
2048}
2049
2050void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2051 SourceLocation Loc;
2052 QualType Type;
2053 const FunctionProtoType *proto = 0;
2054 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2055 Loc = VD->getLocation();
2056 Type = VD->getType();
2057 }
2058 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2059 Loc = FD->getLocation();
2060 // Check for ObjC 'id' and class types that have been adorned with protocol
2061 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2062 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2063 assert(funcType && "missing function type");
2064 proto = dyn_cast<FunctionProtoType>(funcType);
2065 if (!proto)
2066 return;
2067 Type = proto->getResultType();
2068 }
2069 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2070 Loc = FD->getLocation();
2071 Type = FD->getType();
2072 }
2073 else
2074 return;
2075
2076 if (needToScanForQualifiers(Type)) {
2077 // Since types are unique, we need to scan the buffer.
2078
2079 const char *endBuf = SM->getCharacterData(Loc);
2080 const char *startBuf = endBuf;
2081 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2082 startBuf--; // scan backward (from the decl location) for return type.
2083 const char *startRef = 0, *endRef = 0;
2084 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2085 // Get the locations of the startRef, endRef.
2086 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2087 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2088 // Comment out the protocol references.
2089 InsertText(LessLoc, "/*");
2090 InsertText(GreaterLoc, "*/");
2091 }
2092 }
2093 if (!proto)
2094 return; // most likely, was a variable
2095 // Now check arguments.
2096 const char *startBuf = SM->getCharacterData(Loc);
2097 const char *startFuncBuf = startBuf;
2098 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2099 if (needToScanForQualifiers(proto->getArgType(i))) {
2100 // Since types are unique, we need to scan the buffer.
2101
2102 const char *endBuf = startBuf;
2103 // scan forward (from the decl location) for argument types.
2104 scanToNextArgument(endBuf);
2105 const char *startRef = 0, *endRef = 0;
2106 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2107 // Get the locations of the startRef, endRef.
2108 SourceLocation LessLoc =
2109 Loc.getLocWithOffset(startRef-startFuncBuf);
2110 SourceLocation GreaterLoc =
2111 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2112 // Comment out the protocol references.
2113 InsertText(LessLoc, "/*");
2114 InsertText(GreaterLoc, "*/");
2115 }
2116 startBuf = ++endBuf;
2117 }
2118 else {
2119 // If the function name is derived from a macro expansion, then the
2120 // argument buffer will not follow the name. Need to speak with Chris.
2121 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2122 startBuf++; // scan forward (from the decl location) for argument types.
2123 startBuf++;
2124 }
2125 }
2126}
2127
2128void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2129 QualType QT = ND->getType();
2130 const Type* TypePtr = QT->getAs<Type>();
2131 if (!isa<TypeOfExprType>(TypePtr))
2132 return;
2133 while (isa<TypeOfExprType>(TypePtr)) {
2134 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2135 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2136 TypePtr = QT->getAs<Type>();
2137 }
2138 // FIXME. This will not work for multiple declarators; as in:
2139 // __typeof__(a) b,c,d;
2140 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2141 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2142 const char *startBuf = SM->getCharacterData(DeclLoc);
2143 if (ND->getInit()) {
2144 std::string Name(ND->getNameAsString());
2145 TypeAsString += " " + Name + " = ";
2146 Expr *E = ND->getInit();
2147 SourceLocation startLoc;
2148 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2149 startLoc = ECE->getLParenLoc();
2150 else
2151 startLoc = E->getLocStart();
2152 startLoc = SM->getExpansionLoc(startLoc);
2153 const char *endBuf = SM->getCharacterData(startLoc);
2154 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2155 }
2156 else {
2157 SourceLocation X = ND->getLocEnd();
2158 X = SM->getExpansionLoc(X);
2159 const char *endBuf = SM->getCharacterData(X);
2160 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2161 }
2162}
2163
2164// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2165void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2166 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2167 SmallVector<QualType, 16> ArgTys;
2168 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2169 QualType getFuncType =
2170 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2171 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2172 SourceLocation(),
2173 SourceLocation(),
2174 SelGetUidIdent, getFuncType, 0,
2175 SC_Extern,
2176 SC_None, false);
2177}
2178
2179void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2180 // declared in <objc/objc.h>
2181 if (FD->getIdentifier() &&
2182 FD->getName() == "sel_registerName") {
2183 SelGetUidFunctionDecl = FD;
2184 return;
2185 }
2186 RewriteObjCQualifiedInterfaceTypes(FD);
2187}
2188
2189void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2190 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2191 const char *argPtr = TypeString.c_str();
2192 if (!strchr(argPtr, '^')) {
2193 Str += TypeString;
2194 return;
2195 }
2196 while (*argPtr) {
2197 Str += (*argPtr == '^' ? '*' : *argPtr);
2198 argPtr++;
2199 }
2200}
2201
2202// FIXME. Consolidate this routine with RewriteBlockPointerType.
2203void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2204 ValueDecl *VD) {
2205 QualType Type = VD->getType();
2206 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2207 const char *argPtr = TypeString.c_str();
2208 int paren = 0;
2209 while (*argPtr) {
2210 switch (*argPtr) {
2211 case '(':
2212 Str += *argPtr;
2213 paren++;
2214 break;
2215 case ')':
2216 Str += *argPtr;
2217 paren--;
2218 break;
2219 case '^':
2220 Str += '*';
2221 if (paren == 1)
2222 Str += VD->getNameAsString();
2223 break;
2224 default:
2225 Str += *argPtr;
2226 break;
2227 }
2228 argPtr++;
2229 }
2230}
2231
2232
2233void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2234 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2235 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2236 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2237 if (!proto)
2238 return;
2239 QualType Type = proto->getResultType();
2240 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2241 FdStr += " ";
2242 FdStr += FD->getName();
2243 FdStr += "(";
2244 unsigned numArgs = proto->getNumArgs();
2245 for (unsigned i = 0; i < numArgs; i++) {
2246 QualType ArgType = proto->getArgType(i);
2247 RewriteBlockPointerType(FdStr, ArgType);
2248 if (i+1 < numArgs)
2249 FdStr += ", ";
2250 }
2251 FdStr += ");\n";
2252 InsertText(FunLocStart, FdStr);
2253 CurFunctionDeclToDeclareForBlock = 0;
2254}
2255
2256// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2257void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2258 if (SuperContructorFunctionDecl)
2259 return;
2260 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2261 SmallVector<QualType, 16> ArgTys;
2262 QualType argT = Context->getObjCIdType();
2263 assert(!argT.isNull() && "Can't find 'id' type");
2264 ArgTys.push_back(argT);
2265 ArgTys.push_back(argT);
2266 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2267 &ArgTys[0], ArgTys.size());
2268 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2269 SourceLocation(),
2270 SourceLocation(),
2271 msgSendIdent, msgSendType, 0,
2272 SC_Extern,
2273 SC_None, false);
2274}
2275
2276// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2277void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2278 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2279 SmallVector<QualType, 16> ArgTys;
2280 QualType argT = Context->getObjCIdType();
2281 assert(!argT.isNull() && "Can't find 'id' type");
2282 ArgTys.push_back(argT);
2283 argT = Context->getObjCSelType();
2284 assert(!argT.isNull() && "Can't find 'SEL' type");
2285 ArgTys.push_back(argT);
2286 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2287 &ArgTys[0], ArgTys.size(),
2288 true /*isVariadic*/);
2289 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2290 SourceLocation(),
2291 SourceLocation(),
2292 msgSendIdent, msgSendType, 0,
2293 SC_Extern,
2294 SC_None, false);
2295}
2296
2297// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2298void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2299 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2300 SmallVector<QualType, 16> ArgTys;
2301 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2302 SourceLocation(), SourceLocation(),
2303 &Context->Idents.get("objc_super"));
2304 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2305 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2306 ArgTys.push_back(argT);
2307 argT = Context->getObjCSelType();
2308 assert(!argT.isNull() && "Can't find 'SEL' type");
2309 ArgTys.push_back(argT);
2310 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2311 &ArgTys[0], ArgTys.size(),
2312 true /*isVariadic*/);
2313 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2314 SourceLocation(),
2315 SourceLocation(),
2316 msgSendIdent, msgSendType, 0,
2317 SC_Extern,
2318 SC_None, false);
2319}
2320
2321// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2322void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2323 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2324 SmallVector<QualType, 16> ArgTys;
2325 QualType argT = Context->getObjCIdType();
2326 assert(!argT.isNull() && "Can't find 'id' type");
2327 ArgTys.push_back(argT);
2328 argT = Context->getObjCSelType();
2329 assert(!argT.isNull() && "Can't find 'SEL' type");
2330 ArgTys.push_back(argT);
2331 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2332 &ArgTys[0], ArgTys.size(),
2333 true /*isVariadic*/);
2334 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2335 SourceLocation(),
2336 SourceLocation(),
2337 msgSendIdent, msgSendType, 0,
2338 SC_Extern,
2339 SC_None, false);
2340}
2341
2342// SynthMsgSendSuperStretFunctionDecl -
2343// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2344void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2345 IdentifierInfo *msgSendIdent =
2346 &Context->Idents.get("objc_msgSendSuper_stret");
2347 SmallVector<QualType, 16> ArgTys;
2348 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2349 SourceLocation(), SourceLocation(),
2350 &Context->Idents.get("objc_super"));
2351 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2352 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2353 ArgTys.push_back(argT);
2354 argT = Context->getObjCSelType();
2355 assert(!argT.isNull() && "Can't find 'SEL' type");
2356 ArgTys.push_back(argT);
2357 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2358 &ArgTys[0], ArgTys.size(),
2359 true /*isVariadic*/);
2360 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2361 SourceLocation(),
2362 SourceLocation(),
2363 msgSendIdent, msgSendType, 0,
2364 SC_Extern,
2365 SC_None, false);
2366}
2367
2368// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2369void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2370 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2371 SmallVector<QualType, 16> ArgTys;
2372 QualType argT = Context->getObjCIdType();
2373 assert(!argT.isNull() && "Can't find 'id' type");
2374 ArgTys.push_back(argT);
2375 argT = Context->getObjCSelType();
2376 assert(!argT.isNull() && "Can't find 'SEL' type");
2377 ArgTys.push_back(argT);
2378 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2379 &ArgTys[0], ArgTys.size(),
2380 true /*isVariadic*/);
2381 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2382 SourceLocation(),
2383 SourceLocation(),
2384 msgSendIdent, msgSendType, 0,
2385 SC_Extern,
2386 SC_None, false);
2387}
2388
2389// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2390void RewriteModernObjC::SynthGetClassFunctionDecl() {
2391 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2392 SmallVector<QualType, 16> ArgTys;
2393 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2394 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2395 &ArgTys[0], ArgTys.size());
2396 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2397 SourceLocation(),
2398 SourceLocation(),
2399 getClassIdent, getClassType, 0,
2400 SC_Extern,
2401 SC_None, false);
2402}
2403
2404// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2405void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2406 IdentifierInfo *getSuperClassIdent =
2407 &Context->Idents.get("class_getSuperclass");
2408 SmallVector<QualType, 16> ArgTys;
2409 ArgTys.push_back(Context->getObjCClassType());
2410 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2411 &ArgTys[0], ArgTys.size());
2412 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2413 SourceLocation(),
2414 SourceLocation(),
2415 getSuperClassIdent,
2416 getClassType, 0,
2417 SC_Extern,
2418 SC_None,
2419 false);
2420}
2421
2422// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2423void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2424 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2425 SmallVector<QualType, 16> ArgTys;
2426 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2427 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2428 &ArgTys[0], ArgTys.size());
2429 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2430 SourceLocation(),
2431 SourceLocation(),
2432 getClassIdent, getClassType, 0,
2433 SC_Extern,
2434 SC_None, false);
2435}
2436
2437Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2438 QualType strType = getConstantStringStructType();
2439
2440 std::string S = "__NSConstantStringImpl_";
2441
2442 std::string tmpName = InFileName;
2443 unsigned i;
2444 for (i=0; i < tmpName.length(); i++) {
2445 char c = tmpName.at(i);
2446 // replace any non alphanumeric characters with '_'.
2447 if (!isalpha(c) && (c < '0' || c > '9'))
2448 tmpName[i] = '_';
2449 }
2450 S += tmpName;
2451 S += "_";
2452 S += utostr(NumObjCStringLiterals++);
2453
2454 Preamble += "static __NSConstantStringImpl " + S;
2455 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2456 Preamble += "0x000007c8,"; // utf8_str
2457 // The pretty printer for StringLiteral handles escape characters properly.
2458 std::string prettyBufS;
2459 llvm::raw_string_ostream prettyBuf(prettyBufS);
2460 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2461 PrintingPolicy(LangOpts));
2462 Preamble += prettyBuf.str();
2463 Preamble += ",";
2464 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2465
2466 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2467 SourceLocation(), &Context->Idents.get(S),
2468 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002469 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002470 SourceLocation());
2471 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2472 Context->getPointerType(DRE->getType()),
2473 VK_RValue, OK_Ordinary,
2474 SourceLocation());
2475 // cast to NSConstantString *
2476 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2477 CK_CPointerToObjCPointerCast, Unop);
2478 ReplaceStmt(Exp, cast);
2479 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2480 return cast;
2481}
2482
Fariborz Jahanian55947042012-03-27 20:17:30 +00002483Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2484 unsigned IntSize =
2485 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2486
2487 Expr *FlagExp = IntegerLiteral::Create(*Context,
2488 llvm::APInt(IntSize, Exp->getValue()),
2489 Context->IntTy, Exp->getLocation());
2490 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2491 CK_BitCast, FlagExp);
2492 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2493 cast);
2494 ReplaceStmt(Exp, PE);
2495 return PE;
2496}
2497
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002498Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2499 // synthesize declaration of helper functions needed in this routine.
2500 if (!SelGetUidFunctionDecl)
2501 SynthSelGetUidFunctionDecl();
2502 // use objc_msgSend() for all.
2503 if (!MsgSendFunctionDecl)
2504 SynthMsgSendFunctionDecl();
2505 if (!GetClassFunctionDecl)
2506 SynthGetClassFunctionDecl();
2507
2508 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2509 SourceLocation StartLoc = Exp->getLocStart();
2510 SourceLocation EndLoc = Exp->getLocEnd();
2511
2512 // Synthesize a call to objc_msgSend().
2513 SmallVector<Expr*, 4> MsgExprs;
2514 SmallVector<Expr*, 4> ClsExprs;
2515 QualType argType = Context->getPointerType(Context->CharTy);
2516 QualType expType = Exp->getType();
2517
2518 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2519 ObjCInterfaceDecl *Class =
2520 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2521
2522 IdentifierInfo *clsName = Class->getIdentifier();
2523 ClsExprs.push_back(StringLiteral::Create(*Context,
2524 clsName->getName(),
2525 StringLiteral::Ascii, false,
2526 argType, SourceLocation()));
2527 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2528 &ClsExprs[0],
2529 ClsExprs.size(),
2530 StartLoc, EndLoc);
2531 MsgExprs.push_back(Cls);
2532
2533 // Create a call to sel_registerName("numberWithBool:"), etc.
2534 // it will be the 2nd argument.
2535 SmallVector<Expr*, 4> SelExprs;
2536 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2537 SelExprs.push_back(StringLiteral::Create(*Context,
2538 NumericMethod->getSelector().getAsString(),
2539 StringLiteral::Ascii, false,
2540 argType, SourceLocation()));
2541 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2542 &SelExprs[0], SelExprs.size(),
2543 StartLoc, EndLoc);
2544 MsgExprs.push_back(SelExp);
2545
2546 // User provided numeric literal is the 3rd, and last, argument.
2547 Expr *userExpr = Exp->getNumber();
2548 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2549 QualType type = ICE->getType();
2550 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2551 CastKind CK = CK_BitCast;
2552 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2553 CK = CK_IntegralToBoolean;
2554 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2555 }
2556 MsgExprs.push_back(userExpr);
2557
2558 SmallVector<QualType, 4> ArgTypes;
2559 ArgTypes.push_back(Context->getObjCIdType());
2560 ArgTypes.push_back(Context->getObjCSelType());
2561 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2562 E = NumericMethod->param_end(); PI != E; ++PI)
2563 ArgTypes.push_back((*PI)->getType());
2564
2565 QualType returnType = Exp->getType();
2566 // Get the type, we will need to reference it in a couple spots.
2567 QualType msgSendType = MsgSendFlavor->getType();
2568
2569 // Create a reference to the objc_msgSend() declaration.
2570 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2571 VK_LValue, SourceLocation());
2572
2573 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2574 Context->getPointerType(Context->VoidTy),
2575 CK_BitCast, DRE);
2576
2577 // Now do the "normal" pointer to function cast.
2578 QualType castType =
2579 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2580 NumericMethod->isVariadic());
2581 castType = Context->getPointerType(castType);
2582 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2583 cast);
2584
2585 // Don't forget the parens to enforce the proper binding.
2586 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2587
2588 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2589 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2590 MsgExprs.size(),
2591 FT->getResultType(), VK_RValue,
2592 EndLoc);
2593 ReplaceStmt(Exp, CE);
2594 return CE;
2595}
2596
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002597Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2598 // synthesize declaration of helper functions needed in this routine.
2599 if (!SelGetUidFunctionDecl)
2600 SynthSelGetUidFunctionDecl();
2601 // use objc_msgSend() for all.
2602 if (!MsgSendFunctionDecl)
2603 SynthMsgSendFunctionDecl();
2604 if (!GetClassFunctionDecl)
2605 SynthGetClassFunctionDecl();
2606
2607 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2608 SourceLocation StartLoc = Exp->getLocStart();
2609 SourceLocation EndLoc = Exp->getLocEnd();
2610
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002611 // Build the expression: __NSArray_literal(int, ...).arr
2612 QualType IntQT = Context->IntTy;
2613 QualType NSArrayFType =
2614 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2615 std::string NSArrayFName("__NSArray_literal");
2616 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2617 DeclRefExpr *NSArrayDRE =
2618 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2619 SourceLocation());
2620
2621 SmallVector<Expr*, 16> InitExprs;
2622 unsigned NumElements = Exp->getNumElements();
2623 unsigned UnsignedIntSize =
2624 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2625 Expr *count = IntegerLiteral::Create(*Context,
2626 llvm::APInt(UnsignedIntSize, NumElements),
2627 Context->UnsignedIntTy, SourceLocation());
2628 InitExprs.push_back(count);
2629 for (unsigned i = 0; i < NumElements; i++)
2630 InitExprs.push_back(Exp->getElement(i));
2631 Expr *NSArrayCallExpr =
2632 new (Context) CallExpr(*Context, NSArrayDRE, &InitExprs[0], InitExprs.size(),
2633 NSArrayFType, VK_LValue, SourceLocation());
2634
2635 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2636 SourceLocation(),
2637 &Context->Idents.get("arr"),
2638 Context->getPointerType(Context->VoidPtrTy), 0,
2639 /*BitWidth=*/0, /*Mutable=*/true,
2640 /*HasInit=*/false);
2641 MemberExpr *ArrayLiteralME =
2642 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2643 SourceLocation(),
2644 ARRFD->getType(), VK_LValue,
2645 OK_Ordinary);
2646 QualType ConstIdT = Context->getObjCIdType().withConst();
2647 CStyleCastExpr * ArrayLiteralObjects =
2648 NoTypeInfoCStyleCastExpr(Context,
2649 Context->getPointerType(ConstIdT),
2650 CK_BitCast,
2651 ArrayLiteralME);
2652
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002653 // Synthesize a call to objc_msgSend().
2654 SmallVector<Expr*, 32> MsgExprs;
2655 SmallVector<Expr*, 4> ClsExprs;
2656 QualType argType = Context->getPointerType(Context->CharTy);
2657 QualType expType = Exp->getType();
2658
2659 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2660 ObjCInterfaceDecl *Class =
2661 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2662
2663 IdentifierInfo *clsName = Class->getIdentifier();
2664 ClsExprs.push_back(StringLiteral::Create(*Context,
2665 clsName->getName(),
2666 StringLiteral::Ascii, false,
2667 argType, SourceLocation()));
2668 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2669 &ClsExprs[0],
2670 ClsExprs.size(),
2671 StartLoc, EndLoc);
2672 MsgExprs.push_back(Cls);
2673
2674 // Create a call to sel_registerName("arrayWithObjects:count:").
2675 // it will be the 2nd argument.
2676 SmallVector<Expr*, 4> SelExprs;
2677 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2678 SelExprs.push_back(StringLiteral::Create(*Context,
2679 ArrayMethod->getSelector().getAsString(),
2680 StringLiteral::Ascii, false,
2681 argType, SourceLocation()));
2682 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2683 &SelExprs[0], SelExprs.size(),
2684 StartLoc, EndLoc);
2685 MsgExprs.push_back(SelExp);
2686
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002687 // (const id [])objects
2688 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002689
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002690 // (NSUInteger)cnt
2691 Expr *cnt = IntegerLiteral::Create(*Context,
2692 llvm::APInt(UnsignedIntSize, NumElements),
2693 Context->UnsignedIntTy, SourceLocation());
2694 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002695
2696
2697 SmallVector<QualType, 4> ArgTypes;
2698 ArgTypes.push_back(Context->getObjCIdType());
2699 ArgTypes.push_back(Context->getObjCSelType());
2700 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2701 E = ArrayMethod->param_end(); PI != E; ++PI)
2702 ArgTypes.push_back((*PI)->getType());
2703
2704 QualType returnType = Exp->getType();
2705 // Get the type, we will need to reference it in a couple spots.
2706 QualType msgSendType = MsgSendFlavor->getType();
2707
2708 // Create a reference to the objc_msgSend() declaration.
2709 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2710 VK_LValue, SourceLocation());
2711
2712 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2713 Context->getPointerType(Context->VoidTy),
2714 CK_BitCast, DRE);
2715
2716 // Now do the "normal" pointer to function cast.
2717 QualType castType =
2718 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2719 ArrayMethod->isVariadic());
2720 castType = Context->getPointerType(castType);
2721 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2722 cast);
2723
2724 // Don't forget the parens to enforce the proper binding.
2725 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2726
2727 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2728 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2729 MsgExprs.size(),
2730 FT->getResultType(), VK_RValue,
2731 EndLoc);
2732 ReplaceStmt(Exp, CE);
2733 return CE;
2734}
2735
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002736// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2737QualType RewriteModernObjC::getSuperStructType() {
2738 if (!SuperStructDecl) {
2739 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2740 SourceLocation(), SourceLocation(),
2741 &Context->Idents.get("objc_super"));
2742 QualType FieldTypes[2];
2743
2744 // struct objc_object *receiver;
2745 FieldTypes[0] = Context->getObjCIdType();
2746 // struct objc_class *super;
2747 FieldTypes[1] = Context->getObjCClassType();
2748
2749 // Create fields
2750 for (unsigned i = 0; i < 2; ++i) {
2751 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2752 SourceLocation(),
2753 SourceLocation(), 0,
2754 FieldTypes[i], 0,
2755 /*BitWidth=*/0,
2756 /*Mutable=*/false,
2757 /*HasInit=*/false));
2758 }
2759
2760 SuperStructDecl->completeDefinition();
2761 }
2762 return Context->getTagDeclType(SuperStructDecl);
2763}
2764
2765QualType RewriteModernObjC::getConstantStringStructType() {
2766 if (!ConstantStringDecl) {
2767 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2768 SourceLocation(), SourceLocation(),
2769 &Context->Idents.get("__NSConstantStringImpl"));
2770 QualType FieldTypes[4];
2771
2772 // struct objc_object *receiver;
2773 FieldTypes[0] = Context->getObjCIdType();
2774 // int flags;
2775 FieldTypes[1] = Context->IntTy;
2776 // char *str;
2777 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2778 // long length;
2779 FieldTypes[3] = Context->LongTy;
2780
2781 // Create fields
2782 for (unsigned i = 0; i < 4; ++i) {
2783 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2784 ConstantStringDecl,
2785 SourceLocation(),
2786 SourceLocation(), 0,
2787 FieldTypes[i], 0,
2788 /*BitWidth=*/0,
2789 /*Mutable=*/true,
2790 /*HasInit=*/false));
2791 }
2792
2793 ConstantStringDecl->completeDefinition();
2794 }
2795 return Context->getTagDeclType(ConstantStringDecl);
2796}
2797
2798Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2799 SourceLocation StartLoc,
2800 SourceLocation EndLoc) {
2801 if (!SelGetUidFunctionDecl)
2802 SynthSelGetUidFunctionDecl();
2803 if (!MsgSendFunctionDecl)
2804 SynthMsgSendFunctionDecl();
2805 if (!MsgSendSuperFunctionDecl)
2806 SynthMsgSendSuperFunctionDecl();
2807 if (!MsgSendStretFunctionDecl)
2808 SynthMsgSendStretFunctionDecl();
2809 if (!MsgSendSuperStretFunctionDecl)
2810 SynthMsgSendSuperStretFunctionDecl();
2811 if (!MsgSendFpretFunctionDecl)
2812 SynthMsgSendFpretFunctionDecl();
2813 if (!GetClassFunctionDecl)
2814 SynthGetClassFunctionDecl();
2815 if (!GetSuperClassFunctionDecl)
2816 SynthGetSuperClassFunctionDecl();
2817 if (!GetMetaClassFunctionDecl)
2818 SynthGetMetaClassFunctionDecl();
2819
2820 // default to objc_msgSend().
2821 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2822 // May need to use objc_msgSend_stret() as well.
2823 FunctionDecl *MsgSendStretFlavor = 0;
2824 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2825 QualType resultType = mDecl->getResultType();
2826 if (resultType->isRecordType())
2827 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2828 else if (resultType->isRealFloatingType())
2829 MsgSendFlavor = MsgSendFpretFunctionDecl;
2830 }
2831
2832 // Synthesize a call to objc_msgSend().
2833 SmallVector<Expr*, 8> MsgExprs;
2834 switch (Exp->getReceiverKind()) {
2835 case ObjCMessageExpr::SuperClass: {
2836 MsgSendFlavor = MsgSendSuperFunctionDecl;
2837 if (MsgSendStretFlavor)
2838 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2839 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2840
2841 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2842
2843 SmallVector<Expr*, 4> InitExprs;
2844
2845 // set the receiver to self, the first argument to all methods.
2846 InitExprs.push_back(
2847 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2848 CK_BitCast,
2849 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002850 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002851 Context->getObjCIdType(),
2852 VK_RValue,
2853 SourceLocation()))
2854 ); // set the 'receiver'.
2855
2856 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2857 SmallVector<Expr*, 8> ClsExprs;
2858 QualType argType = Context->getPointerType(Context->CharTy);
2859 ClsExprs.push_back(StringLiteral::Create(*Context,
2860 ClassDecl->getIdentifier()->getName(),
2861 StringLiteral::Ascii, false,
2862 argType, SourceLocation()));
2863 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2864 &ClsExprs[0],
2865 ClsExprs.size(),
2866 StartLoc,
2867 EndLoc);
2868 // (Class)objc_getClass("CurrentClass")
2869 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2870 Context->getObjCClassType(),
2871 CK_BitCast, Cls);
2872 ClsExprs.clear();
2873 ClsExprs.push_back(ArgExpr);
2874 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2875 &ClsExprs[0], ClsExprs.size(),
2876 StartLoc, EndLoc);
2877
2878 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2879 // To turn off a warning, type-cast to 'id'
2880 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2881 NoTypeInfoCStyleCastExpr(Context,
2882 Context->getObjCIdType(),
2883 CK_BitCast, Cls));
2884 // struct objc_super
2885 QualType superType = getSuperStructType();
2886 Expr *SuperRep;
2887
2888 if (LangOpts.MicrosoftExt) {
2889 SynthSuperContructorFunctionDecl();
2890 // Simulate a contructor call...
2891 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002892 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002893 SourceLocation());
2894 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2895 InitExprs.size(),
2896 superType, VK_LValue,
2897 SourceLocation());
2898 // The code for super is a little tricky to prevent collision with
2899 // the structure definition in the header. The rewriter has it's own
2900 // internal definition (__rw_objc_super) that is uses. This is why
2901 // we need the cast below. For example:
2902 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2903 //
2904 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2905 Context->getPointerType(SuperRep->getType()),
2906 VK_RValue, OK_Ordinary,
2907 SourceLocation());
2908 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2909 Context->getPointerType(superType),
2910 CK_BitCast, SuperRep);
2911 } else {
2912 // (struct objc_super) { <exprs from above> }
2913 InitListExpr *ILE =
2914 new (Context) InitListExpr(*Context, SourceLocation(),
2915 &InitExprs[0], InitExprs.size(),
2916 SourceLocation());
2917 TypeSourceInfo *superTInfo
2918 = Context->getTrivialTypeSourceInfo(superType);
2919 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2920 superType, VK_LValue,
2921 ILE, false);
2922 // struct objc_super *
2923 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2924 Context->getPointerType(SuperRep->getType()),
2925 VK_RValue, OK_Ordinary,
2926 SourceLocation());
2927 }
2928 MsgExprs.push_back(SuperRep);
2929 break;
2930 }
2931
2932 case ObjCMessageExpr::Class: {
2933 SmallVector<Expr*, 8> ClsExprs;
2934 QualType argType = Context->getPointerType(Context->CharTy);
2935 ObjCInterfaceDecl *Class
2936 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2937 IdentifierInfo *clsName = Class->getIdentifier();
2938 ClsExprs.push_back(StringLiteral::Create(*Context,
2939 clsName->getName(),
2940 StringLiteral::Ascii, false,
2941 argType, SourceLocation()));
2942 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2943 &ClsExprs[0],
2944 ClsExprs.size(),
2945 StartLoc, EndLoc);
2946 MsgExprs.push_back(Cls);
2947 break;
2948 }
2949
2950 case ObjCMessageExpr::SuperInstance:{
2951 MsgSendFlavor = MsgSendSuperFunctionDecl;
2952 if (MsgSendStretFlavor)
2953 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2954 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2955 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2956 SmallVector<Expr*, 4> InitExprs;
2957
2958 InitExprs.push_back(
2959 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2960 CK_BitCast,
2961 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002962 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002963 Context->getObjCIdType(),
2964 VK_RValue, SourceLocation()))
2965 ); // set the 'receiver'.
2966
2967 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2968 SmallVector<Expr*, 8> ClsExprs;
2969 QualType argType = Context->getPointerType(Context->CharTy);
2970 ClsExprs.push_back(StringLiteral::Create(*Context,
2971 ClassDecl->getIdentifier()->getName(),
2972 StringLiteral::Ascii, false, argType,
2973 SourceLocation()));
2974 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2975 &ClsExprs[0],
2976 ClsExprs.size(),
2977 StartLoc, EndLoc);
2978 // (Class)objc_getClass("CurrentClass")
2979 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2980 Context->getObjCClassType(),
2981 CK_BitCast, Cls);
2982 ClsExprs.clear();
2983 ClsExprs.push_back(ArgExpr);
2984 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2985 &ClsExprs[0], ClsExprs.size(),
2986 StartLoc, EndLoc);
2987
2988 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2989 // To turn off a warning, type-cast to 'id'
2990 InitExprs.push_back(
2991 // set 'super class', using class_getSuperclass().
2992 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2993 CK_BitCast, Cls));
2994 // struct objc_super
2995 QualType superType = getSuperStructType();
2996 Expr *SuperRep;
2997
2998 if (LangOpts.MicrosoftExt) {
2999 SynthSuperContructorFunctionDecl();
3000 // Simulate a contructor call...
3001 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003002 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003003 SourceLocation());
3004 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
3005 InitExprs.size(),
3006 superType, VK_LValue, SourceLocation());
3007 // The code for super is a little tricky to prevent collision with
3008 // the structure definition in the header. The rewriter has it's own
3009 // internal definition (__rw_objc_super) that is uses. This is why
3010 // we need the cast below. For example:
3011 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3012 //
3013 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3014 Context->getPointerType(SuperRep->getType()),
3015 VK_RValue, OK_Ordinary,
3016 SourceLocation());
3017 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3018 Context->getPointerType(superType),
3019 CK_BitCast, SuperRep);
3020 } else {
3021 // (struct objc_super) { <exprs from above> }
3022 InitListExpr *ILE =
3023 new (Context) InitListExpr(*Context, SourceLocation(),
3024 &InitExprs[0], InitExprs.size(),
3025 SourceLocation());
3026 TypeSourceInfo *superTInfo
3027 = Context->getTrivialTypeSourceInfo(superType);
3028 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3029 superType, VK_RValue, ILE,
3030 false);
3031 }
3032 MsgExprs.push_back(SuperRep);
3033 break;
3034 }
3035
3036 case ObjCMessageExpr::Instance: {
3037 // Remove all type-casts because it may contain objc-style types; e.g.
3038 // Foo<Proto> *.
3039 Expr *recExpr = Exp->getInstanceReceiver();
3040 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3041 recExpr = CE->getSubExpr();
3042 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3043 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3044 ? CK_BlockPointerToObjCPointerCast
3045 : CK_CPointerToObjCPointerCast;
3046
3047 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3048 CK, recExpr);
3049 MsgExprs.push_back(recExpr);
3050 break;
3051 }
3052 }
3053
3054 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3055 SmallVector<Expr*, 8> SelExprs;
3056 QualType argType = Context->getPointerType(Context->CharTy);
3057 SelExprs.push_back(StringLiteral::Create(*Context,
3058 Exp->getSelector().getAsString(),
3059 StringLiteral::Ascii, false,
3060 argType, SourceLocation()));
3061 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3062 &SelExprs[0], SelExprs.size(),
3063 StartLoc,
3064 EndLoc);
3065 MsgExprs.push_back(SelExp);
3066
3067 // Now push any user supplied arguments.
3068 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3069 Expr *userExpr = Exp->getArg(i);
3070 // Make all implicit casts explicit...ICE comes in handy:-)
3071 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3072 // Reuse the ICE type, it is exactly what the doctor ordered.
3073 QualType type = ICE->getType();
3074 if (needToScanForQualifiers(type))
3075 type = Context->getObjCIdType();
3076 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3077 (void)convertBlockPointerToFunctionPointer(type);
3078 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3079 CastKind CK;
3080 if (SubExpr->getType()->isIntegralType(*Context) &&
3081 type->isBooleanType()) {
3082 CK = CK_IntegralToBoolean;
3083 } else if (type->isObjCObjectPointerType()) {
3084 if (SubExpr->getType()->isBlockPointerType()) {
3085 CK = CK_BlockPointerToObjCPointerCast;
3086 } else if (SubExpr->getType()->isPointerType()) {
3087 CK = CK_CPointerToObjCPointerCast;
3088 } else {
3089 CK = CK_BitCast;
3090 }
3091 } else {
3092 CK = CK_BitCast;
3093 }
3094
3095 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3096 }
3097 // Make id<P...> cast into an 'id' cast.
3098 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3099 if (CE->getType()->isObjCQualifiedIdType()) {
3100 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3101 userExpr = CE->getSubExpr();
3102 CastKind CK;
3103 if (userExpr->getType()->isIntegralType(*Context)) {
3104 CK = CK_IntegralToPointer;
3105 } else if (userExpr->getType()->isBlockPointerType()) {
3106 CK = CK_BlockPointerToObjCPointerCast;
3107 } else if (userExpr->getType()->isPointerType()) {
3108 CK = CK_CPointerToObjCPointerCast;
3109 } else {
3110 CK = CK_BitCast;
3111 }
3112 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3113 CK, userExpr);
3114 }
3115 }
3116 MsgExprs.push_back(userExpr);
3117 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3118 // out the argument in the original expression (since we aren't deleting
3119 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3120 //Exp->setArg(i, 0);
3121 }
3122 // Generate the funky cast.
3123 CastExpr *cast;
3124 SmallVector<QualType, 8> ArgTypes;
3125 QualType returnType;
3126
3127 // Push 'id' and 'SEL', the 2 implicit arguments.
3128 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3129 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3130 else
3131 ArgTypes.push_back(Context->getObjCIdType());
3132 ArgTypes.push_back(Context->getObjCSelType());
3133 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3134 // Push any user argument types.
3135 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3136 E = OMD->param_end(); PI != E; ++PI) {
3137 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3138 ? Context->getObjCIdType()
3139 : (*PI)->getType();
3140 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3141 (void)convertBlockPointerToFunctionPointer(t);
3142 ArgTypes.push_back(t);
3143 }
3144 returnType = Exp->getType();
3145 convertToUnqualifiedObjCType(returnType);
3146 (void)convertBlockPointerToFunctionPointer(returnType);
3147 } else {
3148 returnType = Context->getObjCIdType();
3149 }
3150 // Get the type, we will need to reference it in a couple spots.
3151 QualType msgSendType = MsgSendFlavor->getType();
3152
3153 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003154 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003155 VK_LValue, SourceLocation());
3156
3157 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3158 // If we don't do this cast, we get the following bizarre warning/note:
3159 // xx.m:13: warning: function called through a non-compatible type
3160 // xx.m:13: note: if this code is reached, the program will abort
3161 cast = NoTypeInfoCStyleCastExpr(Context,
3162 Context->getPointerType(Context->VoidTy),
3163 CK_BitCast, DRE);
3164
3165 // Now do the "normal" pointer to function cast.
3166 QualType castType =
3167 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3168 // If we don't have a method decl, force a variadic cast.
3169 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3170 castType = Context->getPointerType(castType);
3171 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3172 cast);
3173
3174 // Don't forget the parens to enforce the proper binding.
3175 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3176
3177 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3178 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3179 MsgExprs.size(),
3180 FT->getResultType(), VK_RValue,
3181 EndLoc);
3182 Stmt *ReplacingStmt = CE;
3183 if (MsgSendStretFlavor) {
3184 // We have the method which returns a struct/union. Must also generate
3185 // call to objc_msgSend_stret and hang both varieties on a conditional
3186 // expression which dictate which one to envoke depending on size of
3187 // method's return type.
3188
3189 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003190 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3191 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003192 VK_LValue, SourceLocation());
3193 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3194 cast = NoTypeInfoCStyleCastExpr(Context,
3195 Context->getPointerType(Context->VoidTy),
3196 CK_BitCast, STDRE);
3197 // Now do the "normal" pointer to function cast.
3198 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3199 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3200 castType = Context->getPointerType(castType);
3201 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3202 cast);
3203
3204 // Don't forget the parens to enforce the proper binding.
3205 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3206
3207 FT = msgSendType->getAs<FunctionType>();
3208 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3209 MsgExprs.size(),
3210 FT->getResultType(), VK_RValue,
3211 SourceLocation());
3212
3213 // Build sizeof(returnType)
3214 UnaryExprOrTypeTraitExpr *sizeofExpr =
3215 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3216 Context->getTrivialTypeSourceInfo(returnType),
3217 Context->getSizeType(), SourceLocation(),
3218 SourceLocation());
3219 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3220 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3221 // For X86 it is more complicated and some kind of target specific routine
3222 // is needed to decide what to do.
3223 unsigned IntSize =
3224 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3225 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3226 llvm::APInt(IntSize, 8),
3227 Context->IntTy,
3228 SourceLocation());
3229 BinaryOperator *lessThanExpr =
3230 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3231 VK_RValue, OK_Ordinary, SourceLocation());
3232 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3233 ConditionalOperator *CondExpr =
3234 new (Context) ConditionalOperator(lessThanExpr,
3235 SourceLocation(), CE,
3236 SourceLocation(), STCE,
3237 returnType, VK_RValue, OK_Ordinary);
3238 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3239 CondExpr);
3240 }
3241 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3242 return ReplacingStmt;
3243}
3244
3245Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3246 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3247 Exp->getLocEnd());
3248
3249 // Now do the actual rewrite.
3250 ReplaceStmt(Exp, ReplacingStmt);
3251
3252 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3253 return ReplacingStmt;
3254}
3255
3256// typedef struct objc_object Protocol;
3257QualType RewriteModernObjC::getProtocolType() {
3258 if (!ProtocolTypeDecl) {
3259 TypeSourceInfo *TInfo
3260 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3261 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3262 SourceLocation(), SourceLocation(),
3263 &Context->Idents.get("Protocol"),
3264 TInfo);
3265 }
3266 return Context->getTypeDeclType(ProtocolTypeDecl);
3267}
3268
3269/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3270/// a synthesized/forward data reference (to the protocol's metadata).
3271/// The forward references (and metadata) are generated in
3272/// RewriteModernObjC::HandleTranslationUnit().
3273Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003274 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3275 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003276 IdentifierInfo *ID = &Context->Idents.get(Name);
3277 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3278 SourceLocation(), ID, getProtocolType(), 0,
3279 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003280 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3281 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003282 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3283 Context->getPointerType(DRE->getType()),
3284 VK_RValue, OK_Ordinary, SourceLocation());
3285 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3286 CK_BitCast,
3287 DerefExpr);
3288 ReplaceStmt(Exp, castExpr);
3289 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3290 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3291 return castExpr;
3292
3293}
3294
3295bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3296 const char *endBuf) {
3297 while (startBuf < endBuf) {
3298 if (*startBuf == '#') {
3299 // Skip whitespace.
3300 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3301 ;
3302 if (!strncmp(startBuf, "if", strlen("if")) ||
3303 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3304 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3305 !strncmp(startBuf, "define", strlen("define")) ||
3306 !strncmp(startBuf, "undef", strlen("undef")) ||
3307 !strncmp(startBuf, "else", strlen("else")) ||
3308 !strncmp(startBuf, "elif", strlen("elif")) ||
3309 !strncmp(startBuf, "endif", strlen("endif")) ||
3310 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3311 !strncmp(startBuf, "include", strlen("include")) ||
3312 !strncmp(startBuf, "import", strlen("import")) ||
3313 !strncmp(startBuf, "include_next", strlen("include_next")))
3314 return true;
3315 }
3316 startBuf++;
3317 }
3318 return false;
3319}
3320
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003321/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003322/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003323bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3324 std::string &Result) {
3325 if (Type->isArrayType()) {
3326 QualType ElemTy = Context->getBaseElementType(Type);
3327 return RewriteObjCFieldDeclType(ElemTy, Result);
3328 }
3329 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003330 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3331 if (RD->isCompleteDefinition()) {
3332 if (RD->isStruct())
3333 Result += "\n\tstruct ";
3334 else if (RD->isUnion())
3335 Result += "\n\tunion ";
3336 else
3337 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003338
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003339 Result += RD->getName();
3340 if (TagsDefinedInIvarDecls.count(RD)) {
3341 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003342 Result += " ";
3343 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003344 }
3345 TagsDefinedInIvarDecls.insert(RD);
3346 Result += " {\n";
3347 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003348 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003349 FieldDecl *FD = *i;
3350 RewriteObjCFieldDecl(FD, Result);
3351 }
3352 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003353 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003354 }
3355 }
3356 else if (Type->isEnumeralType()) {
3357 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3358 if (ED->isCompleteDefinition()) {
3359 Result += "\n\tenum ";
3360 Result += ED->getName();
3361 if (TagsDefinedInIvarDecls.count(ED)) {
3362 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003363 Result += " ";
3364 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003365 }
3366 TagsDefinedInIvarDecls.insert(ED);
3367
3368 Result += " {\n";
3369 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3370 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3371 Result += "\t"; Result += EC->getName(); Result += " = ";
3372 llvm::APSInt Val = EC->getInitVal();
3373 Result += Val.toString(10);
3374 Result += ",\n";
3375 }
3376 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003377 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003378 }
3379 }
3380
3381 Result += "\t";
3382 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003383 return false;
3384}
3385
3386
3387/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3388/// It handles elaborated types, as well as enum types in the process.
3389void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3390 std::string &Result) {
3391 QualType Type = fieldDecl->getType();
3392 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003393
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003394 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3395 if (!EleboratedType)
3396 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003397 Result += Name;
3398 if (fieldDecl->isBitField()) {
3399 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3400 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003401 else if (EleboratedType && Type->isArrayType()) {
3402 CanQualType CType = Context->getCanonicalType(Type);
3403 while (isa<ArrayType>(CType)) {
3404 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3405 Result += "[";
3406 llvm::APInt Dim = CAT->getSize();
3407 Result += utostr(Dim.getZExtValue());
3408 Result += "]";
3409 }
3410 CType = CType->getAs<ArrayType>()->getElementType();
3411 }
3412 }
3413
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003414 Result += ";\n";
3415}
3416
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003417/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3418/// an objective-c class with ivars.
3419void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3420 std::string &Result) {
3421 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3422 assert(CDecl->getName() != "" &&
3423 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003424 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003425 SmallVector<ObjCIvarDecl *, 8> IVars;
3426 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003427 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003428 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003429
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003430 SourceLocation LocStart = CDecl->getLocStart();
3431 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003432
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003433 const char *startBuf = SM->getCharacterData(LocStart);
3434 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003435
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003436 // If no ivars and no root or if its root, directly or indirectly,
3437 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003438 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003439 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3440 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3441 ReplaceText(LocStart, endBuf-startBuf, Result);
3442 return;
3443 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003444
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003445 Result += "\nstruct ";
3446 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003447 Result += "_IMPL {\n";
3448
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003449 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003450 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3451 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3452 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003453 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003454 TagsDefinedInIvarDecls.clear();
3455 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3456 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003457
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003458 Result += "};\n";
3459 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3460 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003461 // Mark this struct as having been generated.
3462 if (!ObjCSynthesizedStructs.insert(CDecl))
3463 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003464}
3465
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003466static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3467 ObjCIvarDecl *IvarDecl, std::string &Result) {
3468 Result += "OBJC_IVAR_$_";
3469 Result += IDecl->getName();
3470 Result += "$";
3471 Result += IvarDecl->getName();
3472}
3473
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003474/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3475/// have been referenced in an ivar access expression.
3476void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3477 std::string &Result) {
3478 // write out ivar offset symbols which have been referenced in an ivar
3479 // access expression.
3480 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3481 if (Ivars.empty())
3482 return;
3483 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3484 e = Ivars.end(); i != e; i++) {
3485 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003486 Result += "\n";
3487 if (LangOpts.MicrosoftExt)
3488 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003489 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003490 if (LangOpts.MicrosoftExt &&
3491 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003492 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3493 Result += "__declspec(dllimport) ";
3494
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003495 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003496 WriteInternalIvarName(CDecl, IvarDecl, Result);
3497 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003498 }
3499}
3500
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003501//===----------------------------------------------------------------------===//
3502// Meta Data Emission
3503//===----------------------------------------------------------------------===//
3504
3505
3506/// RewriteImplementations - This routine rewrites all method implementations
3507/// and emits meta-data.
3508
3509void RewriteModernObjC::RewriteImplementations() {
3510 int ClsDefCount = ClassImplementation.size();
3511 int CatDefCount = CategoryImplementation.size();
3512
3513 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003514 for (int i = 0; i < ClsDefCount; i++) {
3515 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3516 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3517 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003518 assert(false &&
3519 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003520 RewriteImplementationDecl(OIMP);
3521 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003522
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003523 for (int i = 0; i < CatDefCount; i++) {
3524 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3525 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3526 if (CDecl->isImplicitInterfaceDecl())
3527 assert(false &&
3528 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003529 RewriteImplementationDecl(CIMP);
3530 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003531}
3532
3533void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3534 const std::string &Name,
3535 ValueDecl *VD, bool def) {
3536 assert(BlockByRefDeclNo.count(VD) &&
3537 "RewriteByRefString: ByRef decl missing");
3538 if (def)
3539 ResultStr += "struct ";
3540 ResultStr += "__Block_byref_" + Name +
3541 "_" + utostr(BlockByRefDeclNo[VD]) ;
3542}
3543
3544static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3545 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3546 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3547 return false;
3548}
3549
3550std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3551 StringRef funcName,
3552 std::string Tag) {
3553 const FunctionType *AFT = CE->getFunctionType();
3554 QualType RT = AFT->getResultType();
3555 std::string StructRef = "struct " + Tag;
3556 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003557 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003558
3559 BlockDecl *BD = CE->getBlockDecl();
3560
3561 if (isa<FunctionNoProtoType>(AFT)) {
3562 // No user-supplied arguments. Still need to pass in a pointer to the
3563 // block (to reference imported block decl refs).
3564 S += "(" + StructRef + " *__cself)";
3565 } else if (BD->param_empty()) {
3566 S += "(" + StructRef + " *__cself)";
3567 } else {
3568 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3569 assert(FT && "SynthesizeBlockFunc: No function proto");
3570 S += '(';
3571 // first add the implicit argument.
3572 S += StructRef + " *__cself, ";
3573 std::string ParamStr;
3574 for (BlockDecl::param_iterator AI = BD->param_begin(),
3575 E = BD->param_end(); AI != E; ++AI) {
3576 if (AI != BD->param_begin()) S += ", ";
3577 ParamStr = (*AI)->getNameAsString();
3578 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003579 (void)convertBlockPointerToFunctionPointer(QT);
3580 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003581 S += ParamStr;
3582 }
3583 if (FT->isVariadic()) {
3584 if (!BD->param_empty()) S += ", ";
3585 S += "...";
3586 }
3587 S += ')';
3588 }
3589 S += " {\n";
3590
3591 // Create local declarations to avoid rewriting all closure decl ref exprs.
3592 // First, emit a declaration for all "by ref" decls.
3593 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3594 E = BlockByRefDecls.end(); I != E; ++I) {
3595 S += " ";
3596 std::string Name = (*I)->getNameAsString();
3597 std::string TypeString;
3598 RewriteByRefString(TypeString, Name, (*I));
3599 TypeString += " *";
3600 Name = TypeString + Name;
3601 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3602 }
3603 // Next, emit a declaration for all "by copy" declarations.
3604 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3605 E = BlockByCopyDecls.end(); I != E; ++I) {
3606 S += " ";
3607 // Handle nested closure invocation. For example:
3608 //
3609 // void (^myImportedClosure)(void);
3610 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3611 //
3612 // void (^anotherClosure)(void);
3613 // anotherClosure = ^(void) {
3614 // myImportedClosure(); // import and invoke the closure
3615 // };
3616 //
3617 if (isTopLevelBlockPointerType((*I)->getType())) {
3618 RewriteBlockPointerTypeVariable(S, (*I));
3619 S += " = (";
3620 RewriteBlockPointerType(S, (*I)->getType());
3621 S += ")";
3622 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3623 }
3624 else {
3625 std::string Name = (*I)->getNameAsString();
3626 QualType QT = (*I)->getType();
3627 if (HasLocalVariableExternalStorage(*I))
3628 QT = Context->getPointerType(QT);
3629 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3630 S += Name + " = __cself->" +
3631 (*I)->getNameAsString() + "; // bound by copy\n";
3632 }
3633 }
3634 std::string RewrittenStr = RewrittenBlockExprs[CE];
3635 const char *cstr = RewrittenStr.c_str();
3636 while (*cstr++ != '{') ;
3637 S += cstr;
3638 S += "\n";
3639 return S;
3640}
3641
3642std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3643 StringRef funcName,
3644 std::string Tag) {
3645 std::string StructRef = "struct " + Tag;
3646 std::string S = "static void __";
3647
3648 S += funcName;
3649 S += "_block_copy_" + utostr(i);
3650 S += "(" + StructRef;
3651 S += "*dst, " + StructRef;
3652 S += "*src) {";
3653 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3654 E = ImportedBlockDecls.end(); I != E; ++I) {
3655 ValueDecl *VD = (*I);
3656 S += "_Block_object_assign((void*)&dst->";
3657 S += (*I)->getNameAsString();
3658 S += ", (void*)src->";
3659 S += (*I)->getNameAsString();
3660 if (BlockByRefDeclsPtrSet.count((*I)))
3661 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3662 else if (VD->getType()->isBlockPointerType())
3663 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3664 else
3665 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3666 }
3667 S += "}\n";
3668
3669 S += "\nstatic void __";
3670 S += funcName;
3671 S += "_block_dispose_" + utostr(i);
3672 S += "(" + StructRef;
3673 S += "*src) {";
3674 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3675 E = ImportedBlockDecls.end(); I != E; ++I) {
3676 ValueDecl *VD = (*I);
3677 S += "_Block_object_dispose((void*)src->";
3678 S += (*I)->getNameAsString();
3679 if (BlockByRefDeclsPtrSet.count((*I)))
3680 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3681 else if (VD->getType()->isBlockPointerType())
3682 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3683 else
3684 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3685 }
3686 S += "}\n";
3687 return S;
3688}
3689
3690std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3691 std::string Desc) {
3692 std::string S = "\nstruct " + Tag;
3693 std::string Constructor = " " + Tag;
3694
3695 S += " {\n struct __block_impl impl;\n";
3696 S += " struct " + Desc;
3697 S += "* Desc;\n";
3698
3699 Constructor += "(void *fp, "; // Invoke function pointer.
3700 Constructor += "struct " + Desc; // Descriptor pointer.
3701 Constructor += " *desc";
3702
3703 if (BlockDeclRefs.size()) {
3704 // Output all "by copy" declarations.
3705 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3706 E = BlockByCopyDecls.end(); I != E; ++I) {
3707 S += " ";
3708 std::string FieldName = (*I)->getNameAsString();
3709 std::string ArgName = "_" + FieldName;
3710 // Handle nested closure invocation. For example:
3711 //
3712 // void (^myImportedBlock)(void);
3713 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3714 //
3715 // void (^anotherBlock)(void);
3716 // anotherBlock = ^(void) {
3717 // myImportedBlock(); // import and invoke the closure
3718 // };
3719 //
3720 if (isTopLevelBlockPointerType((*I)->getType())) {
3721 S += "struct __block_impl *";
3722 Constructor += ", void *" + ArgName;
3723 } else {
3724 QualType QT = (*I)->getType();
3725 if (HasLocalVariableExternalStorage(*I))
3726 QT = Context->getPointerType(QT);
3727 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3728 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3729 Constructor += ", " + ArgName;
3730 }
3731 S += FieldName + ";\n";
3732 }
3733 // Output all "by ref" declarations.
3734 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3735 E = BlockByRefDecls.end(); I != E; ++I) {
3736 S += " ";
3737 std::string FieldName = (*I)->getNameAsString();
3738 std::string ArgName = "_" + FieldName;
3739 {
3740 std::string TypeString;
3741 RewriteByRefString(TypeString, FieldName, (*I));
3742 TypeString += " *";
3743 FieldName = TypeString + FieldName;
3744 ArgName = TypeString + ArgName;
3745 Constructor += ", " + ArgName;
3746 }
3747 S += FieldName + "; // by ref\n";
3748 }
3749 // Finish writing the constructor.
3750 Constructor += ", int flags=0)";
3751 // Initialize all "by copy" arguments.
3752 bool firsTime = true;
3753 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3754 E = BlockByCopyDecls.end(); I != E; ++I) {
3755 std::string Name = (*I)->getNameAsString();
3756 if (firsTime) {
3757 Constructor += " : ";
3758 firsTime = false;
3759 }
3760 else
3761 Constructor += ", ";
3762 if (isTopLevelBlockPointerType((*I)->getType()))
3763 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3764 else
3765 Constructor += Name + "(_" + Name + ")";
3766 }
3767 // Initialize all "by ref" arguments.
3768 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3769 E = BlockByRefDecls.end(); I != E; ++I) {
3770 std::string Name = (*I)->getNameAsString();
3771 if (firsTime) {
3772 Constructor += " : ";
3773 firsTime = false;
3774 }
3775 else
3776 Constructor += ", ";
3777 Constructor += Name + "(_" + Name + "->__forwarding)";
3778 }
3779
3780 Constructor += " {\n";
3781 if (GlobalVarDecl)
3782 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3783 else
3784 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3785 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3786
3787 Constructor += " Desc = desc;\n";
3788 } else {
3789 // Finish writing the constructor.
3790 Constructor += ", int flags=0) {\n";
3791 if (GlobalVarDecl)
3792 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3793 else
3794 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3795 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3796 Constructor += " Desc = desc;\n";
3797 }
3798 Constructor += " ";
3799 Constructor += "}\n";
3800 S += Constructor;
3801 S += "};\n";
3802 return S;
3803}
3804
3805std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3806 std::string ImplTag, int i,
3807 StringRef FunName,
3808 unsigned hasCopy) {
3809 std::string S = "\nstatic struct " + DescTag;
3810
3811 S += " {\n unsigned long reserved;\n";
3812 S += " unsigned long Block_size;\n";
3813 if (hasCopy) {
3814 S += " void (*copy)(struct ";
3815 S += ImplTag; S += "*, struct ";
3816 S += ImplTag; S += "*);\n";
3817
3818 S += " void (*dispose)(struct ";
3819 S += ImplTag; S += "*);\n";
3820 }
3821 S += "} ";
3822
3823 S += DescTag + "_DATA = { 0, sizeof(struct ";
3824 S += ImplTag + ")";
3825 if (hasCopy) {
3826 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3827 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3828 }
3829 S += "};\n";
3830 return S;
3831}
3832
3833void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3834 StringRef FunName) {
3835 // Insert declaration for the function in which block literal is used.
3836 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3837 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3838 bool RewriteSC = (GlobalVarDecl &&
3839 !Blocks.empty() &&
3840 GlobalVarDecl->getStorageClass() == SC_Static &&
3841 GlobalVarDecl->getType().getCVRQualifiers());
3842 if (RewriteSC) {
3843 std::string SC(" void __");
3844 SC += GlobalVarDecl->getNameAsString();
3845 SC += "() {}";
3846 InsertText(FunLocStart, SC);
3847 }
3848
3849 // Insert closures that were part of the function.
3850 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3851 CollectBlockDeclRefInfo(Blocks[i]);
3852 // Need to copy-in the inner copied-in variables not actually used in this
3853 // block.
3854 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003855 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003856 ValueDecl *VD = Exp->getDecl();
3857 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003858 if (!VD->hasAttr<BlocksAttr>()) {
3859 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3860 BlockByCopyDeclsPtrSet.insert(VD);
3861 BlockByCopyDecls.push_back(VD);
3862 }
3863 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003864 }
John McCallf4b88a42012-03-10 09:33:50 +00003865
3866 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003867 BlockByRefDeclsPtrSet.insert(VD);
3868 BlockByRefDecls.push_back(VD);
3869 }
John McCallf4b88a42012-03-10 09:33:50 +00003870
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003871 // imported objects in the inner blocks not used in the outer
3872 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003873 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003874 VD->getType()->isBlockPointerType())
3875 ImportedBlockDecls.insert(VD);
3876 }
3877
3878 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3879 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3880
3881 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3882
3883 InsertText(FunLocStart, CI);
3884
3885 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3886
3887 InsertText(FunLocStart, CF);
3888
3889 if (ImportedBlockDecls.size()) {
3890 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3891 InsertText(FunLocStart, HF);
3892 }
3893 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3894 ImportedBlockDecls.size() > 0);
3895 InsertText(FunLocStart, BD);
3896
3897 BlockDeclRefs.clear();
3898 BlockByRefDecls.clear();
3899 BlockByRefDeclsPtrSet.clear();
3900 BlockByCopyDecls.clear();
3901 BlockByCopyDeclsPtrSet.clear();
3902 ImportedBlockDecls.clear();
3903 }
3904 if (RewriteSC) {
3905 // Must insert any 'const/volatile/static here. Since it has been
3906 // removed as result of rewriting of block literals.
3907 std::string SC;
3908 if (GlobalVarDecl->getStorageClass() == SC_Static)
3909 SC = "static ";
3910 if (GlobalVarDecl->getType().isConstQualified())
3911 SC += "const ";
3912 if (GlobalVarDecl->getType().isVolatileQualified())
3913 SC += "volatile ";
3914 if (GlobalVarDecl->getType().isRestrictQualified())
3915 SC += "restrict ";
3916 InsertText(FunLocStart, SC);
3917 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003918 if (GlobalConstructionExp) {
3919 // extra fancy dance for global literal expression.
3920
3921 // Always the latest block expression on the block stack.
3922 std::string Tag = "__";
3923 Tag += FunName;
3924 Tag += "_block_impl_";
3925 Tag += utostr(Blocks.size()-1);
3926 std::string globalBuf = "static ";
3927 globalBuf += Tag; globalBuf += " ";
3928 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003929
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003930 llvm::raw_string_ostream constructorExprBuf(SStr);
3931 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3932 PrintingPolicy(LangOpts));
3933 globalBuf += constructorExprBuf.str();
3934 globalBuf += ";\n";
3935 InsertText(FunLocStart, globalBuf);
3936 GlobalConstructionExp = 0;
3937 }
3938
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003939 Blocks.clear();
3940 InnerDeclRefsCount.clear();
3941 InnerDeclRefs.clear();
3942 RewrittenBlockExprs.clear();
3943}
3944
3945void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3946 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3947 StringRef FuncName = FD->getName();
3948
3949 SynthesizeBlockLiterals(FunLocStart, FuncName);
3950}
3951
3952static void BuildUniqueMethodName(std::string &Name,
3953 ObjCMethodDecl *MD) {
3954 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3955 Name = IFace->getName();
3956 Name += "__" + MD->getSelector().getAsString();
3957 // Convert colons to underscores.
3958 std::string::size_type loc = 0;
3959 while ((loc = Name.find(":", loc)) != std::string::npos)
3960 Name.replace(loc, 1, "_");
3961}
3962
3963void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3964 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3965 //SourceLocation FunLocStart = MD->getLocStart();
3966 SourceLocation FunLocStart = MD->getLocStart();
3967 std::string FuncName;
3968 BuildUniqueMethodName(FuncName, MD);
3969 SynthesizeBlockLiterals(FunLocStart, FuncName);
3970}
3971
3972void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3973 for (Stmt::child_range CI = S->children(); CI; ++CI)
3974 if (*CI) {
3975 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3976 GetBlockDeclRefExprs(CBE->getBody());
3977 else
3978 GetBlockDeclRefExprs(*CI);
3979 }
3980 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003981 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3982 if (DRE->refersToEnclosingLocal() &&
3983 HasLocalVariableExternalStorage(DRE->getDecl())) {
3984 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003985 }
3986
3987 return;
3988}
3989
3990void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003991 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003992 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3993 for (Stmt::child_range CI = S->children(); CI; ++CI)
3994 if (*CI) {
3995 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3996 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3997 GetInnerBlockDeclRefExprs(CBE->getBody(),
3998 InnerBlockDeclRefs,
3999 InnerContexts);
4000 }
4001 else
4002 GetInnerBlockDeclRefExprs(*CI,
4003 InnerBlockDeclRefs,
4004 InnerContexts);
4005
4006 }
4007 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004008 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4009 if (DRE->refersToEnclosingLocal()) {
4010 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4011 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4012 InnerBlockDeclRefs.push_back(DRE);
4013 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4014 if (Var->isFunctionOrMethodVarDecl())
4015 ImportedLocalExternalDecls.insert(Var);
4016 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004017 }
4018
4019 return;
4020}
4021
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004022/// convertObjCTypeToCStyleType - This routine converts such objc types
4023/// as qualified objects, and blocks to their closest c/c++ types that
4024/// it can. It returns true if input type was modified.
4025bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4026 QualType oldT = T;
4027 convertBlockPointerToFunctionPointer(T);
4028 if (T->isFunctionPointerType()) {
4029 QualType PointeeTy;
4030 if (const PointerType* PT = T->getAs<PointerType>()) {
4031 PointeeTy = PT->getPointeeType();
4032 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4033 T = convertFunctionTypeOfBlocks(FT);
4034 T = Context->getPointerType(T);
4035 }
4036 }
4037 }
4038
4039 convertToUnqualifiedObjCType(T);
4040 return T != oldT;
4041}
4042
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004043/// convertFunctionTypeOfBlocks - This routine converts a function type
4044/// whose result type may be a block pointer or whose argument type(s)
4045/// might be block pointers to an equivalent function type replacing
4046/// all block pointers to function pointers.
4047QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4048 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4049 // FTP will be null for closures that don't take arguments.
4050 // Generate a funky cast.
4051 SmallVector<QualType, 8> ArgTypes;
4052 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004053 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004054
4055 if (FTP) {
4056 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4057 E = FTP->arg_type_end(); I && (I != E); ++I) {
4058 QualType t = *I;
4059 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004060 if (convertObjCTypeToCStyleType(t))
4061 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004062 ArgTypes.push_back(t);
4063 }
4064 }
4065 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004066 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004067 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4068 else FuncType = QualType(FT, 0);
4069 return FuncType;
4070}
4071
4072Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4073 // Navigate to relevant type information.
4074 const BlockPointerType *CPT = 0;
4075
4076 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4077 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004078 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4079 CPT = MExpr->getType()->getAs<BlockPointerType>();
4080 }
4081 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4082 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4083 }
4084 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4085 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4086 else if (const ConditionalOperator *CEXPR =
4087 dyn_cast<ConditionalOperator>(BlockExp)) {
4088 Expr *LHSExp = CEXPR->getLHS();
4089 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4090 Expr *RHSExp = CEXPR->getRHS();
4091 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4092 Expr *CONDExp = CEXPR->getCond();
4093 ConditionalOperator *CondExpr =
4094 new (Context) ConditionalOperator(CONDExp,
4095 SourceLocation(), cast<Expr>(LHSStmt),
4096 SourceLocation(), cast<Expr>(RHSStmt),
4097 Exp->getType(), VK_RValue, OK_Ordinary);
4098 return CondExpr;
4099 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4100 CPT = IRE->getType()->getAs<BlockPointerType>();
4101 } else if (const PseudoObjectExpr *POE
4102 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4103 CPT = POE->getType()->castAs<BlockPointerType>();
4104 } else {
4105 assert(1 && "RewriteBlockClass: Bad type");
4106 }
4107 assert(CPT && "RewriteBlockClass: Bad type");
4108 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4109 assert(FT && "RewriteBlockClass: Bad type");
4110 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4111 // FTP will be null for closures that don't take arguments.
4112
4113 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4114 SourceLocation(), SourceLocation(),
4115 &Context->Idents.get("__block_impl"));
4116 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4117
4118 // Generate a funky cast.
4119 SmallVector<QualType, 8> ArgTypes;
4120
4121 // Push the block argument type.
4122 ArgTypes.push_back(PtrBlock);
4123 if (FTP) {
4124 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4125 E = FTP->arg_type_end(); I && (I != E); ++I) {
4126 QualType t = *I;
4127 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4128 if (!convertBlockPointerToFunctionPointer(t))
4129 convertToUnqualifiedObjCType(t);
4130 ArgTypes.push_back(t);
4131 }
4132 }
4133 // Now do the pointer to function cast.
4134 QualType PtrToFuncCastType
4135 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4136
4137 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4138
4139 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4140 CK_BitCast,
4141 const_cast<Expr*>(BlockExp));
4142 // Don't forget the parens to enforce the proper binding.
4143 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4144 BlkCast);
4145 //PE->dump();
4146
4147 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4148 SourceLocation(),
4149 &Context->Idents.get("FuncPtr"),
4150 Context->VoidPtrTy, 0,
4151 /*BitWidth=*/0, /*Mutable=*/true,
4152 /*HasInit=*/false);
4153 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4154 FD->getType(), VK_LValue,
4155 OK_Ordinary);
4156
4157
4158 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4159 CK_BitCast, ME);
4160 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4161
4162 SmallVector<Expr*, 8> BlkExprs;
4163 // Add the implicit argument.
4164 BlkExprs.push_back(BlkCast);
4165 // Add the user arguments.
4166 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4167 E = Exp->arg_end(); I != E; ++I) {
4168 BlkExprs.push_back(*I);
4169 }
4170 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4171 BlkExprs.size(),
4172 Exp->getType(), VK_RValue,
4173 SourceLocation());
4174 return CE;
4175}
4176
4177// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004178// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004179// For example:
4180//
4181// int main() {
4182// __block Foo *f;
4183// __block int i;
4184//
4185// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004186// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004187// i = 77;
4188// };
4189//}
John McCallf4b88a42012-03-10 09:33:50 +00004190Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004191 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4192 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004193 ValueDecl *VD = DeclRefExp->getDecl();
4194 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004195
4196 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4197 SourceLocation(),
4198 &Context->Idents.get("__forwarding"),
4199 Context->VoidPtrTy, 0,
4200 /*BitWidth=*/0, /*Mutable=*/true,
4201 /*HasInit=*/false);
4202 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4203 FD, SourceLocation(),
4204 FD->getType(), VK_LValue,
4205 OK_Ordinary);
4206
4207 StringRef Name = VD->getName();
4208 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4209 &Context->Idents.get(Name),
4210 Context->VoidPtrTy, 0,
4211 /*BitWidth=*/0, /*Mutable=*/true,
4212 /*HasInit=*/false);
4213 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4214 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4215
4216
4217
4218 // Need parens to enforce precedence.
4219 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4220 DeclRefExp->getExprLoc(),
4221 ME);
4222 ReplaceStmt(DeclRefExp, PE);
4223 return PE;
4224}
4225
4226// Rewrites the imported local variable V with external storage
4227// (static, extern, etc.) as *V
4228//
4229Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4230 ValueDecl *VD = DRE->getDecl();
4231 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4232 if (!ImportedLocalExternalDecls.count(Var))
4233 return DRE;
4234 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4235 VK_LValue, OK_Ordinary,
4236 DRE->getLocation());
4237 // Need parens to enforce precedence.
4238 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4239 Exp);
4240 ReplaceStmt(DRE, PE);
4241 return PE;
4242}
4243
4244void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4245 SourceLocation LocStart = CE->getLParenLoc();
4246 SourceLocation LocEnd = CE->getRParenLoc();
4247
4248 // Need to avoid trying to rewrite synthesized casts.
4249 if (LocStart.isInvalid())
4250 return;
4251 // Need to avoid trying to rewrite casts contained in macros.
4252 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4253 return;
4254
4255 const char *startBuf = SM->getCharacterData(LocStart);
4256 const char *endBuf = SM->getCharacterData(LocEnd);
4257 QualType QT = CE->getType();
4258 const Type* TypePtr = QT->getAs<Type>();
4259 if (isa<TypeOfExprType>(TypePtr)) {
4260 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4261 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4262 std::string TypeAsString = "(";
4263 RewriteBlockPointerType(TypeAsString, QT);
4264 TypeAsString += ")";
4265 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4266 return;
4267 }
4268 // advance the location to startArgList.
4269 const char *argPtr = startBuf;
4270
4271 while (*argPtr++ && (argPtr < endBuf)) {
4272 switch (*argPtr) {
4273 case '^':
4274 // Replace the '^' with '*'.
4275 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4276 ReplaceText(LocStart, 1, "*");
4277 break;
4278 }
4279 }
4280 return;
4281}
4282
4283void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4284 SourceLocation DeclLoc = FD->getLocation();
4285 unsigned parenCount = 0;
4286
4287 // We have 1 or more arguments that have closure pointers.
4288 const char *startBuf = SM->getCharacterData(DeclLoc);
4289 const char *startArgList = strchr(startBuf, '(');
4290
4291 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4292
4293 parenCount++;
4294 // advance the location to startArgList.
4295 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4296 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4297
4298 const char *argPtr = startArgList;
4299
4300 while (*argPtr++ && parenCount) {
4301 switch (*argPtr) {
4302 case '^':
4303 // Replace the '^' with '*'.
4304 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4305 ReplaceText(DeclLoc, 1, "*");
4306 break;
4307 case '(':
4308 parenCount++;
4309 break;
4310 case ')':
4311 parenCount--;
4312 break;
4313 }
4314 }
4315 return;
4316}
4317
4318bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4319 const FunctionProtoType *FTP;
4320 const PointerType *PT = QT->getAs<PointerType>();
4321 if (PT) {
4322 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4323 } else {
4324 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4325 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4326 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4327 }
4328 if (FTP) {
4329 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4330 E = FTP->arg_type_end(); I != E; ++I)
4331 if (isTopLevelBlockPointerType(*I))
4332 return true;
4333 }
4334 return false;
4335}
4336
4337bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4338 const FunctionProtoType *FTP;
4339 const PointerType *PT = QT->getAs<PointerType>();
4340 if (PT) {
4341 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4342 } else {
4343 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4344 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4345 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4346 }
4347 if (FTP) {
4348 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4349 E = FTP->arg_type_end(); I != E; ++I) {
4350 if ((*I)->isObjCQualifiedIdType())
4351 return true;
4352 if ((*I)->isObjCObjectPointerType() &&
4353 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4354 return true;
4355 }
4356
4357 }
4358 return false;
4359}
4360
4361void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4362 const char *&RParen) {
4363 const char *argPtr = strchr(Name, '(');
4364 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4365
4366 LParen = argPtr; // output the start.
4367 argPtr++; // skip past the left paren.
4368 unsigned parenCount = 1;
4369
4370 while (*argPtr && parenCount) {
4371 switch (*argPtr) {
4372 case '(': parenCount++; break;
4373 case ')': parenCount--; break;
4374 default: break;
4375 }
4376 if (parenCount) argPtr++;
4377 }
4378 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4379 RParen = argPtr; // output the end
4380}
4381
4382void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4383 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4384 RewriteBlockPointerFunctionArgs(FD);
4385 return;
4386 }
4387 // Handle Variables and Typedefs.
4388 SourceLocation DeclLoc = ND->getLocation();
4389 QualType DeclT;
4390 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4391 DeclT = VD->getType();
4392 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4393 DeclT = TDD->getUnderlyingType();
4394 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4395 DeclT = FD->getType();
4396 else
4397 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4398
4399 const char *startBuf = SM->getCharacterData(DeclLoc);
4400 const char *endBuf = startBuf;
4401 // scan backward (from the decl location) for the end of the previous decl.
4402 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4403 startBuf--;
4404 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4405 std::string buf;
4406 unsigned OrigLength=0;
4407 // *startBuf != '^' if we are dealing with a pointer to function that
4408 // may take block argument types (which will be handled below).
4409 if (*startBuf == '^') {
4410 // Replace the '^' with '*', computing a negative offset.
4411 buf = '*';
4412 startBuf++;
4413 OrigLength++;
4414 }
4415 while (*startBuf != ')') {
4416 buf += *startBuf;
4417 startBuf++;
4418 OrigLength++;
4419 }
4420 buf += ')';
4421 OrigLength++;
4422
4423 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4424 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4425 // Replace the '^' with '*' for arguments.
4426 // Replace id<P> with id/*<>*/
4427 DeclLoc = ND->getLocation();
4428 startBuf = SM->getCharacterData(DeclLoc);
4429 const char *argListBegin, *argListEnd;
4430 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4431 while (argListBegin < argListEnd) {
4432 if (*argListBegin == '^')
4433 buf += '*';
4434 else if (*argListBegin == '<') {
4435 buf += "/*";
4436 buf += *argListBegin++;
4437 OrigLength++;;
4438 while (*argListBegin != '>') {
4439 buf += *argListBegin++;
4440 OrigLength++;
4441 }
4442 buf += *argListBegin;
4443 buf += "*/";
4444 }
4445 else
4446 buf += *argListBegin;
4447 argListBegin++;
4448 OrigLength++;
4449 }
4450 buf += ')';
4451 OrigLength++;
4452 }
4453 ReplaceText(Start, OrigLength, buf);
4454
4455 return;
4456}
4457
4458
4459/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4460/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4461/// struct Block_byref_id_object *src) {
4462/// _Block_object_assign (&_dest->object, _src->object,
4463/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4464/// [|BLOCK_FIELD_IS_WEAK]) // object
4465/// _Block_object_assign(&_dest->object, _src->object,
4466/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4467/// [|BLOCK_FIELD_IS_WEAK]) // block
4468/// }
4469/// And:
4470/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4471/// _Block_object_dispose(_src->object,
4472/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4473/// [|BLOCK_FIELD_IS_WEAK]) // object
4474/// _Block_object_dispose(_src->object,
4475/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4476/// [|BLOCK_FIELD_IS_WEAK]) // block
4477/// }
4478
4479std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4480 int flag) {
4481 std::string S;
4482 if (CopyDestroyCache.count(flag))
4483 return S;
4484 CopyDestroyCache.insert(flag);
4485 S = "static void __Block_byref_id_object_copy_";
4486 S += utostr(flag);
4487 S += "(void *dst, void *src) {\n";
4488
4489 // offset into the object pointer is computed as:
4490 // void * + void* + int + int + void* + void *
4491 unsigned IntSize =
4492 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4493 unsigned VoidPtrSize =
4494 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4495
4496 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4497 S += " _Block_object_assign((char*)dst + ";
4498 S += utostr(offset);
4499 S += ", *(void * *) ((char*)src + ";
4500 S += utostr(offset);
4501 S += "), ";
4502 S += utostr(flag);
4503 S += ");\n}\n";
4504
4505 S += "static void __Block_byref_id_object_dispose_";
4506 S += utostr(flag);
4507 S += "(void *src) {\n";
4508 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4509 S += utostr(offset);
4510 S += "), ";
4511 S += utostr(flag);
4512 S += ");\n}\n";
4513 return S;
4514}
4515
4516/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4517/// the declaration into:
4518/// struct __Block_byref_ND {
4519/// void *__isa; // NULL for everything except __weak pointers
4520/// struct __Block_byref_ND *__forwarding;
4521/// int32_t __flags;
4522/// int32_t __size;
4523/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4524/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4525/// typex ND;
4526/// };
4527///
4528/// It then replaces declaration of ND variable with:
4529/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4530/// __size=sizeof(struct __Block_byref_ND),
4531/// ND=initializer-if-any};
4532///
4533///
4534void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4535 // Insert declaration for the function in which block literal is
4536 // used.
4537 if (CurFunctionDeclToDeclareForBlock)
4538 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4539 int flag = 0;
4540 int isa = 0;
4541 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4542 if (DeclLoc.isInvalid())
4543 // If type location is missing, it is because of missing type (a warning).
4544 // Use variable's location which is good for this case.
4545 DeclLoc = ND->getLocation();
4546 const char *startBuf = SM->getCharacterData(DeclLoc);
4547 SourceLocation X = ND->getLocEnd();
4548 X = SM->getExpansionLoc(X);
4549 const char *endBuf = SM->getCharacterData(X);
4550 std::string Name(ND->getNameAsString());
4551 std::string ByrefType;
4552 RewriteByRefString(ByrefType, Name, ND, true);
4553 ByrefType += " {\n";
4554 ByrefType += " void *__isa;\n";
4555 RewriteByRefString(ByrefType, Name, ND);
4556 ByrefType += " *__forwarding;\n";
4557 ByrefType += " int __flags;\n";
4558 ByrefType += " int __size;\n";
4559 // Add void *__Block_byref_id_object_copy;
4560 // void *__Block_byref_id_object_dispose; if needed.
4561 QualType Ty = ND->getType();
4562 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4563 if (HasCopyAndDispose) {
4564 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4565 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4566 }
4567
4568 QualType T = Ty;
4569 (void)convertBlockPointerToFunctionPointer(T);
4570 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4571
4572 ByrefType += " " + Name + ";\n";
4573 ByrefType += "};\n";
4574 // Insert this type in global scope. It is needed by helper function.
4575 SourceLocation FunLocStart;
4576 if (CurFunctionDef)
4577 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4578 else {
4579 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4580 FunLocStart = CurMethodDef->getLocStart();
4581 }
4582 InsertText(FunLocStart, ByrefType);
4583 if (Ty.isObjCGCWeak()) {
4584 flag |= BLOCK_FIELD_IS_WEAK;
4585 isa = 1;
4586 }
4587
4588 if (HasCopyAndDispose) {
4589 flag = BLOCK_BYREF_CALLER;
4590 QualType Ty = ND->getType();
4591 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4592 if (Ty->isBlockPointerType())
4593 flag |= BLOCK_FIELD_IS_BLOCK;
4594 else
4595 flag |= BLOCK_FIELD_IS_OBJECT;
4596 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4597 if (!HF.empty())
4598 InsertText(FunLocStart, HF);
4599 }
4600
4601 // struct __Block_byref_ND ND =
4602 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4603 // initializer-if-any};
4604 bool hasInit = (ND->getInit() != 0);
4605 unsigned flags = 0;
4606 if (HasCopyAndDispose)
4607 flags |= BLOCK_HAS_COPY_DISPOSE;
4608 Name = ND->getNameAsString();
4609 ByrefType.clear();
4610 RewriteByRefString(ByrefType, Name, ND);
4611 std::string ForwardingCastType("(");
4612 ForwardingCastType += ByrefType + " *)";
4613 if (!hasInit) {
4614 ByrefType += " " + Name + " = {(void*)";
4615 ByrefType += utostr(isa);
4616 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4617 ByrefType += utostr(flags);
4618 ByrefType += ", ";
4619 ByrefType += "sizeof(";
4620 RewriteByRefString(ByrefType, Name, ND);
4621 ByrefType += ")";
4622 if (HasCopyAndDispose) {
4623 ByrefType += ", __Block_byref_id_object_copy_";
4624 ByrefType += utostr(flag);
4625 ByrefType += ", __Block_byref_id_object_dispose_";
4626 ByrefType += utostr(flag);
4627 }
4628 ByrefType += "};\n";
4629 unsigned nameSize = Name.size();
4630 // for block or function pointer declaration. Name is aleady
4631 // part of the declaration.
4632 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4633 nameSize = 1;
4634 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4635 }
4636 else {
4637 SourceLocation startLoc;
4638 Expr *E = ND->getInit();
4639 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4640 startLoc = ECE->getLParenLoc();
4641 else
4642 startLoc = E->getLocStart();
4643 startLoc = SM->getExpansionLoc(startLoc);
4644 endBuf = SM->getCharacterData(startLoc);
4645 ByrefType += " " + Name;
4646 ByrefType += " = {(void*)";
4647 ByrefType += utostr(isa);
4648 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4649 ByrefType += utostr(flags);
4650 ByrefType += ", ";
4651 ByrefType += "sizeof(";
4652 RewriteByRefString(ByrefType, Name, ND);
4653 ByrefType += "), ";
4654 if (HasCopyAndDispose) {
4655 ByrefType += "__Block_byref_id_object_copy_";
4656 ByrefType += utostr(flag);
4657 ByrefType += ", __Block_byref_id_object_dispose_";
4658 ByrefType += utostr(flag);
4659 ByrefType += ", ";
4660 }
4661 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4662
4663 // Complete the newly synthesized compound expression by inserting a right
4664 // curly brace before the end of the declaration.
4665 // FIXME: This approach avoids rewriting the initializer expression. It
4666 // also assumes there is only one declarator. For example, the following
4667 // isn't currently supported by this routine (in general):
4668 //
4669 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4670 //
4671 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4672 const char *semiBuf = strchr(startInitializerBuf, ';');
4673 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4674 SourceLocation semiLoc =
4675 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4676
4677 InsertText(semiLoc, "}");
4678 }
4679 return;
4680}
4681
4682void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4683 // Add initializers for any closure decl refs.
4684 GetBlockDeclRefExprs(Exp->getBody());
4685 if (BlockDeclRefs.size()) {
4686 // Unique all "by copy" declarations.
4687 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004688 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004689 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4690 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4691 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4692 }
4693 }
4694 // Unique all "by ref" declarations.
4695 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004696 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004697 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4698 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4699 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4700 }
4701 }
4702 // Find any imported blocks...they will need special attention.
4703 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004704 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004705 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4706 BlockDeclRefs[i]->getType()->isBlockPointerType())
4707 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4708 }
4709}
4710
4711FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4712 IdentifierInfo *ID = &Context->Idents.get(name);
4713 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4714 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4715 SourceLocation(), ID, FType, 0, SC_Extern,
4716 SC_None, false, false);
4717}
4718
4719Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004720 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004721
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004722 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004723
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004724 Blocks.push_back(Exp);
4725
4726 CollectBlockDeclRefInfo(Exp);
4727
4728 // Add inner imported variables now used in current block.
4729 int countOfInnerDecls = 0;
4730 if (!InnerBlockDeclRefs.empty()) {
4731 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004732 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004733 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004734 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004735 // We need to save the copied-in variables in nested
4736 // blocks because it is needed at the end for some of the API generations.
4737 // See SynthesizeBlockLiterals routine.
4738 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4739 BlockDeclRefs.push_back(Exp);
4740 BlockByCopyDeclsPtrSet.insert(VD);
4741 BlockByCopyDecls.push_back(VD);
4742 }
John McCallf4b88a42012-03-10 09:33:50 +00004743 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004744 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4745 BlockDeclRefs.push_back(Exp);
4746 BlockByRefDeclsPtrSet.insert(VD);
4747 BlockByRefDecls.push_back(VD);
4748 }
4749 }
4750 // Find any imported blocks...they will need special attention.
4751 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004752 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004753 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4754 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4755 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4756 }
4757 InnerDeclRefsCount.push_back(countOfInnerDecls);
4758
4759 std::string FuncName;
4760
4761 if (CurFunctionDef)
4762 FuncName = CurFunctionDef->getNameAsString();
4763 else if (CurMethodDef)
4764 BuildUniqueMethodName(FuncName, CurMethodDef);
4765 else if (GlobalVarDecl)
4766 FuncName = std::string(GlobalVarDecl->getNameAsString());
4767
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004768 bool GlobalBlockExpr =
4769 block->getDeclContext()->getRedeclContext()->isFileContext();
4770
4771 if (GlobalBlockExpr && !GlobalVarDecl) {
4772 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4773 GlobalBlockExpr = false;
4774 }
4775
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004776 std::string BlockNumber = utostr(Blocks.size()-1);
4777
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004778 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4779
4780 // Get a pointer to the function type so we can cast appropriately.
4781 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4782 QualType FType = Context->getPointerType(BFT);
4783
4784 FunctionDecl *FD;
4785 Expr *NewRep;
4786
4787 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004788 std::string Tag;
4789
4790 if (GlobalBlockExpr)
4791 Tag = "__global_";
4792 else
4793 Tag = "__";
4794 Tag += FuncName + "_block_impl_" + BlockNumber;
4795
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004796 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004797 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004798 SourceLocation());
4799
4800 SmallVector<Expr*, 4> InitExprs;
4801
4802 // Initialize the block function.
4803 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004804 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4805 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004806 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4807 CK_BitCast, Arg);
4808 InitExprs.push_back(castExpr);
4809
4810 // Initialize the block descriptor.
4811 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4812
4813 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4814 SourceLocation(), SourceLocation(),
4815 &Context->Idents.get(DescData.c_str()),
4816 Context->VoidPtrTy, 0,
4817 SC_Static, SC_None);
4818 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004819 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004820 Context->VoidPtrTy,
4821 VK_LValue,
4822 SourceLocation()),
4823 UO_AddrOf,
4824 Context->getPointerType(Context->VoidPtrTy),
4825 VK_RValue, OK_Ordinary,
4826 SourceLocation());
4827 InitExprs.push_back(DescRefExpr);
4828
4829 // Add initializers for any closure decl refs.
4830 if (BlockDeclRefs.size()) {
4831 Expr *Exp;
4832 // Output all "by copy" declarations.
4833 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4834 E = BlockByCopyDecls.end(); I != E; ++I) {
4835 if (isObjCType((*I)->getType())) {
4836 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4837 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004838 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4839 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004840 if (HasLocalVariableExternalStorage(*I)) {
4841 QualType QT = (*I)->getType();
4842 QT = Context->getPointerType(QT);
4843 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4844 OK_Ordinary, SourceLocation());
4845 }
4846 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4847 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004848 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4849 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004850 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4851 CK_BitCast, Arg);
4852 } else {
4853 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004854 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4855 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004856 if (HasLocalVariableExternalStorage(*I)) {
4857 QualType QT = (*I)->getType();
4858 QT = Context->getPointerType(QT);
4859 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4860 OK_Ordinary, SourceLocation());
4861 }
4862
4863 }
4864 InitExprs.push_back(Exp);
4865 }
4866 // Output all "by ref" declarations.
4867 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4868 E = BlockByRefDecls.end(); I != E; ++I) {
4869 ValueDecl *ND = (*I);
4870 std::string Name(ND->getNameAsString());
4871 std::string RecName;
4872 RewriteByRefString(RecName, Name, ND, true);
4873 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4874 + sizeof("struct"));
4875 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4876 SourceLocation(), SourceLocation(),
4877 II);
4878 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4879 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4880
4881 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004882 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004883 SourceLocation());
4884 bool isNestedCapturedVar = false;
4885 if (block)
4886 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4887 ce = block->capture_end(); ci != ce; ++ci) {
4888 const VarDecl *variable = ci->getVariable();
4889 if (variable == ND && ci->isNested()) {
4890 assert (ci->isByRef() &&
4891 "SynthBlockInitExpr - captured block variable is not byref");
4892 isNestedCapturedVar = true;
4893 break;
4894 }
4895 }
4896 // captured nested byref variable has its address passed. Do not take
4897 // its address again.
4898 if (!isNestedCapturedVar)
4899 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4900 Context->getPointerType(Exp->getType()),
4901 VK_RValue, OK_Ordinary, SourceLocation());
4902 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4903 InitExprs.push_back(Exp);
4904 }
4905 }
4906 if (ImportedBlockDecls.size()) {
4907 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4908 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4909 unsigned IntSize =
4910 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4911 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4912 Context->IntTy, SourceLocation());
4913 InitExprs.push_back(FlagExp);
4914 }
4915 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4916 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004917
4918 if (GlobalBlockExpr) {
4919 assert (GlobalConstructionExp == 0 &&
4920 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4921 GlobalConstructionExp = NewRep;
4922 NewRep = DRE;
4923 }
4924
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004925 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4926 Context->getPointerType(NewRep->getType()),
4927 VK_RValue, OK_Ordinary, SourceLocation());
4928 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4929 NewRep);
4930 BlockDeclRefs.clear();
4931 BlockByRefDecls.clear();
4932 BlockByRefDeclsPtrSet.clear();
4933 BlockByCopyDecls.clear();
4934 BlockByCopyDeclsPtrSet.clear();
4935 ImportedBlockDecls.clear();
4936 return NewRep;
4937}
4938
4939bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4940 if (const ObjCForCollectionStmt * CS =
4941 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4942 return CS->getElement() == DS;
4943 return false;
4944}
4945
4946//===----------------------------------------------------------------------===//
4947// Function Body / Expression rewriting
4948//===----------------------------------------------------------------------===//
4949
4950Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4951 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4952 isa<DoStmt>(S) || isa<ForStmt>(S))
4953 Stmts.push_back(S);
4954 else if (isa<ObjCForCollectionStmt>(S)) {
4955 Stmts.push_back(S);
4956 ObjCBcLabelNo.push_back(++BcLabelCount);
4957 }
4958
4959 // Pseudo-object operations and ivar references need special
4960 // treatment because we're going to recursively rewrite them.
4961 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4962 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4963 return RewritePropertyOrImplicitSetter(PseudoOp);
4964 } else {
4965 return RewritePropertyOrImplicitGetter(PseudoOp);
4966 }
4967 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4968 return RewriteObjCIvarRefExpr(IvarRefExpr);
4969 }
4970
4971 SourceRange OrigStmtRange = S->getSourceRange();
4972
4973 // Perform a bottom up rewrite of all children.
4974 for (Stmt::child_range CI = S->children(); CI; ++CI)
4975 if (*CI) {
4976 Stmt *childStmt = (*CI);
4977 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4978 if (newStmt) {
4979 *CI = newStmt;
4980 }
4981 }
4982
4983 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004984 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004985 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4986 InnerContexts.insert(BE->getBlockDecl());
4987 ImportedLocalExternalDecls.clear();
4988 GetInnerBlockDeclRefExprs(BE->getBody(),
4989 InnerBlockDeclRefs, InnerContexts);
4990 // Rewrite the block body in place.
4991 Stmt *SaveCurrentBody = CurrentBody;
4992 CurrentBody = BE->getBody();
4993 PropParentMap = 0;
4994 // block literal on rhs of a property-dot-sytax assignment
4995 // must be replaced by its synthesize ast so getRewrittenText
4996 // works as expected. In this case, what actually ends up on RHS
4997 // is the blockTranscribed which is the helper function for the
4998 // block literal; as in: self.c = ^() {[ace ARR];};
4999 bool saveDisableReplaceStmt = DisableReplaceStmt;
5000 DisableReplaceStmt = false;
5001 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5002 DisableReplaceStmt = saveDisableReplaceStmt;
5003 CurrentBody = SaveCurrentBody;
5004 PropParentMap = 0;
5005 ImportedLocalExternalDecls.clear();
5006 // Now we snarf the rewritten text and stash it away for later use.
5007 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5008 RewrittenBlockExprs[BE] = Str;
5009
5010 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5011
5012 //blockTranscribed->dump();
5013 ReplaceStmt(S, blockTranscribed);
5014 return blockTranscribed;
5015 }
5016 // Handle specific things.
5017 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5018 return RewriteAtEncode(AtEncode);
5019
5020 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5021 return RewriteAtSelector(AtSelector);
5022
5023 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5024 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005025
5026 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5027 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005028
5029 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
5030 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005031
5032 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5033 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005034
5035 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5036#if 0
5037 // Before we rewrite it, put the original message expression in a comment.
5038 SourceLocation startLoc = MessExpr->getLocStart();
5039 SourceLocation endLoc = MessExpr->getLocEnd();
5040
5041 const char *startBuf = SM->getCharacterData(startLoc);
5042 const char *endBuf = SM->getCharacterData(endLoc);
5043
5044 std::string messString;
5045 messString += "// ";
5046 messString.append(startBuf, endBuf-startBuf+1);
5047 messString += "\n";
5048
5049 // FIXME: Missing definition of
5050 // InsertText(clang::SourceLocation, char const*, unsigned int).
5051 // InsertText(startLoc, messString.c_str(), messString.size());
5052 // Tried this, but it didn't work either...
5053 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5054#endif
5055 return RewriteMessageExpr(MessExpr);
5056 }
5057
5058 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5059 return RewriteObjCTryStmt(StmtTry);
5060
5061 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5062 return RewriteObjCSynchronizedStmt(StmtTry);
5063
5064 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5065 return RewriteObjCThrowStmt(StmtThrow);
5066
5067 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5068 return RewriteObjCProtocolExpr(ProtocolExp);
5069
5070 if (ObjCForCollectionStmt *StmtForCollection =
5071 dyn_cast<ObjCForCollectionStmt>(S))
5072 return RewriteObjCForCollectionStmt(StmtForCollection,
5073 OrigStmtRange.getEnd());
5074 if (BreakStmt *StmtBreakStmt =
5075 dyn_cast<BreakStmt>(S))
5076 return RewriteBreakStmt(StmtBreakStmt);
5077 if (ContinueStmt *StmtContinueStmt =
5078 dyn_cast<ContinueStmt>(S))
5079 return RewriteContinueStmt(StmtContinueStmt);
5080
5081 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5082 // and cast exprs.
5083 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5084 // FIXME: What we're doing here is modifying the type-specifier that
5085 // precedes the first Decl. In the future the DeclGroup should have
5086 // a separate type-specifier that we can rewrite.
5087 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5088 // the context of an ObjCForCollectionStmt. For example:
5089 // NSArray *someArray;
5090 // for (id <FooProtocol> index in someArray) ;
5091 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5092 // and it depends on the original text locations/positions.
5093 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5094 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5095
5096 // Blocks rewrite rules.
5097 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5098 DI != DE; ++DI) {
5099 Decl *SD = *DI;
5100 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5101 if (isTopLevelBlockPointerType(ND->getType()))
5102 RewriteBlockPointerDecl(ND);
5103 else if (ND->getType()->isFunctionPointerType())
5104 CheckFunctionPointerDecl(ND->getType(), ND);
5105 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5106 if (VD->hasAttr<BlocksAttr>()) {
5107 static unsigned uniqueByrefDeclCount = 0;
5108 assert(!BlockByRefDeclNo.count(ND) &&
5109 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5110 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5111 RewriteByRefVar(VD);
5112 }
5113 else
5114 RewriteTypeOfDecl(VD);
5115 }
5116 }
5117 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5118 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5119 RewriteBlockPointerDecl(TD);
5120 else if (TD->getUnderlyingType()->isFunctionPointerType())
5121 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5122 }
5123 }
5124 }
5125
5126 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5127 RewriteObjCQualifiedInterfaceTypes(CE);
5128
5129 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5130 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5131 assert(!Stmts.empty() && "Statement stack is empty");
5132 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5133 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5134 && "Statement stack mismatch");
5135 Stmts.pop_back();
5136 }
5137 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005138 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5139 ValueDecl *VD = DRE->getDecl();
5140 if (VD->hasAttr<BlocksAttr>())
5141 return RewriteBlockDeclRefExpr(DRE);
5142 if (HasLocalVariableExternalStorage(VD))
5143 return RewriteLocalVariableExternalStorage(DRE);
5144 }
5145
5146 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5147 if (CE->getCallee()->getType()->isBlockPointerType()) {
5148 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5149 ReplaceStmt(S, BlockCall);
5150 return BlockCall;
5151 }
5152 }
5153 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5154 RewriteCastExpr(CE);
5155 }
5156#if 0
5157 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5158 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5159 ICE->getSubExpr(),
5160 SourceLocation());
5161 // Get the new text.
5162 std::string SStr;
5163 llvm::raw_string_ostream Buf(SStr);
5164 Replacement->printPretty(Buf, *Context);
5165 const std::string &Str = Buf.str();
5166
5167 printf("CAST = %s\n", &Str[0]);
5168 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5169 delete S;
5170 return Replacement;
5171 }
5172#endif
5173 // Return this stmt unmodified.
5174 return S;
5175}
5176
5177void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5178 for (RecordDecl::field_iterator i = RD->field_begin(),
5179 e = RD->field_end(); i != e; ++i) {
5180 FieldDecl *FD = *i;
5181 if (isTopLevelBlockPointerType(FD->getType()))
5182 RewriteBlockPointerDecl(FD);
5183 if (FD->getType()->isObjCQualifiedIdType() ||
5184 FD->getType()->isObjCQualifiedInterfaceType())
5185 RewriteObjCQualifiedInterfaceTypes(FD);
5186 }
5187}
5188
5189/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5190/// main file of the input.
5191void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5192 switch (D->getKind()) {
5193 case Decl::Function: {
5194 FunctionDecl *FD = cast<FunctionDecl>(D);
5195 if (FD->isOverloadedOperator())
5196 return;
5197
5198 // Since function prototypes don't have ParmDecl's, we check the function
5199 // prototype. This enables us to rewrite function declarations and
5200 // definitions using the same code.
5201 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5202
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005203 if (!FD->isThisDeclarationADefinition())
5204 break;
5205
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005206 // FIXME: If this should support Obj-C++, support CXXTryStmt
5207 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5208 CurFunctionDef = FD;
5209 CurFunctionDeclToDeclareForBlock = FD;
5210 CurrentBody = Body;
5211 Body =
5212 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5213 FD->setBody(Body);
5214 CurrentBody = 0;
5215 if (PropParentMap) {
5216 delete PropParentMap;
5217 PropParentMap = 0;
5218 }
5219 // This synthesizes and inserts the block "impl" struct, invoke function,
5220 // and any copy/dispose helper functions.
5221 InsertBlockLiteralsWithinFunction(FD);
5222 CurFunctionDef = 0;
5223 CurFunctionDeclToDeclareForBlock = 0;
5224 }
5225 break;
5226 }
5227 case Decl::ObjCMethod: {
5228 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5229 if (CompoundStmt *Body = MD->getCompoundBody()) {
5230 CurMethodDef = MD;
5231 CurrentBody = Body;
5232 Body =
5233 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5234 MD->setBody(Body);
5235 CurrentBody = 0;
5236 if (PropParentMap) {
5237 delete PropParentMap;
5238 PropParentMap = 0;
5239 }
5240 InsertBlockLiteralsWithinMethod(MD);
5241 CurMethodDef = 0;
5242 }
5243 break;
5244 }
5245 case Decl::ObjCImplementation: {
5246 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5247 ClassImplementation.push_back(CI);
5248 break;
5249 }
5250 case Decl::ObjCCategoryImpl: {
5251 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5252 CategoryImplementation.push_back(CI);
5253 break;
5254 }
5255 case Decl::Var: {
5256 VarDecl *VD = cast<VarDecl>(D);
5257 RewriteObjCQualifiedInterfaceTypes(VD);
5258 if (isTopLevelBlockPointerType(VD->getType()))
5259 RewriteBlockPointerDecl(VD);
5260 else if (VD->getType()->isFunctionPointerType()) {
5261 CheckFunctionPointerDecl(VD->getType(), VD);
5262 if (VD->getInit()) {
5263 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5264 RewriteCastExpr(CE);
5265 }
5266 }
5267 } else if (VD->getType()->isRecordType()) {
5268 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5269 if (RD->isCompleteDefinition())
5270 RewriteRecordBody(RD);
5271 }
5272 if (VD->getInit()) {
5273 GlobalVarDecl = VD;
5274 CurrentBody = VD->getInit();
5275 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5276 CurrentBody = 0;
5277 if (PropParentMap) {
5278 delete PropParentMap;
5279 PropParentMap = 0;
5280 }
5281 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5282 GlobalVarDecl = 0;
5283
5284 // This is needed for blocks.
5285 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5286 RewriteCastExpr(CE);
5287 }
5288 }
5289 break;
5290 }
5291 case Decl::TypeAlias:
5292 case Decl::Typedef: {
5293 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5294 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5295 RewriteBlockPointerDecl(TD);
5296 else if (TD->getUnderlyingType()->isFunctionPointerType())
5297 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5298 }
5299 break;
5300 }
5301 case Decl::CXXRecord:
5302 case Decl::Record: {
5303 RecordDecl *RD = cast<RecordDecl>(D);
5304 if (RD->isCompleteDefinition())
5305 RewriteRecordBody(RD);
5306 break;
5307 }
5308 default:
5309 break;
5310 }
5311 // Nothing yet.
5312}
5313
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005314/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5315/// protocol reference symbols in the for of:
5316/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5317static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5318 ObjCProtocolDecl *PDecl,
5319 std::string &Result) {
5320 // Also output .objc_protorefs$B section and its meta-data.
5321 if (Context->getLangOpts().MicrosoftExt)
5322 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5323 Result += "struct _protocol_t *";
5324 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5325 Result += PDecl->getNameAsString();
5326 Result += " = &";
5327 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5328 Result += ";\n";
5329}
5330
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005331void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5332 if (Diags.hasErrorOccurred())
5333 return;
5334
5335 RewriteInclude();
5336
5337 // Here's a great place to add any extra declarations that may be needed.
5338 // Write out meta data for each @protocol(<expr>).
5339 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005340 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005341 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005342 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5343 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005344
5345 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005346 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5347 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5348 // Write struct declaration for the class matching its ivar declarations.
5349 // Note that for modern abi, this is postponed until the end of TU
5350 // because class extensions and the implementation might declare their own
5351 // private ivars.
5352 RewriteInterfaceDecl(CDecl);
5353 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005354
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005355 if (ClassImplementation.size() || CategoryImplementation.size())
5356 RewriteImplementations();
5357
5358 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5359 // we are done.
5360 if (const RewriteBuffer *RewriteBuf =
5361 Rewrite.getRewriteBufferFor(MainFileID)) {
5362 //printf("Changed:\n");
5363 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5364 } else {
5365 llvm::errs() << "No changes\n";
5366 }
5367
5368 if (ClassImplementation.size() || CategoryImplementation.size() ||
5369 ProtocolExprDecls.size()) {
5370 // Rewrite Objective-c meta data*
5371 std::string ResultStr;
5372 RewriteMetaDataIntoBuffer(ResultStr);
5373 // Emit metadata.
5374 *OutFile << ResultStr;
5375 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005376 // Emit ImageInfo;
5377 {
5378 std::string ResultStr;
5379 WriteImageInfo(ResultStr);
5380 *OutFile << ResultStr;
5381 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005382 OutFile->flush();
5383}
5384
5385void RewriteModernObjC::Initialize(ASTContext &context) {
5386 InitializeCommon(context);
5387
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005388 Preamble += "#ifndef __OBJC2__\n";
5389 Preamble += "#define __OBJC2__\n";
5390 Preamble += "#endif\n";
5391
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005392 // declaring objc_selector outside the parameter list removes a silly
5393 // scope related warning...
5394 if (IsHeader)
5395 Preamble = "#pragma once\n";
5396 Preamble += "struct objc_selector; struct objc_class;\n";
5397 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5398 Preamble += "struct objc_object *superClass; ";
5399 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005400 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005401 // These are currently generated.
5402 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005403 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005404 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5405 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005406 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5407 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005408 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005409 // These are generated but not necessary for functionality.
5410 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5411 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005412 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5413 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005414 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005415
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005416 // These need be generated for performance. Currently they are not,
5417 // using API calls instead.
5418 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5419 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5420 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5421
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005422 // Add a constructor for creating temporary objects.
5423 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5424 ": ";
5425 Preamble += "object(o), superClass(s) {} ";
5426 }
5427 Preamble += "};\n";
5428 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5429 Preamble += "typedef struct objc_object Protocol;\n";
5430 Preamble += "#define _REWRITER_typedef_Protocol\n";
5431 Preamble += "#endif\n";
5432 if (LangOpts.MicrosoftExt) {
5433 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5434 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005435 }
5436 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005437 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005438
5439 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5440 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5441 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5442 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5443 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5444
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005445 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5446 Preamble += "(const char *);\n";
5447 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5448 Preamble += "(struct objc_class *);\n";
5449 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5450 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005451 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005452 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005453 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5454 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005455 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5456 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5457 Preamble += "struct __objcFastEnumerationState {\n\t";
5458 Preamble += "unsigned long state;\n\t";
5459 Preamble += "void **itemsPtr;\n\t";
5460 Preamble += "unsigned long *mutationsPtr;\n\t";
5461 Preamble += "unsigned long extra[5];\n};\n";
5462 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5463 Preamble += "#define __FASTENUMERATIONSTATE\n";
5464 Preamble += "#endif\n";
5465 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5466 Preamble += "struct __NSConstantStringImpl {\n";
5467 Preamble += " int *isa;\n";
5468 Preamble += " int flags;\n";
5469 Preamble += " char *str;\n";
5470 Preamble += " long length;\n";
5471 Preamble += "};\n";
5472 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5473 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5474 Preamble += "#else\n";
5475 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5476 Preamble += "#endif\n";
5477 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5478 Preamble += "#endif\n";
5479 // Blocks preamble.
5480 Preamble += "#ifndef BLOCK_IMPL\n";
5481 Preamble += "#define BLOCK_IMPL\n";
5482 Preamble += "struct __block_impl {\n";
5483 Preamble += " void *isa;\n";
5484 Preamble += " int Flags;\n";
5485 Preamble += " int Reserved;\n";
5486 Preamble += " void *FuncPtr;\n";
5487 Preamble += "};\n";
5488 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5489 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5490 Preamble += "extern \"C\" __declspec(dllexport) "
5491 "void _Block_object_assign(void *, const void *, const int);\n";
5492 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5493 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5494 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5495 Preamble += "#else\n";
5496 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5497 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5498 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5499 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5500 Preamble += "#endif\n";
5501 Preamble += "#endif\n";
5502 if (LangOpts.MicrosoftExt) {
5503 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5504 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5505 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5506 Preamble += "#define __attribute__(X)\n";
5507 Preamble += "#endif\n";
5508 Preamble += "#define __weak\n";
5509 }
5510 else {
5511 Preamble += "#define __block\n";
5512 Preamble += "#define __weak\n";
5513 }
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00005514
5515 // Declarations required for modern objective-c array and dictionary literals.
5516 Preamble += "\n#include <stdarg.h>\n";
5517 Preamble += "struct __NSArray_literal {\n";
5518 Preamble += " void * *arr;\n";
5519 Preamble += " __NSArray_literal (unsigned int count, ...) {\n";
5520 Preamble += "\tva_list marker;\n";
5521 Preamble += "\tva_start(marker, count);\n";
5522 Preamble += "\tarr = new void *[count];\n";
5523 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
5524 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
5525 Preamble += "\tva_end( marker );\n";
5526 Preamble += " };\n";
5527 Preamble += " ~__NSArray_literal() {\n";
5528 Preamble += "\tdelete[] arr;\n";
5529 Preamble += " }\n";
5530 Preamble += "};\n";
5531
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005532 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5533 // as this avoids warning in any 64bit/32bit compilation model.
5534 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5535}
5536
5537/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5538/// ivar offset.
5539void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5540 std::string &Result) {
5541 if (ivar->isBitField()) {
5542 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5543 // place all bitfields at offset 0.
5544 Result += "0";
5545 } else {
5546 Result += "__OFFSETOFIVAR__(struct ";
5547 Result += ivar->getContainingInterface()->getNameAsString();
5548 if (LangOpts.MicrosoftExt)
5549 Result += "_IMPL";
5550 Result += ", ";
5551 Result += ivar->getNameAsString();
5552 Result += ")";
5553 }
5554}
5555
5556/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5557/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005558/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005559/// char *attributes;
5560/// }
5561
5562/// struct _prop_list_t {
5563/// uint32_t entsize; // sizeof(struct _prop_t)
5564/// uint32_t count_of_properties;
5565/// struct _prop_t prop_list[count_of_properties];
5566/// }
5567
5568/// struct _protocol_t;
5569
5570/// struct _protocol_list_t {
5571/// long protocol_count; // Note, this is 32/64 bit
5572/// struct _protocol_t * protocol_list[protocol_count];
5573/// }
5574
5575/// struct _objc_method {
5576/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005577/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005578/// char *_imp;
5579/// }
5580
5581/// struct _method_list_t {
5582/// uint32_t entsize; // sizeof(struct _objc_method)
5583/// uint32_t method_count;
5584/// struct _objc_method method_list[method_count];
5585/// }
5586
5587/// struct _protocol_t {
5588/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005589/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005590/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005591/// const struct method_list_t *instance_methods;
5592/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005593/// const struct method_list_t *optionalInstanceMethods;
5594/// const struct method_list_t *optionalClassMethods;
5595/// const struct _prop_list_t * properties;
5596/// const uint32_t size; // sizeof(struct _protocol_t)
5597/// const uint32_t flags; // = 0
5598/// const char ** extendedMethodTypes;
5599/// }
5600
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005601/// struct _ivar_t {
5602/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005603/// const char *name;
5604/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005605/// uint32_t alignment;
5606/// uint32_t size;
5607/// }
5608
5609/// struct _ivar_list_t {
5610/// uint32 entsize; // sizeof(struct _ivar_t)
5611/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005612/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005613/// }
5614
5615/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005616/// uint32_t flags;
5617/// uint32_t instanceStart;
5618/// uint32_t instanceSize;
5619/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005620/// const uint8_t *ivarLayout;
5621/// const char *name;
5622/// const struct _method_list_t *baseMethods;
5623/// const struct _protocol_list_t *baseProtocols;
5624/// const struct _ivar_list_t *ivars;
5625/// const uint8_t *weakIvarLayout;
5626/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005627/// }
5628
5629/// struct _class_t {
5630/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005631/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005632/// void *cache;
5633/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005634/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005635/// }
5636
5637/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005638/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005639/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005640/// const struct _method_list_t *instance_methods;
5641/// const struct _method_list_t *class_methods;
5642/// const struct _protocol_list_t *protocols;
5643/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005644/// }
5645
5646/// MessageRefTy - LLVM for:
5647/// struct _message_ref_t {
5648/// IMP messenger;
5649/// SEL name;
5650/// };
5651
5652/// SuperMessageRefTy - LLVM for:
5653/// struct _super_message_ref_t {
5654/// SUPER_IMP messenger;
5655/// SEL name;
5656/// };
5657
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005658static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005659 static bool meta_data_declared = false;
5660 if (meta_data_declared)
5661 return;
5662
5663 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005664 Result += "\tconst char *name;\n";
5665 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005666 Result += "};\n";
5667
5668 Result += "\nstruct _protocol_t;\n";
5669
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005670 Result += "\nstruct _objc_method {\n";
5671 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005672 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005673 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005674 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005675
5676 Result += "\nstruct _protocol_t {\n";
5677 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005678 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005679 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005680 Result += "\tconst struct method_list_t *instance_methods;\n";
5681 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005682 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5683 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5684 Result += "\tconst struct _prop_list_t * properties;\n";
5685 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5686 Result += "\tconst unsigned int flags; // = 0\n";
5687 Result += "\tconst char ** extendedMethodTypes;\n";
5688 Result += "};\n";
5689
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005690 Result += "\nstruct _ivar_t {\n";
5691 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005692 Result += "\tconst char *name;\n";
5693 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005694 Result += "\tunsigned int alignment;\n";
5695 Result += "\tunsigned int size;\n";
5696 Result += "};\n";
5697
5698 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005699 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005700 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005701 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005702 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5703 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005704 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005705 Result += "\tconst unsigned char *ivarLayout;\n";
5706 Result += "\tconst char *name;\n";
5707 Result += "\tconst struct _method_list_t *baseMethods;\n";
5708 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5709 Result += "\tconst struct _ivar_list_t *ivars;\n";
5710 Result += "\tconst unsigned char *weakIvarLayout;\n";
5711 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005712 Result += "};\n";
5713
5714 Result += "\nstruct _class_t {\n";
5715 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005716 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005717 Result += "\tvoid *cache;\n";
5718 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005719 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005720 Result += "};\n";
5721
5722 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005723 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005724 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005725 Result += "\tconst struct _method_list_t *instance_methods;\n";
5726 Result += "\tconst struct _method_list_t *class_methods;\n";
5727 Result += "\tconst struct _protocol_list_t *protocols;\n";
5728 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005729 Result += "};\n";
5730
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005731 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005732 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005733 meta_data_declared = true;
5734}
5735
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005736static void Write_protocol_list_t_TypeDecl(std::string &Result,
5737 long super_protocol_count) {
5738 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5739 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5740 Result += "\tstruct _protocol_t *super_protocols[";
5741 Result += utostr(super_protocol_count); Result += "];\n";
5742 Result += "}";
5743}
5744
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005745static void Write_method_list_t_TypeDecl(std::string &Result,
5746 unsigned int method_count) {
5747 Result += "struct /*_method_list_t*/"; Result += " {\n";
5748 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5749 Result += "\tunsigned int method_count;\n";
5750 Result += "\tstruct _objc_method method_list[";
5751 Result += utostr(method_count); Result += "];\n";
5752 Result += "}";
5753}
5754
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005755static void Write__prop_list_t_TypeDecl(std::string &Result,
5756 unsigned int property_count) {
5757 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5758 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5759 Result += "\tunsigned int count_of_properties;\n";
5760 Result += "\tstruct _prop_t prop_list[";
5761 Result += utostr(property_count); Result += "];\n";
5762 Result += "}";
5763}
5764
Fariborz Jahanianae932952012-02-10 20:47:10 +00005765static void Write__ivar_list_t_TypeDecl(std::string &Result,
5766 unsigned int ivar_count) {
5767 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5768 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5769 Result += "\tunsigned int count;\n";
5770 Result += "\tstruct _ivar_t ivar_list[";
5771 Result += utostr(ivar_count); Result += "];\n";
5772 Result += "}";
5773}
5774
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005775static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5776 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5777 StringRef VarName,
5778 StringRef ProtocolName) {
5779 if (SuperProtocols.size() > 0) {
5780 Result += "\nstatic ";
5781 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5782 Result += " "; Result += VarName;
5783 Result += ProtocolName;
5784 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5785 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5786 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5787 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5788 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5789 Result += SuperPD->getNameAsString();
5790 if (i == e-1)
5791 Result += "\n};\n";
5792 else
5793 Result += ",\n";
5794 }
5795 }
5796}
5797
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005798static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5799 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005800 ArrayRef<ObjCMethodDecl *> Methods,
5801 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005802 StringRef TopLevelDeclName,
5803 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005804 if (Methods.size() > 0) {
5805 Result += "\nstatic ";
5806 Write_method_list_t_TypeDecl(Result, Methods.size());
5807 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005808 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005809 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5810 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5811 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5812 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5813 ObjCMethodDecl *MD = Methods[i];
5814 if (i == 0)
5815 Result += "\t{{(struct objc_selector *)\"";
5816 else
5817 Result += "\t{(struct objc_selector *)\"";
5818 Result += (MD)->getSelector().getAsString(); Result += "\"";
5819 Result += ", ";
5820 std::string MethodTypeString;
5821 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5822 Result += "\""; Result += MethodTypeString; Result += "\"";
5823 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005824 if (!MethodImpl)
5825 Result += "0";
5826 else {
5827 Result += "(void *)";
5828 Result += RewriteObj.MethodInternalNames[MD];
5829 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005830 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005831 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005832 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005833 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005834 }
5835 Result += "};\n";
5836 }
5837}
5838
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005839static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005840 ASTContext *Context, std::string &Result,
5841 ArrayRef<ObjCPropertyDecl *> Properties,
5842 const Decl *Container,
5843 StringRef VarName,
5844 StringRef ProtocolName) {
5845 if (Properties.size() > 0) {
5846 Result += "\nstatic ";
5847 Write__prop_list_t_TypeDecl(Result, Properties.size());
5848 Result += " "; Result += VarName;
5849 Result += ProtocolName;
5850 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5851 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5852 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5853 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5854 ObjCPropertyDecl *PropDecl = Properties[i];
5855 if (i == 0)
5856 Result += "\t{{\"";
5857 else
5858 Result += "\t{\"";
5859 Result += PropDecl->getName(); Result += "\",";
5860 std::string PropertyTypeString, QuotePropertyTypeString;
5861 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5862 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5863 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5864 if (i == e-1)
5865 Result += "}}\n";
5866 else
5867 Result += "},\n";
5868 }
5869 Result += "};\n";
5870 }
5871}
5872
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005873// Metadata flags
5874enum MetaDataDlags {
5875 CLS = 0x0,
5876 CLS_META = 0x1,
5877 CLS_ROOT = 0x2,
5878 OBJC2_CLS_HIDDEN = 0x10,
5879 CLS_EXCEPTION = 0x20,
5880
5881 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5882 CLS_HAS_IVAR_RELEASER = 0x40,
5883 /// class was compiled with -fobjc-arr
5884 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5885};
5886
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005887static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5888 unsigned int flags,
5889 const std::string &InstanceStart,
5890 const std::string &InstanceSize,
5891 ArrayRef<ObjCMethodDecl *>baseMethods,
5892 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5893 ArrayRef<ObjCIvarDecl *>ivars,
5894 ArrayRef<ObjCPropertyDecl *>Properties,
5895 StringRef VarName,
5896 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005897 Result += "\nstatic struct _class_ro_t ";
5898 Result += VarName; Result += ClassName;
5899 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5900 Result += "\t";
5901 Result += llvm::utostr(flags); Result += ", ";
5902 Result += InstanceStart; Result += ", ";
5903 Result += InstanceSize; Result += ", \n";
5904 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005905 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5906 if (Triple.getArch() == llvm::Triple::x86_64)
5907 // uint32_t const reserved; // only when building for 64bit targets
5908 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005909 // const uint8_t * const ivarLayout;
5910 Result += "0, \n\t";
5911 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005912 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005913 if (baseMethods.size() > 0) {
5914 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005915 if (metaclass)
5916 Result += "_OBJC_$_CLASS_METHODS_";
5917 else
5918 Result += "_OBJC_$_INSTANCE_METHODS_";
5919 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005920 Result += ",\n\t";
5921 }
5922 else
5923 Result += "0, \n\t";
5924
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005925 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005926 Result += "(const struct _objc_protocol_list *)&";
5927 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5928 Result += ",\n\t";
5929 }
5930 else
5931 Result += "0, \n\t";
5932
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005933 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005934 Result += "(const struct _ivar_list_t *)&";
5935 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5936 Result += ",\n\t";
5937 }
5938 else
5939 Result += "0, \n\t";
5940
5941 // weakIvarLayout
5942 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005943 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005944 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005945 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005946 Result += ",\n";
5947 }
5948 else
5949 Result += "0, \n";
5950
5951 Result += "};\n";
5952}
5953
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005954static void Write_class_t(ASTContext *Context, std::string &Result,
5955 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005956 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5957 bool rootClass = (!CDecl->getSuperClass());
5958 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005959
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005960 if (!rootClass) {
5961 // Find the Root class
5962 RootClass = CDecl->getSuperClass();
5963 while (RootClass->getSuperClass()) {
5964 RootClass = RootClass->getSuperClass();
5965 }
5966 }
5967
5968 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005969 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005970 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005971 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005972 if (CDecl->getImplementation())
5973 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005974 else
5975 Result += "__declspec(dllimport) ";
5976
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005977 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005978 Result += CDecl->getNameAsString();
5979 Result += ";\n";
5980 }
5981 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005982 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005983 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005984 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005985 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005986 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005987 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005988 else
5989 Result += "__declspec(dllimport) ";
5990
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005991 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005992 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005993 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005994 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005995
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005996 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005997 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005998 if (RootClass->getImplementation())
5999 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006000 else
6001 Result += "__declspec(dllimport) ";
6002
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006003 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006004 Result += VarName;
6005 Result += RootClass->getNameAsString();
6006 Result += ";\n";
6007 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006008 }
6009
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006010 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6011 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006012 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6013 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006014 if (metaclass) {
6015 if (!rootClass) {
6016 Result += "0, // &"; Result += VarName;
6017 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006018 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006019 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006020 Result += CDecl->getSuperClass()->getNameAsString();
6021 Result += ",\n\t";
6022 }
6023 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006024 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006025 Result += CDecl->getNameAsString();
6026 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006027 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006028 Result += ",\n\t";
6029 }
6030 }
6031 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006032 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006033 Result += CDecl->getNameAsString();
6034 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006035 if (!rootClass) {
6036 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006037 Result += CDecl->getSuperClass()->getNameAsString();
6038 Result += ",\n\t";
6039 }
6040 else
6041 Result += "0,\n\t";
6042 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006043 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6044 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6045 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006046 Result += "&_OBJC_METACLASS_RO_$_";
6047 else
6048 Result += "&_OBJC_CLASS_RO_$_";
6049 Result += CDecl->getNameAsString();
6050 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006051
6052 // Add static function to initialize some of the meta-data fields.
6053 // avoid doing it twice.
6054 if (metaclass)
6055 return;
6056
6057 const ObjCInterfaceDecl *SuperClass =
6058 rootClass ? CDecl : CDecl->getSuperClass();
6059
6060 Result += "static void OBJC_CLASS_SETUP_$_";
6061 Result += CDecl->getNameAsString();
6062 Result += "(void ) {\n";
6063 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6064 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006065 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006066
6067 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006068 Result += ".superclass = ";
6069 if (rootClass)
6070 Result += "&OBJC_CLASS_$_";
6071 else
6072 Result += "&OBJC_METACLASS_$_";
6073
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006074 Result += SuperClass->getNameAsString(); Result += ";\n";
6075
6076 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6077 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6078
6079 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6080 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6081 Result += CDecl->getNameAsString(); Result += ";\n";
6082
6083 if (!rootClass) {
6084 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6085 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6086 Result += SuperClass->getNameAsString(); Result += ";\n";
6087 }
6088
6089 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6090 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6091 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006092}
6093
Fariborz Jahanian61186122012-02-17 18:40:41 +00006094static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6095 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006096 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006097 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006098 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6099 ArrayRef<ObjCMethodDecl *> ClassMethods,
6100 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6101 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006102 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006103 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006104 // must declare an extern class object in case this class is not implemented
6105 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006106 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006107 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006108 if (ClassDecl->getImplementation())
6109 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006110 else
6111 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006112
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006113 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006114 Result += "OBJC_CLASS_$_"; Result += ClassName;
6115 Result += ";\n";
6116
Fariborz Jahanian61186122012-02-17 18:40:41 +00006117 Result += "\nstatic struct _category_t ";
6118 Result += "_OBJC_$_CATEGORY_";
6119 Result += ClassName; Result += "_$_"; Result += CatName;
6120 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6121 Result += "{\n";
6122 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006123 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006124 Result += ",\n";
6125 if (InstanceMethods.size() > 0) {
6126 Result += "\t(const struct _method_list_t *)&";
6127 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6128 Result += ClassName; Result += "_$_"; Result += CatName;
6129 Result += ",\n";
6130 }
6131 else
6132 Result += "\t0,\n";
6133
6134 if (ClassMethods.size() > 0) {
6135 Result += "\t(const struct _method_list_t *)&";
6136 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6137 Result += ClassName; Result += "_$_"; Result += CatName;
6138 Result += ",\n";
6139 }
6140 else
6141 Result += "\t0,\n";
6142
6143 if (RefedProtocols.size() > 0) {
6144 Result += "\t(const struct _protocol_list_t *)&";
6145 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6146 Result += ClassName; Result += "_$_"; Result += CatName;
6147 Result += ",\n";
6148 }
6149 else
6150 Result += "\t0,\n";
6151
6152 if (ClassProperties.size() > 0) {
6153 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6154 Result += ClassName; Result += "_$_"; Result += CatName;
6155 Result += ",\n";
6156 }
6157 else
6158 Result += "\t0,\n";
6159
6160 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006161
6162 // Add static function to initialize the class pointer in the category structure.
6163 Result += "static void OBJC_CATEGORY_SETUP_$_";
6164 Result += ClassDecl->getNameAsString();
6165 Result += "_$_";
6166 Result += CatName;
6167 Result += "(void ) {\n";
6168 Result += "\t_OBJC_$_CATEGORY_";
6169 Result += ClassDecl->getNameAsString();
6170 Result += "_$_";
6171 Result += CatName;
6172 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6173 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006174}
6175
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006176static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6177 ASTContext *Context, std::string &Result,
6178 ArrayRef<ObjCMethodDecl *> Methods,
6179 StringRef VarName,
6180 StringRef ProtocolName) {
6181 if (Methods.size() == 0)
6182 return;
6183
6184 Result += "\nstatic const char *";
6185 Result += VarName; Result += ProtocolName;
6186 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6187 Result += "{\n";
6188 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6189 ObjCMethodDecl *MD = Methods[i];
6190 std::string MethodTypeString, QuoteMethodTypeString;
6191 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6192 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6193 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6194 if (i == e-1)
6195 Result += "\n};\n";
6196 else {
6197 Result += ",\n";
6198 }
6199 }
6200}
6201
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006202static void Write_IvarOffsetVar(ASTContext *Context,
6203 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006204 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006205 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006206 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6207 // this is what happens:
6208 /**
6209 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6210 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6211 Class->getVisibility() == HiddenVisibility)
6212 Visibility shoud be: HiddenVisibility;
6213 else
6214 Visibility shoud be: DefaultVisibility;
6215 */
6216
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006217 Result += "\n";
6218 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6219 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006220 if (Context->getLangOpts().MicrosoftExt)
6221 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6222
6223 if (!Context->getLangOpts().MicrosoftExt ||
6224 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006225 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006226 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006227 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006228 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006229 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006230 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6231 Result += " = ";
6232 if (IvarDecl->isBitField()) {
6233 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6234 // place all bitfields at offset 0.
6235 Result += "0;\n";
6236 }
6237 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006238 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006239 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006240 Result += "_IMPL, ";
6241 Result += IvarDecl->getName(); Result += ");\n";
6242 }
6243 }
6244}
6245
Fariborz Jahanianae932952012-02-10 20:47:10 +00006246static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6247 ASTContext *Context, std::string &Result,
6248 ArrayRef<ObjCIvarDecl *> Ivars,
6249 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006250 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006251 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006252 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006253
Fariborz Jahanianae932952012-02-10 20:47:10 +00006254 Result += "\nstatic ";
6255 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6256 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006257 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006258 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6259 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6260 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6261 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6262 ObjCIvarDecl *IvarDecl = Ivars[i];
6263 if (i == 0)
6264 Result += "\t{{";
6265 else
6266 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006267 Result += "(unsigned long int *)&";
6268 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006269 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006270
6271 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6272 std::string IvarTypeString, QuoteIvarTypeString;
6273 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6274 IvarDecl);
6275 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6276 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6277
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006278 // FIXME. this alignment represents the host alignment and need be changed to
6279 // represent the target alignment.
6280 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6281 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006282 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006283 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6284 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006285 if (i == e-1)
6286 Result += "}}\n";
6287 else
6288 Result += "},\n";
6289 }
6290 Result += "};\n";
6291 }
6292}
6293
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006294/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006295void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6296 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006297
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006298 // Do not synthesize the protocol more than once.
6299 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6300 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006301 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006302
6303 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6304 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006305 // Must write out all protocol definitions in current qualifier list,
6306 // and in their nested qualifiers before writing out current definition.
6307 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6308 E = PDecl->protocol_end(); I != E; ++I)
6309 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006310
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006311 // Construct method lists.
6312 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6313 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6314 for (ObjCProtocolDecl::instmeth_iterator
6315 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6316 I != E; ++I) {
6317 ObjCMethodDecl *MD = *I;
6318 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6319 OptInstanceMethods.push_back(MD);
6320 } else {
6321 InstanceMethods.push_back(MD);
6322 }
6323 }
6324
6325 for (ObjCProtocolDecl::classmeth_iterator
6326 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6327 I != E; ++I) {
6328 ObjCMethodDecl *MD = *I;
6329 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6330 OptClassMethods.push_back(MD);
6331 } else {
6332 ClassMethods.push_back(MD);
6333 }
6334 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006335 std::vector<ObjCMethodDecl *> AllMethods;
6336 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6337 AllMethods.push_back(InstanceMethods[i]);
6338 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6339 AllMethods.push_back(ClassMethods[i]);
6340 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6341 AllMethods.push_back(OptInstanceMethods[i]);
6342 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6343 AllMethods.push_back(OptClassMethods[i]);
6344
6345 Write__extendedMethodTypes_initializer(*this, Context, Result,
6346 AllMethods,
6347 "_OBJC_PROTOCOL_METHOD_TYPES_",
6348 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006349 // Protocol's super protocol list
6350 std::vector<ObjCProtocolDecl *> SuperProtocols;
6351 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6352 E = PDecl->protocol_end(); I != E; ++I)
6353 SuperProtocols.push_back(*I);
6354
6355 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6356 "_OBJC_PROTOCOL_REFS_",
6357 PDecl->getNameAsString());
6358
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006359 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006360 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006361 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006362
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006363 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006364 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006365 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006366
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006367 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006368 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006369 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006370
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006371 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006372 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006373 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006374
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006375 // Protocol's property metadata.
6376 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6377 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6378 E = PDecl->prop_end(); I != E; ++I)
6379 ProtocolProperties.push_back(*I);
6380
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006381 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006382 /* Container */0,
6383 "_OBJC_PROTOCOL_PROPERTIES_",
6384 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006385
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006386 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006387 Result += "\n";
6388 if (LangOpts.MicrosoftExt)
6389 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006390 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006391 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006392 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6393 Result += "\t0,\n"; // id is; is null
6394 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006395 if (SuperProtocols.size() > 0) {
6396 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6397 Result += PDecl->getNameAsString(); Result += ",\n";
6398 }
6399 else
6400 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006401 if (InstanceMethods.size() > 0) {
6402 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6403 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006404 }
6405 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006406 Result += "\t0,\n";
6407
6408 if (ClassMethods.size() > 0) {
6409 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6410 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006411 }
6412 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006413 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006414
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006415 if (OptInstanceMethods.size() > 0) {
6416 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6417 Result += PDecl->getNameAsString(); Result += ",\n";
6418 }
6419 else
6420 Result += "\t0,\n";
6421
6422 if (OptClassMethods.size() > 0) {
6423 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6424 Result += PDecl->getNameAsString(); Result += ",\n";
6425 }
6426 else
6427 Result += "\t0,\n";
6428
6429 if (ProtocolProperties.size() > 0) {
6430 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6431 Result += PDecl->getNameAsString(); Result += ",\n";
6432 }
6433 else
6434 Result += "\t0,\n";
6435
6436 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6437 Result += "\t0,\n";
6438
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006439 if (AllMethods.size() > 0) {
6440 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6441 Result += PDecl->getNameAsString();
6442 Result += "\n};\n";
6443 }
6444 else
6445 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006446
6447 // Use this protocol meta-data to build protocol list table in section
6448 // .objc_protolist$B
6449 // Unspecified visibility means 'private extern'.
6450 if (LangOpts.MicrosoftExt)
6451 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6452 Result += "struct _protocol_t *";
6453 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6454 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6455 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006456
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006457 // Mark this protocol as having been generated.
6458 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6459 llvm_unreachable("protocol already synthesized");
6460
6461}
6462
6463void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6464 const ObjCList<ObjCProtocolDecl> &Protocols,
6465 StringRef prefix, StringRef ClassName,
6466 std::string &Result) {
6467 if (Protocols.empty()) return;
6468
6469 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006470 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006471
6472 // Output the top lovel protocol meta-data for the class.
6473 /* struct _objc_protocol_list {
6474 struct _objc_protocol_list *next;
6475 int protocol_count;
6476 struct _objc_protocol *class_protocols[];
6477 }
6478 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006479 Result += "\n";
6480 if (LangOpts.MicrosoftExt)
6481 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6482 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006483 Result += "\tstruct _objc_protocol_list *next;\n";
6484 Result += "\tint protocol_count;\n";
6485 Result += "\tstruct _objc_protocol *class_protocols[";
6486 Result += utostr(Protocols.size());
6487 Result += "];\n} _OBJC_";
6488 Result += prefix;
6489 Result += "_PROTOCOLS_";
6490 Result += ClassName;
6491 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6492 "{\n\t0, ";
6493 Result += utostr(Protocols.size());
6494 Result += "\n";
6495
6496 Result += "\t,{&_OBJC_PROTOCOL_";
6497 Result += Protocols[0]->getNameAsString();
6498 Result += " \n";
6499
6500 for (unsigned i = 1; i != Protocols.size(); i++) {
6501 Result += "\t ,&_OBJC_PROTOCOL_";
6502 Result += Protocols[i]->getNameAsString();
6503 Result += "\n";
6504 }
6505 Result += "\t }\n};\n";
6506}
6507
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006508/// hasObjCExceptionAttribute - Return true if this class or any super
6509/// class has the __objc_exception__ attribute.
6510/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6511static bool hasObjCExceptionAttribute(ASTContext &Context,
6512 const ObjCInterfaceDecl *OID) {
6513 if (OID->hasAttr<ObjCExceptionAttr>())
6514 return true;
6515 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6516 return hasObjCExceptionAttribute(Context, Super);
6517 return false;
6518}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006519
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006520void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6521 std::string &Result) {
6522 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6523
6524 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006525 if (CDecl->isImplicitInterfaceDecl())
6526 assert(false &&
6527 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006528
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006529 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006530 SmallVector<ObjCIvarDecl *, 8> IVars;
6531
6532 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6533 IVD; IVD = IVD->getNextIvar()) {
6534 // Ignore unnamed bit-fields.
6535 if (!IVD->getDeclName())
6536 continue;
6537 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006538 }
6539
Fariborz Jahanianae932952012-02-10 20:47:10 +00006540 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006541 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006542 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006543
6544 // Build _objc_method_list for class's instance methods if needed
6545 SmallVector<ObjCMethodDecl *, 32>
6546 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6547
6548 // If any of our property implementations have associated getters or
6549 // setters, produce metadata for them as well.
6550 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6551 PropEnd = IDecl->propimpl_end();
6552 Prop != PropEnd; ++Prop) {
6553 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6554 continue;
6555 if (!(*Prop)->getPropertyIvarDecl())
6556 continue;
6557 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6558 if (!PD)
6559 continue;
6560 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6561 if (!Getter->isDefined())
6562 InstanceMethods.push_back(Getter);
6563 if (PD->isReadOnly())
6564 continue;
6565 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6566 if (!Setter->isDefined())
6567 InstanceMethods.push_back(Setter);
6568 }
6569
6570 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6571 "_OBJC_$_INSTANCE_METHODS_",
6572 IDecl->getNameAsString(), true);
6573
6574 SmallVector<ObjCMethodDecl *, 32>
6575 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6576
6577 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6578 "_OBJC_$_CLASS_METHODS_",
6579 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006580
6581 // Protocols referenced in class declaration?
6582 // Protocol's super protocol list
6583 std::vector<ObjCProtocolDecl *> RefedProtocols;
6584 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6585 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6586 E = Protocols.end();
6587 I != E; ++I) {
6588 RefedProtocols.push_back(*I);
6589 // Must write out all protocol definitions in current qualifier list,
6590 // and in their nested qualifiers before writing out current definition.
6591 RewriteObjCProtocolMetaData(*I, Result);
6592 }
6593
6594 Write_protocol_list_initializer(Context, Result,
6595 RefedProtocols,
6596 "_OBJC_CLASS_PROTOCOLS_$_",
6597 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006598
6599 // Protocol's property metadata.
6600 std::vector<ObjCPropertyDecl *> ClassProperties;
6601 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6602 E = CDecl->prop_end(); I != E; ++I)
6603 ClassProperties.push_back(*I);
6604
6605 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006606 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006607 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006608 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006609
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006610
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006611 // Data for initializing _class_ro_t metaclass meta-data
6612 uint32_t flags = CLS_META;
6613 std::string InstanceSize;
6614 std::string InstanceStart;
6615
6616
6617 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6618 if (classIsHidden)
6619 flags |= OBJC2_CLS_HIDDEN;
6620
6621 if (!CDecl->getSuperClass())
6622 // class is root
6623 flags |= CLS_ROOT;
6624 InstanceSize = "sizeof(struct _class_t)";
6625 InstanceStart = InstanceSize;
6626 Write__class_ro_t_initializer(Context, Result, flags,
6627 InstanceStart, InstanceSize,
6628 ClassMethods,
6629 0,
6630 0,
6631 0,
6632 "_OBJC_METACLASS_RO_$_",
6633 CDecl->getNameAsString());
6634
6635
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006636 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006637 flags = CLS;
6638 if (classIsHidden)
6639 flags |= OBJC2_CLS_HIDDEN;
6640
6641 if (hasObjCExceptionAttribute(*Context, CDecl))
6642 flags |= CLS_EXCEPTION;
6643
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006644 if (!CDecl->getSuperClass())
6645 // class is root
6646 flags |= CLS_ROOT;
6647
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006648 InstanceSize.clear();
6649 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006650 if (!ObjCSynthesizedStructs.count(CDecl)) {
6651 InstanceSize = "0";
6652 InstanceStart = "0";
6653 }
6654 else {
6655 InstanceSize = "sizeof(struct ";
6656 InstanceSize += CDecl->getNameAsString();
6657 InstanceSize += "_IMPL)";
6658
6659 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6660 if (IVD) {
6661 InstanceStart += "__OFFSETOFIVAR__(struct ";
6662 InstanceStart += CDecl->getNameAsString();
6663 InstanceStart += "_IMPL, ";
6664 InstanceStart += IVD->getNameAsString();
6665 InstanceStart += ")";
6666 }
6667 else
6668 InstanceStart = InstanceSize;
6669 }
6670 Write__class_ro_t_initializer(Context, Result, flags,
6671 InstanceStart, InstanceSize,
6672 InstanceMethods,
6673 RefedProtocols,
6674 IVars,
6675 ClassProperties,
6676 "_OBJC_CLASS_RO_$_",
6677 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006678
6679 Write_class_t(Context, Result,
6680 "OBJC_METACLASS_$_",
6681 CDecl, /*metaclass*/true);
6682
6683 Write_class_t(Context, Result,
6684 "OBJC_CLASS_$_",
6685 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006686
6687 if (ImplementationIsNonLazy(IDecl))
6688 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006689
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006690}
6691
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006692void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6693 int ClsDefCount = ClassImplementation.size();
6694 if (!ClsDefCount)
6695 return;
6696 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6697 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6698 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6699 for (int i = 0; i < ClsDefCount; i++) {
6700 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6701 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6702 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6703 Result += CDecl->getName(); Result += ",\n";
6704 }
6705 Result += "};\n";
6706}
6707
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006708void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6709 int ClsDefCount = ClassImplementation.size();
6710 int CatDefCount = CategoryImplementation.size();
6711
6712 // For each implemented class, write out all its meta data.
6713 for (int i = 0; i < ClsDefCount; i++)
6714 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6715
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006716 RewriteClassSetupInitHook(Result);
6717
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006718 // For each implemented category, write out all its meta data.
6719 for (int i = 0; i < CatDefCount; i++)
6720 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6721
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006722 RewriteCategorySetupInitHook(Result);
6723
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006724 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006725 if (LangOpts.MicrosoftExt)
6726 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006727 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6728 Result += llvm::utostr(ClsDefCount); Result += "]";
6729 Result +=
6730 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6731 "regular,no_dead_strip\")))= {\n";
6732 for (int i = 0; i < ClsDefCount; i++) {
6733 Result += "\t&OBJC_CLASS_$_";
6734 Result += ClassImplementation[i]->getNameAsString();
6735 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006736 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006737 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006738
6739 if (!DefinedNonLazyClasses.empty()) {
6740 if (LangOpts.MicrosoftExt)
6741 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6742 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6743 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6744 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6745 Result += ",\n";
6746 }
6747 Result += "};\n";
6748 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006749 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006750
6751 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006752 if (LangOpts.MicrosoftExt)
6753 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006754 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6755 Result += llvm::utostr(CatDefCount); Result += "]";
6756 Result +=
6757 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6758 "regular,no_dead_strip\")))= {\n";
6759 for (int i = 0; i < CatDefCount; i++) {
6760 Result += "\t&_OBJC_$_CATEGORY_";
6761 Result +=
6762 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6763 Result += "_$_";
6764 Result += CategoryImplementation[i]->getNameAsString();
6765 Result += ",\n";
6766 }
6767 Result += "};\n";
6768 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006769
6770 if (!DefinedNonLazyCategories.empty()) {
6771 if (LangOpts.MicrosoftExt)
6772 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6773 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6774 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6775 Result += "\t&_OBJC_$_CATEGORY_";
6776 Result +=
6777 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6778 Result += "_$_";
6779 Result += DefinedNonLazyCategories[i]->getNameAsString();
6780 Result += ",\n";
6781 }
6782 Result += "};\n";
6783 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006784}
6785
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006786void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6787 if (LangOpts.MicrosoftExt)
6788 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6789
6790 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6791 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006792 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006793}
6794
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006795/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6796/// implementation.
6797void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6798 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006799 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006800 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6801 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006802 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006803 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6804 CDecl = CDecl->getNextClassCategory())
6805 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6806 break;
6807
6808 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006809 FullCategoryName += "_$_";
6810 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006811
6812 // Build _objc_method_list for class's instance methods if needed
6813 SmallVector<ObjCMethodDecl *, 32>
6814 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6815
6816 // If any of our property implementations have associated getters or
6817 // setters, produce metadata for them as well.
6818 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6819 PropEnd = IDecl->propimpl_end();
6820 Prop != PropEnd; ++Prop) {
6821 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6822 continue;
6823 if (!(*Prop)->getPropertyIvarDecl())
6824 continue;
6825 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6826 if (!PD)
6827 continue;
6828 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6829 InstanceMethods.push_back(Getter);
6830 if (PD->isReadOnly())
6831 continue;
6832 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6833 InstanceMethods.push_back(Setter);
6834 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006835
Fariborz Jahanian61186122012-02-17 18:40:41 +00006836 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6837 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6838 FullCategoryName, true);
6839
6840 SmallVector<ObjCMethodDecl *, 32>
6841 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6842
6843 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6844 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6845 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006846
6847 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006848 // Protocol's super protocol list
6849 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006850 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6851 E = CDecl->protocol_end();
6852
6853 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006854 RefedProtocols.push_back(*I);
6855 // Must write out all protocol definitions in current qualifier list,
6856 // and in their nested qualifiers before writing out current definition.
6857 RewriteObjCProtocolMetaData(*I, Result);
6858 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006859
Fariborz Jahanian61186122012-02-17 18:40:41 +00006860 Write_protocol_list_initializer(Context, Result,
6861 RefedProtocols,
6862 "_OBJC_CATEGORY_PROTOCOLS_$_",
6863 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006864
Fariborz Jahanian61186122012-02-17 18:40:41 +00006865 // Protocol's property metadata.
6866 std::vector<ObjCPropertyDecl *> ClassProperties;
6867 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6868 E = CDecl->prop_end(); I != E; ++I)
6869 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006870
Fariborz Jahanian61186122012-02-17 18:40:41 +00006871 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6872 /* Container */0,
6873 "_OBJC_$_PROP_LIST_",
6874 FullCategoryName);
6875
6876 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006877 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006878 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006879 InstanceMethods,
6880 ClassMethods,
6881 RefedProtocols,
6882 ClassProperties);
6883
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006884 // Determine if this category is also "non-lazy".
6885 if (ImplementationIsNonLazy(IDecl))
6886 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006887
6888}
6889
6890void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
6891 int CatDefCount = CategoryImplementation.size();
6892 if (!CatDefCount)
6893 return;
6894 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6895 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6896 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
6897 for (int i = 0; i < CatDefCount; i++) {
6898 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
6899 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
6900 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6901 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
6902 Result += ClassDecl->getName();
6903 Result += "_$_";
6904 Result += CatDecl->getName();
6905 Result += ",\n";
6906 }
6907 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006908}
6909
6910// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6911/// class methods.
6912template<typename MethodIterator>
6913void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6914 MethodIterator MethodEnd,
6915 bool IsInstanceMethod,
6916 StringRef prefix,
6917 StringRef ClassName,
6918 std::string &Result) {
6919 if (MethodBegin == MethodEnd) return;
6920
6921 if (!objc_impl_method) {
6922 /* struct _objc_method {
6923 SEL _cmd;
6924 char *method_types;
6925 void *_imp;
6926 }
6927 */
6928 Result += "\nstruct _objc_method {\n";
6929 Result += "\tSEL _cmd;\n";
6930 Result += "\tchar *method_types;\n";
6931 Result += "\tvoid *_imp;\n";
6932 Result += "};\n";
6933
6934 objc_impl_method = true;
6935 }
6936
6937 // Build _objc_method_list for class's methods if needed
6938
6939 /* struct {
6940 struct _objc_method_list *next_method;
6941 int method_count;
6942 struct _objc_method method_list[];
6943 }
6944 */
6945 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006946 Result += "\n";
6947 if (LangOpts.MicrosoftExt) {
6948 if (IsInstanceMethod)
6949 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6950 else
6951 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6952 }
6953 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006954 Result += "\tstruct _objc_method_list *next_method;\n";
6955 Result += "\tint method_count;\n";
6956 Result += "\tstruct _objc_method method_list[";
6957 Result += utostr(NumMethods);
6958 Result += "];\n} _OBJC_";
6959 Result += prefix;
6960 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6961 Result += "_METHODS_";
6962 Result += ClassName;
6963 Result += " __attribute__ ((used, section (\"__OBJC, __";
6964 Result += IsInstanceMethod ? "inst" : "cls";
6965 Result += "_meth\")))= ";
6966 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6967
6968 Result += "\t,{{(SEL)\"";
6969 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6970 std::string MethodTypeString;
6971 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6972 Result += "\", \"";
6973 Result += MethodTypeString;
6974 Result += "\", (void *)";
6975 Result += MethodInternalNames[*MethodBegin];
6976 Result += "}\n";
6977 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6978 Result += "\t ,{(SEL)\"";
6979 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6980 std::string MethodTypeString;
6981 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6982 Result += "\", \"";
6983 Result += MethodTypeString;
6984 Result += "\", (void *)";
6985 Result += MethodInternalNames[*MethodBegin];
6986 Result += "}\n";
6987 }
6988 Result += "\t }\n};\n";
6989}
6990
6991Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6992 SourceRange OldRange = IV->getSourceRange();
6993 Expr *BaseExpr = IV->getBase();
6994
6995 // Rewrite the base, but without actually doing replaces.
6996 {
6997 DisableReplaceStmtScope S(*this);
6998 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6999 IV->setBase(BaseExpr);
7000 }
7001
7002 ObjCIvarDecl *D = IV->getDecl();
7003
7004 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007005
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007006 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7007 const ObjCInterfaceType *iFaceDecl =
7008 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7009 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7010 // lookup which class implements the instance variable.
7011 ObjCInterfaceDecl *clsDeclared = 0;
7012 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7013 clsDeclared);
7014 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7015
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007016 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007017 std::string IvarOffsetName;
7018 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7019
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007020 ReferencedIvars[clsDeclared].insert(D);
7021
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007022 // cast offset to "char *".
7023 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7024 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007025 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007026 BaseExpr);
7027 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7028 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7029 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007030 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7031 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007032 SourceLocation());
7033 BinaryOperator *addExpr =
7034 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7035 Context->getPointerType(Context->CharTy),
7036 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007037 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007038 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7039 SourceLocation(),
7040 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007041 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007042 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007043 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007044
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007045 castExpr = NoTypeInfoCStyleCastExpr(Context,
7046 castT,
7047 CK_BitCast,
7048 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007049 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007050 VK_LValue, OK_Ordinary,
7051 SourceLocation());
7052 PE = new (Context) ParenExpr(OldRange.getBegin(),
7053 OldRange.getEnd(),
7054 Exp);
7055
7056 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007057 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007058
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007059 ReplaceStmtWithRange(IV, Replacement, OldRange);
7060 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007061}