blob: 91e89d17590131bf73f6ddf4fbfcd8ff6f6f601a [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);
332
333 // Block rewriting.
334 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
335
336 // Block specific rewrite rules.
337 void RewriteBlockPointerDecl(NamedDecl *VD);
338 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000339 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000340 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
341 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
342
343 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
344 std::string &Result);
345
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000346 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
347
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000348 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
349
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000350 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
351 std::string &Result);
352
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000353 virtual void Initialize(ASTContext &context);
354
355 // Misc. AST transformation routines. Somtimes they end up calling
356 // rewriting routines on the new ASTs.
357 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
358 Expr **args, unsigned nargs,
359 SourceLocation StartLoc=SourceLocation(),
360 SourceLocation EndLoc=SourceLocation());
361
362 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
363 SourceLocation StartLoc=SourceLocation(),
364 SourceLocation EndLoc=SourceLocation());
365
366 void SynthCountByEnumWithState(std::string &buf);
367 void SynthMsgSendFunctionDecl();
368 void SynthMsgSendSuperFunctionDecl();
369 void SynthMsgSendStretFunctionDecl();
370 void SynthMsgSendFpretFunctionDecl();
371 void SynthMsgSendSuperStretFunctionDecl();
372 void SynthGetClassFunctionDecl();
373 void SynthGetMetaClassFunctionDecl();
374 void SynthGetSuperClassFunctionDecl();
375 void SynthSelGetUidFunctionDecl();
376 void SynthSuperContructorFunctionDecl();
377
378 // Rewriting metadata
379 template<typename MethodIterator>
380 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
381 MethodIterator MethodEnd,
382 bool IsInstanceMethod,
383 StringRef prefix,
384 StringRef ClassName,
385 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000386 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
387 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000388 virtual void RewriteObjCProtocolListMetaData(
389 const ObjCList<ObjCProtocolDecl> &Prots,
390 StringRef prefix, StringRef ClassName, std::string &Result);
391 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
392 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000393 virtual void RewriteClassSetupInitHook(std::string &Result);
394
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000395 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000396 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000397 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
398 std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000399 virtual void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000400
401 // Rewriting ivar
402 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
403 std::string &Result);
404 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
405
406
407 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
408 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
409 StringRef funcName, std::string Tag);
410 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
411 StringRef funcName, std::string Tag);
412 std::string SynthesizeBlockImpl(BlockExpr *CE,
413 std::string Tag, std::string Desc);
414 std::string SynthesizeBlockDescriptor(std::string DescTag,
415 std::string ImplTag,
416 int i, StringRef funcName,
417 unsigned hasCopy);
418 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
419 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
420 StringRef FunName);
421 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
422 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000423 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000424
425 // Misc. helper routines.
426 QualType getProtocolType();
427 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000428 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
429 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
430 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
431
432 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
433 void CollectBlockDeclRefInfo(BlockExpr *Exp);
434 void GetBlockDeclRefExprs(Stmt *S);
435 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000436 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000437 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
438
439 // We avoid calling Type::isBlockPointerType(), since it operates on the
440 // canonical type. We only care if the top-level type is a closure pointer.
441 bool isTopLevelBlockPointerType(QualType T) {
442 return isa<BlockPointerType>(T);
443 }
444
445 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
446 /// to a function pointer type and upon success, returns true; false
447 /// otherwise.
448 bool convertBlockPointerToFunctionPointer(QualType &T) {
449 if (isTopLevelBlockPointerType(T)) {
450 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
451 T = Context->getPointerType(BPT->getPointeeType());
452 return true;
453 }
454 return false;
455 }
456
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000457 bool convertObjCTypeToCStyleType(QualType &T);
458
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000459 bool needToScanForQualifiers(QualType T);
460 QualType getSuperStructType();
461 QualType getConstantStringStructType();
462 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
463 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
464
465 void convertToUnqualifiedObjCType(QualType &T) {
466 if (T->isObjCQualifiedIdType())
467 T = Context->getObjCIdType();
468 else if (T->isObjCQualifiedClassType())
469 T = Context->getObjCClassType();
470 else if (T->isObjCObjectPointerType() &&
471 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
472 if (const ObjCObjectPointerType * OBJPT =
473 T->getAsObjCInterfacePointerType()) {
474 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
475 T = QualType(IFaceT, 0);
476 T = Context->getPointerType(T);
477 }
478 }
479 }
480
481 // FIXME: This predicate seems like it would be useful to add to ASTContext.
482 bool isObjCType(QualType T) {
483 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
484 return false;
485
486 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
487
488 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
489 OCT == Context->getCanonicalType(Context->getObjCClassType()))
490 return true;
491
492 if (const PointerType *PT = OCT->getAs<PointerType>()) {
493 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
494 PT->getPointeeType()->isObjCQualifiedIdType())
495 return true;
496 }
497 return false;
498 }
499 bool PointerTypeTakesAnyBlockArguments(QualType QT);
500 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
501 void GetExtentOfArgList(const char *Name, const char *&LParen,
502 const char *&RParen);
503
504 void QuoteDoublequotes(std::string &From, std::string &To) {
505 for (unsigned i = 0; i < From.length(); i++) {
506 if (From[i] == '"')
507 To += "\\\"";
508 else
509 To += From[i];
510 }
511 }
512
513 QualType getSimpleFunctionType(QualType result,
514 const QualType *args,
515 unsigned numArgs,
516 bool variadic = false) {
517 if (result == Context->getObjCInstanceType())
518 result = Context->getObjCIdType();
519 FunctionProtoType::ExtProtoInfo fpi;
520 fpi.Variadic = variadic;
521 return Context->getFunctionType(result, args, numArgs, fpi);
522 }
523
524 // Helper function: create a CStyleCastExpr with trivial type source info.
525 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
526 CastKind Kind, Expr *E) {
527 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
528 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
529 SourceLocation(), SourceLocation());
530 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000531
532 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
533 IdentifierInfo* II = &Context->Idents.get("load");
534 Selector LoadSel = Context->Selectors.getSelector(0, &II);
535 return OD->getClassMethod(LoadSel) != 0;
536 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000537 };
538
539}
540
541void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
542 NamedDecl *D) {
543 if (const FunctionProtoType *fproto
544 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
545 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
546 E = fproto->arg_type_end(); I && (I != E); ++I)
547 if (isTopLevelBlockPointerType(*I)) {
548 // All the args are checked/rewritten. Don't call twice!
549 RewriteBlockPointerDecl(D);
550 break;
551 }
552 }
553}
554
555void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
556 const PointerType *PT = funcType->getAs<PointerType>();
557 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
558 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
559}
560
561static bool IsHeaderFile(const std::string &Filename) {
562 std::string::size_type DotPos = Filename.rfind('.');
563
564 if (DotPos == std::string::npos) {
565 // no file extension
566 return false;
567 }
568
569 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
570 // C header: .h
571 // C++ header: .hh or .H;
572 return Ext == "h" || Ext == "hh" || Ext == "H";
573}
574
575RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
576 DiagnosticsEngine &D, const LangOptions &LOpts,
577 bool silenceMacroWarn)
578 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
579 SilenceRewriteMacroWarning(silenceMacroWarn) {
580 IsHeader = IsHeaderFile(inFile);
581 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
582 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000583 // FIXME. This should be an error. But if block is not called, it is OK. And it
584 // may break including some headers.
585 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
586 "rewriting block literal declared in global scope is not implemented");
587
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000588 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
589 DiagnosticsEngine::Warning,
590 "rewriter doesn't support user-specified control flow semantics "
591 "for @try/@finally (code may not execute properly)");
592}
593
594ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
595 raw_ostream* OS,
596 DiagnosticsEngine &Diags,
597 const LangOptions &LOpts,
598 bool SilenceRewriteMacroWarning) {
599 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
600}
601
602void RewriteModernObjC::InitializeCommon(ASTContext &context) {
603 Context = &context;
604 SM = &Context->getSourceManager();
605 TUDecl = Context->getTranslationUnitDecl();
606 MsgSendFunctionDecl = 0;
607 MsgSendSuperFunctionDecl = 0;
608 MsgSendStretFunctionDecl = 0;
609 MsgSendSuperStretFunctionDecl = 0;
610 MsgSendFpretFunctionDecl = 0;
611 GetClassFunctionDecl = 0;
612 GetMetaClassFunctionDecl = 0;
613 GetSuperClassFunctionDecl = 0;
614 SelGetUidFunctionDecl = 0;
615 CFStringFunctionDecl = 0;
616 ConstantStringClassReference = 0;
617 NSStringRecord = 0;
618 CurMethodDef = 0;
619 CurFunctionDef = 0;
620 CurFunctionDeclToDeclareForBlock = 0;
621 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000622 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000623 SuperStructDecl = 0;
624 ProtocolTypeDecl = 0;
625 ConstantStringDecl = 0;
626 BcLabelCount = 0;
627 SuperContructorFunctionDecl = 0;
628 NumObjCStringLiterals = 0;
629 PropParentMap = 0;
630 CurrentBody = 0;
631 DisableReplaceStmt = false;
632 objc_impl_method = false;
633
634 // Get the ID and start/end of the main file.
635 MainFileID = SM->getMainFileID();
636 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
637 MainFileStart = MainBuf->getBufferStart();
638 MainFileEnd = MainBuf->getBufferEnd();
639
David Blaikie4e4d0842012-03-11 07:00:24 +0000640 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000641}
642
643//===----------------------------------------------------------------------===//
644// Top Level Driver Code
645//===----------------------------------------------------------------------===//
646
647void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
648 if (Diags.hasErrorOccurred())
649 return;
650
651 // Two cases: either the decl could be in the main file, or it could be in a
652 // #included file. If the former, rewrite it now. If the later, check to see
653 // if we rewrote the #include/#import.
654 SourceLocation Loc = D->getLocation();
655 Loc = SM->getExpansionLoc(Loc);
656
657 // If this is for a builtin, ignore it.
658 if (Loc.isInvalid()) return;
659
660 // Look for built-in declarations that we need to refer during the rewrite.
661 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
662 RewriteFunctionDecl(FD);
663 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
664 // declared in <Foundation/NSString.h>
665 if (FVD->getName() == "_NSConstantStringClassReference") {
666 ConstantStringClassReference = FVD;
667 return;
668 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000669 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
670 RewriteCategoryDecl(CD);
671 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
672 if (PD->isThisDeclarationADefinition())
673 RewriteProtocolDecl(PD);
674 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675 // Recurse into linkage specifications
676 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677 DIEnd = LSD->decls_end();
678 DI != DIEnd; ) {
679 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680 if (!IFace->isThisDeclarationADefinition()) {
681 SmallVector<Decl *, 8> DG;
682 SourceLocation StartLoc = IFace->getLocStart();
683 do {
684 if (isa<ObjCInterfaceDecl>(*DI) &&
685 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686 StartLoc == (*DI)->getLocStart())
687 DG.push_back(*DI);
688 else
689 break;
690
691 ++DI;
692 } while (DI != DIEnd);
693 RewriteForwardClassDecl(DG);
694 continue;
695 }
696 }
697
698 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699 if (!Proto->isThisDeclarationADefinition()) {
700 SmallVector<Decl *, 8> DG;
701 SourceLocation StartLoc = Proto->getLocStart();
702 do {
703 if (isa<ObjCProtocolDecl>(*DI) &&
704 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705 StartLoc == (*DI)->getLocStart())
706 DG.push_back(*DI);
707 else
708 break;
709
710 ++DI;
711 } while (DI != DIEnd);
712 RewriteForwardProtocolDecl(DG);
713 continue;
714 }
715 }
716
717 HandleTopLevelSingleDecl(*DI);
718 ++DI;
719 }
720 }
721 // If we have a decl in the main file, see if we should rewrite it.
722 if (SM->isFromMainFile(Loc))
723 return HandleDeclInMainFile(D);
724}
725
726//===----------------------------------------------------------------------===//
727// Syntactic (non-AST) Rewriting Code
728//===----------------------------------------------------------------------===//
729
730void RewriteModernObjC::RewriteInclude() {
731 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
732 StringRef MainBuf = SM->getBufferData(MainFileID);
733 const char *MainBufStart = MainBuf.begin();
734 const char *MainBufEnd = MainBuf.end();
735 size_t ImportLen = strlen("import");
736
737 // Loop over the whole file, looking for includes.
738 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
739 if (*BufPtr == '#') {
740 if (++BufPtr == MainBufEnd)
741 return;
742 while (*BufPtr == ' ' || *BufPtr == '\t')
743 if (++BufPtr == MainBufEnd)
744 return;
745 if (!strncmp(BufPtr, "import", ImportLen)) {
746 // replace import with include
747 SourceLocation ImportLoc =
748 LocStart.getLocWithOffset(BufPtr-MainBufStart);
749 ReplaceText(ImportLoc, ImportLen, "include");
750 BufPtr += ImportLen;
751 }
752 }
753 }
754}
755
756static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
758 std::string S;
759 S = "((struct ";
760 S += ClassDecl->getIdentifier()->getName();
761 S += "_IMPL *)self)->";
762 S += OID->getName();
763 return S;
764}
765
766void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767 ObjCImplementationDecl *IMD,
768 ObjCCategoryImplDecl *CID) {
769 static bool objcGetPropertyDefined = false;
770 static bool objcSetPropertyDefined = false;
771 SourceLocation startLoc = PID->getLocStart();
772 InsertText(startLoc, "// ");
773 const char *startBuf = SM->getCharacterData(startLoc);
774 assert((*startBuf == '@') && "bogus @synthesize location");
775 const char *semiBuf = strchr(startBuf, ';');
776 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
777 SourceLocation onePastSemiLoc =
778 startLoc.getLocWithOffset(semiBuf-startBuf+1);
779
780 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781 return; // FIXME: is this correct?
782
783 // Generate the 'getter' function.
784 ObjCPropertyDecl *PD = PID->getPropertyDecl();
785 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
786
787 if (!OID)
788 return;
789 unsigned Attributes = PD->getPropertyAttributes();
790 if (!PD->getGetterMethodDecl()->isDefined()) {
791 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
792 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
793 ObjCPropertyDecl::OBJC_PR_copy));
794 std::string Getr;
795 if (GenGetProperty && !objcGetPropertyDefined) {
796 objcGetPropertyDefined = true;
797 // FIXME. Is this attribute correct in all cases?
798 Getr = "\nextern \"C\" __declspec(dllimport) "
799 "id objc_getProperty(id, SEL, long, bool);\n";
800 }
801 RewriteObjCMethodDecl(OID->getContainingInterface(),
802 PD->getGetterMethodDecl(), Getr);
803 Getr += "{ ";
804 // Synthesize an explicit cast to gain access to the ivar.
805 // See objc-act.c:objc_synthesize_new_getter() for details.
806 if (GenGetProperty) {
807 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
808 Getr += "typedef ";
809 const FunctionType *FPRetType = 0;
810 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
811 FPRetType);
812 Getr += " _TYPE";
813 if (FPRetType) {
814 Getr += ")"; // close the precedence "scope" for "*".
815
816 // Now, emit the argument types (if any).
817 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
818 Getr += "(";
819 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
820 if (i) Getr += ", ";
821 std::string ParamStr = FT->getArgType(i).getAsString(
822 Context->getPrintingPolicy());
823 Getr += ParamStr;
824 }
825 if (FT->isVariadic()) {
826 if (FT->getNumArgs()) Getr += ", ";
827 Getr += "...";
828 }
829 Getr += ")";
830 } else
831 Getr += "()";
832 }
833 Getr += ";\n";
834 Getr += "return (_TYPE)";
835 Getr += "objc_getProperty(self, _cmd, ";
836 RewriteIvarOffsetComputation(OID, Getr);
837 Getr += ", 1)";
838 }
839 else
840 Getr += "return " + getIvarAccessString(OID);
841 Getr += "; }";
842 InsertText(onePastSemiLoc, Getr);
843 }
844
845 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
846 return;
847
848 // Generate the 'setter' function.
849 std::string Setr;
850 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
851 ObjCPropertyDecl::OBJC_PR_copy);
852 if (GenSetProperty && !objcSetPropertyDefined) {
853 objcSetPropertyDefined = true;
854 // FIXME. Is this attribute correct in all cases?
855 Setr = "\nextern \"C\" __declspec(dllimport) "
856 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
857 }
858
859 RewriteObjCMethodDecl(OID->getContainingInterface(),
860 PD->getSetterMethodDecl(), Setr);
861 Setr += "{ ";
862 // Synthesize an explicit cast to initialize the ivar.
863 // See objc-act.c:objc_synthesize_new_setter() for details.
864 if (GenSetProperty) {
865 Setr += "objc_setProperty (self, _cmd, ";
866 RewriteIvarOffsetComputation(OID, Setr);
867 Setr += ", (id)";
868 Setr += PD->getName();
869 Setr += ", ";
870 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
871 Setr += "0, ";
872 else
873 Setr += "1, ";
874 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
875 Setr += "1)";
876 else
877 Setr += "0)";
878 }
879 else {
880 Setr += getIvarAccessString(OID) + " = ";
881 Setr += PD->getName();
882 }
883 Setr += "; }";
884 InsertText(onePastSemiLoc, Setr);
885}
886
887static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
888 std::string &typedefString) {
889 typedefString += "#ifndef _REWRITER_typedef_";
890 typedefString += ForwardDecl->getNameAsString();
891 typedefString += "\n";
892 typedefString += "#define _REWRITER_typedef_";
893 typedefString += ForwardDecl->getNameAsString();
894 typedefString += "\n";
895 typedefString += "typedef struct objc_object ";
896 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000897 // typedef struct { } _objc_exc_Classname;
898 typedefString += ";\ntypedef struct {} _objc_exc_";
899 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000900 typedefString += ";\n#endif\n";
901}
902
903void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
904 const std::string &typedefString) {
905 SourceLocation startLoc = ClassDecl->getLocStart();
906 const char *startBuf = SM->getCharacterData(startLoc);
907 const char *semiPtr = strchr(startBuf, ';');
908 // Replace the @class with typedefs corresponding to the classes.
909 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
910}
911
912void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
913 std::string typedefString;
914 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
915 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
916 if (I == D.begin()) {
917 // Translate to typedef's that forward reference structs with the same name
918 // as the class. As a convenience, we include the original declaration
919 // as a comment.
920 typedefString += "// @class ";
921 typedefString += ForwardDecl->getNameAsString();
922 typedefString += ";\n";
923 }
924 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
925 }
926 DeclGroupRef::iterator I = D.begin();
927 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
928}
929
930void RewriteModernObjC::RewriteForwardClassDecl(
931 const llvm::SmallVector<Decl*, 8> &D) {
932 std::string typedefString;
933 for (unsigned i = 0; i < D.size(); i++) {
934 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
935 if (i == 0) {
936 typedefString += "// @class ";
937 typedefString += ForwardDecl->getNameAsString();
938 typedefString += ";\n";
939 }
940 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
941 }
942 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
943}
944
945void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
946 // When method is a synthesized one, such as a getter/setter there is
947 // nothing to rewrite.
948 if (Method->isImplicit())
949 return;
950 SourceLocation LocStart = Method->getLocStart();
951 SourceLocation LocEnd = Method->getLocEnd();
952
953 if (SM->getExpansionLineNumber(LocEnd) >
954 SM->getExpansionLineNumber(LocStart)) {
955 InsertText(LocStart, "#if 0\n");
956 ReplaceText(LocEnd, 1, ";\n#endif\n");
957 } else {
958 InsertText(LocStart, "// ");
959 }
960}
961
962void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
963 SourceLocation Loc = prop->getAtLoc();
964
965 ReplaceText(Loc, 0, "// ");
966 // FIXME: handle properties that are declared across multiple lines.
967}
968
969void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
970 SourceLocation LocStart = CatDecl->getLocStart();
971
972 // FIXME: handle category headers that are declared across multiple lines.
973 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000974 if (CatDecl->getIvarLBraceLoc().isValid())
975 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000976 for (ObjCCategoryDecl::ivar_iterator
977 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
978 ObjCIvarDecl *Ivar = (*I);
979 SourceLocation LocStart = Ivar->getLocStart();
980 ReplaceText(LocStart, 0, "// ");
981 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000982 if (CatDecl->getIvarRBraceLoc().isValid())
983 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
984
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000985 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
986 E = CatDecl->prop_end(); I != E; ++I)
987 RewriteProperty(*I);
988
989 for (ObjCCategoryDecl::instmeth_iterator
990 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
991 I != E; ++I)
992 RewriteMethodDeclaration(*I);
993 for (ObjCCategoryDecl::classmeth_iterator
994 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
995 I != E; ++I)
996 RewriteMethodDeclaration(*I);
997
998 // Lastly, comment out the @end.
999 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1000 strlen("@end"), "/* @end */");
1001}
1002
1003void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1004 SourceLocation LocStart = PDecl->getLocStart();
1005 assert(PDecl->isThisDeclarationADefinition());
1006
1007 // FIXME: handle protocol headers that are declared across multiple lines.
1008 ReplaceText(LocStart, 0, "// ");
1009
1010 for (ObjCProtocolDecl::instmeth_iterator
1011 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1012 I != E; ++I)
1013 RewriteMethodDeclaration(*I);
1014 for (ObjCProtocolDecl::classmeth_iterator
1015 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1016 I != E; ++I)
1017 RewriteMethodDeclaration(*I);
1018
1019 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1020 E = PDecl->prop_end(); I != E; ++I)
1021 RewriteProperty(*I);
1022
1023 // Lastly, comment out the @end.
1024 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1025 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1026
1027 // Must comment out @optional/@required
1028 const char *startBuf = SM->getCharacterData(LocStart);
1029 const char *endBuf = SM->getCharacterData(LocEnd);
1030 for (const char *p = startBuf; p < endBuf; p++) {
1031 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1032 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1033 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1034
1035 }
1036 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1037 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1038 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1039
1040 }
1041 }
1042}
1043
1044void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1045 SourceLocation LocStart = (*D.begin())->getLocStart();
1046 if (LocStart.isInvalid())
1047 llvm_unreachable("Invalid SourceLocation");
1048 // FIXME: handle forward protocol that are declared across multiple lines.
1049 ReplaceText(LocStart, 0, "// ");
1050}
1051
1052void
1053RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1054 SourceLocation LocStart = DG[0]->getLocStart();
1055 if (LocStart.isInvalid())
1056 llvm_unreachable("Invalid SourceLocation");
1057 // FIXME: handle forward protocol that are declared across multiple lines.
1058 ReplaceText(LocStart, 0, "// ");
1059}
1060
1061void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1062 const FunctionType *&FPRetType) {
1063 if (T->isObjCQualifiedIdType())
1064 ResultStr += "id";
1065 else if (T->isFunctionPointerType() ||
1066 T->isBlockPointerType()) {
1067 // needs special handling, since pointer-to-functions have special
1068 // syntax (where a decaration models use).
1069 QualType retType = T;
1070 QualType PointeeTy;
1071 if (const PointerType* PT = retType->getAs<PointerType>())
1072 PointeeTy = PT->getPointeeType();
1073 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1074 PointeeTy = BPT->getPointeeType();
1075 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1076 ResultStr += FPRetType->getResultType().getAsString(
1077 Context->getPrintingPolicy());
1078 ResultStr += "(*";
1079 }
1080 } else
1081 ResultStr += T.getAsString(Context->getPrintingPolicy());
1082}
1083
1084void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1085 ObjCMethodDecl *OMD,
1086 std::string &ResultStr) {
1087 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1088 const FunctionType *FPRetType = 0;
1089 ResultStr += "\nstatic ";
1090 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1091 ResultStr += " ";
1092
1093 // Unique method name
1094 std::string NameStr;
1095
1096 if (OMD->isInstanceMethod())
1097 NameStr += "_I_";
1098 else
1099 NameStr += "_C_";
1100
1101 NameStr += IDecl->getNameAsString();
1102 NameStr += "_";
1103
1104 if (ObjCCategoryImplDecl *CID =
1105 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1106 NameStr += CID->getNameAsString();
1107 NameStr += "_";
1108 }
1109 // Append selector names, replacing ':' with '_'
1110 {
1111 std::string selString = OMD->getSelector().getAsString();
1112 int len = selString.size();
1113 for (int i = 0; i < len; i++)
1114 if (selString[i] == ':')
1115 selString[i] = '_';
1116 NameStr += selString;
1117 }
1118 // Remember this name for metadata emission
1119 MethodInternalNames[OMD] = NameStr;
1120 ResultStr += NameStr;
1121
1122 // Rewrite arguments
1123 ResultStr += "(";
1124
1125 // invisible arguments
1126 if (OMD->isInstanceMethod()) {
1127 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1128 selfTy = Context->getPointerType(selfTy);
1129 if (!LangOpts.MicrosoftExt) {
1130 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1131 ResultStr += "struct ";
1132 }
1133 // When rewriting for Microsoft, explicitly omit the structure name.
1134 ResultStr += IDecl->getNameAsString();
1135 ResultStr += " *";
1136 }
1137 else
1138 ResultStr += Context->getObjCClassType().getAsString(
1139 Context->getPrintingPolicy());
1140
1141 ResultStr += " self, ";
1142 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1143 ResultStr += " _cmd";
1144
1145 // Method arguments.
1146 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1147 E = OMD->param_end(); PI != E; ++PI) {
1148 ParmVarDecl *PDecl = *PI;
1149 ResultStr += ", ";
1150 if (PDecl->getType()->isObjCQualifiedIdType()) {
1151 ResultStr += "id ";
1152 ResultStr += PDecl->getNameAsString();
1153 } else {
1154 std::string Name = PDecl->getNameAsString();
1155 QualType QT = PDecl->getType();
1156 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001157 (void)convertBlockPointerToFunctionPointer(QT);
1158 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001159 ResultStr += Name;
1160 }
1161 }
1162 if (OMD->isVariadic())
1163 ResultStr += ", ...";
1164 ResultStr += ") ";
1165
1166 if (FPRetType) {
1167 ResultStr += ")"; // close the precedence "scope" for "*".
1168
1169 // Now, emit the argument types (if any).
1170 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1171 ResultStr += "(";
1172 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1173 if (i) ResultStr += ", ";
1174 std::string ParamStr = FT->getArgType(i).getAsString(
1175 Context->getPrintingPolicy());
1176 ResultStr += ParamStr;
1177 }
1178 if (FT->isVariadic()) {
1179 if (FT->getNumArgs()) ResultStr += ", ";
1180 ResultStr += "...";
1181 }
1182 ResultStr += ")";
1183 } else {
1184 ResultStr += "()";
1185 }
1186 }
1187}
1188void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1189 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1190 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1191
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001192 if (IMD) {
1193 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001194 if (IMD->getIvarLBraceLoc().isValid())
1195 InsertText(IMD->getIvarLBraceLoc(), "// ");
1196 for (ObjCImplementationDecl::ivar_iterator
1197 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1198 ObjCIvarDecl *Ivar = (*I);
1199 SourceLocation LocStart = Ivar->getLocStart();
1200 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001201 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001202 if (IMD->getIvarRBraceLoc().isValid())
1203 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001204 }
1205 else
1206 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001207
1208 for (ObjCCategoryImplDecl::instmeth_iterator
1209 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1210 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1211 I != E; ++I) {
1212 std::string ResultStr;
1213 ObjCMethodDecl *OMD = *I;
1214 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1215 SourceLocation LocStart = OMD->getLocStart();
1216 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1217
1218 const char *startBuf = SM->getCharacterData(LocStart);
1219 const char *endBuf = SM->getCharacterData(LocEnd);
1220 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1221 }
1222
1223 for (ObjCCategoryImplDecl::classmeth_iterator
1224 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1225 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1226 I != E; ++I) {
1227 std::string ResultStr;
1228 ObjCMethodDecl *OMD = *I;
1229 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1230 SourceLocation LocStart = OMD->getLocStart();
1231 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1232
1233 const char *startBuf = SM->getCharacterData(LocStart);
1234 const char *endBuf = SM->getCharacterData(LocEnd);
1235 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1236 }
1237 for (ObjCCategoryImplDecl::propimpl_iterator
1238 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1239 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1240 I != E; ++I) {
1241 RewritePropertyImplDecl(*I, IMD, CID);
1242 }
1243
1244 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1245}
1246
1247void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001248 // Do not synthesize more than once.
1249 if (ObjCSynthesizedStructs.count(ClassDecl))
1250 return;
1251 // Make sure super class's are written before current class is written.
1252 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1253 while (SuperClass) {
1254 RewriteInterfaceDecl(SuperClass);
1255 SuperClass = SuperClass->getSuperClass();
1256 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001257 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001258 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001259 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001260 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001261 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1262
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001263 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001264 // Mark this typedef as having been written into its c++ equivalent.
1265 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001266
1267 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001268 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001269 RewriteProperty(*I);
1270 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001271 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001272 I != E; ++I)
1273 RewriteMethodDeclaration(*I);
1274 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001275 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001276 I != E; ++I)
1277 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001278
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001279 // Lastly, comment out the @end.
1280 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1281 "/* @end */");
1282 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001283}
1284
1285Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1286 SourceRange OldRange = PseudoOp->getSourceRange();
1287
1288 // We just magically know some things about the structure of this
1289 // expression.
1290 ObjCMessageExpr *OldMsg =
1291 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1292 PseudoOp->getNumSemanticExprs() - 1));
1293
1294 // Because the rewriter doesn't allow us to rewrite rewritten code,
1295 // we need to suppress rewriting the sub-statements.
1296 Expr *Base, *RHS;
1297 {
1298 DisableReplaceStmtScope S(*this);
1299
1300 // Rebuild the base expression if we have one.
1301 Base = 0;
1302 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1303 Base = OldMsg->getInstanceReceiver();
1304 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1305 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1306 }
1307
1308 // Rebuild the RHS.
1309 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1310 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1311 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1312 }
1313
1314 // TODO: avoid this copy.
1315 SmallVector<SourceLocation, 1> SelLocs;
1316 OldMsg->getSelectorLocs(SelLocs);
1317
1318 ObjCMessageExpr *NewMsg = 0;
1319 switch (OldMsg->getReceiverKind()) {
1320 case ObjCMessageExpr::Class:
1321 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1322 OldMsg->getValueKind(),
1323 OldMsg->getLeftLoc(),
1324 OldMsg->getClassReceiverTypeInfo(),
1325 OldMsg->getSelector(),
1326 SelLocs,
1327 OldMsg->getMethodDecl(),
1328 RHS,
1329 OldMsg->getRightLoc(),
1330 OldMsg->isImplicit());
1331 break;
1332
1333 case ObjCMessageExpr::Instance:
1334 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1335 OldMsg->getValueKind(),
1336 OldMsg->getLeftLoc(),
1337 Base,
1338 OldMsg->getSelector(),
1339 SelLocs,
1340 OldMsg->getMethodDecl(),
1341 RHS,
1342 OldMsg->getRightLoc(),
1343 OldMsg->isImplicit());
1344 break;
1345
1346 case ObjCMessageExpr::SuperClass:
1347 case ObjCMessageExpr::SuperInstance:
1348 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1349 OldMsg->getValueKind(),
1350 OldMsg->getLeftLoc(),
1351 OldMsg->getSuperLoc(),
1352 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1353 OldMsg->getSuperType(),
1354 OldMsg->getSelector(),
1355 SelLocs,
1356 OldMsg->getMethodDecl(),
1357 RHS,
1358 OldMsg->getRightLoc(),
1359 OldMsg->isImplicit());
1360 break;
1361 }
1362
1363 Stmt *Replacement = SynthMessageExpr(NewMsg);
1364 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1365 return Replacement;
1366}
1367
1368Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1369 SourceRange OldRange = PseudoOp->getSourceRange();
1370
1371 // We just magically know some things about the structure of this
1372 // expression.
1373 ObjCMessageExpr *OldMsg =
1374 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1375
1376 // Because the rewriter doesn't allow us to rewrite rewritten code,
1377 // we need to suppress rewriting the sub-statements.
1378 Expr *Base = 0;
1379 {
1380 DisableReplaceStmtScope S(*this);
1381
1382 // Rebuild the base expression if we have one.
1383 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1384 Base = OldMsg->getInstanceReceiver();
1385 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1386 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1387 }
1388 }
1389
1390 // Intentionally empty.
1391 SmallVector<SourceLocation, 1> SelLocs;
1392 SmallVector<Expr*, 1> Args;
1393
1394 ObjCMessageExpr *NewMsg = 0;
1395 switch (OldMsg->getReceiverKind()) {
1396 case ObjCMessageExpr::Class:
1397 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1398 OldMsg->getValueKind(),
1399 OldMsg->getLeftLoc(),
1400 OldMsg->getClassReceiverTypeInfo(),
1401 OldMsg->getSelector(),
1402 SelLocs,
1403 OldMsg->getMethodDecl(),
1404 Args,
1405 OldMsg->getRightLoc(),
1406 OldMsg->isImplicit());
1407 break;
1408
1409 case ObjCMessageExpr::Instance:
1410 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1411 OldMsg->getValueKind(),
1412 OldMsg->getLeftLoc(),
1413 Base,
1414 OldMsg->getSelector(),
1415 SelLocs,
1416 OldMsg->getMethodDecl(),
1417 Args,
1418 OldMsg->getRightLoc(),
1419 OldMsg->isImplicit());
1420 break;
1421
1422 case ObjCMessageExpr::SuperClass:
1423 case ObjCMessageExpr::SuperInstance:
1424 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1425 OldMsg->getValueKind(),
1426 OldMsg->getLeftLoc(),
1427 OldMsg->getSuperLoc(),
1428 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1429 OldMsg->getSuperType(),
1430 OldMsg->getSelector(),
1431 SelLocs,
1432 OldMsg->getMethodDecl(),
1433 Args,
1434 OldMsg->getRightLoc(),
1435 OldMsg->isImplicit());
1436 break;
1437 }
1438
1439 Stmt *Replacement = SynthMessageExpr(NewMsg);
1440 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1441 return Replacement;
1442}
1443
1444/// SynthCountByEnumWithState - To print:
1445/// ((unsigned int (*)
1446/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1447/// (void *)objc_msgSend)((id)l_collection,
1448/// sel_registerName(
1449/// "countByEnumeratingWithState:objects:count:"),
1450/// &enumState,
1451/// (id *)__rw_items, (unsigned int)16)
1452///
1453void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1454 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1455 "id *, unsigned int))(void *)objc_msgSend)";
1456 buf += "\n\t\t";
1457 buf += "((id)l_collection,\n\t\t";
1458 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1459 buf += "\n\t\t";
1460 buf += "&enumState, "
1461 "(id *)__rw_items, (unsigned int)16)";
1462}
1463
1464/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1465/// statement to exit to its outer synthesized loop.
1466///
1467Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1468 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1469 return S;
1470 // replace break with goto __break_label
1471 std::string buf;
1472
1473 SourceLocation startLoc = S->getLocStart();
1474 buf = "goto __break_label_";
1475 buf += utostr(ObjCBcLabelNo.back());
1476 ReplaceText(startLoc, strlen("break"), buf);
1477
1478 return 0;
1479}
1480
1481/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1482/// statement to continue with its inner synthesized loop.
1483///
1484Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1485 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1486 return S;
1487 // replace continue with goto __continue_label
1488 std::string buf;
1489
1490 SourceLocation startLoc = S->getLocStart();
1491 buf = "goto __continue_label_";
1492 buf += utostr(ObjCBcLabelNo.back());
1493 ReplaceText(startLoc, strlen("continue"), buf);
1494
1495 return 0;
1496}
1497
1498/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1499/// It rewrites:
1500/// for ( type elem in collection) { stmts; }
1501
1502/// Into:
1503/// {
1504/// type elem;
1505/// struct __objcFastEnumerationState enumState = { 0 };
1506/// id __rw_items[16];
1507/// id l_collection = (id)collection;
1508/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1509/// objects:__rw_items count:16];
1510/// if (limit) {
1511/// unsigned long startMutations = *enumState.mutationsPtr;
1512/// do {
1513/// unsigned long counter = 0;
1514/// do {
1515/// if (startMutations != *enumState.mutationsPtr)
1516/// objc_enumerationMutation(l_collection);
1517/// elem = (type)enumState.itemsPtr[counter++];
1518/// stmts;
1519/// __continue_label: ;
1520/// } while (counter < limit);
1521/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1522/// objects:__rw_items count:16]);
1523/// elem = nil;
1524/// __break_label: ;
1525/// }
1526/// else
1527/// elem = nil;
1528/// }
1529///
1530Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1531 SourceLocation OrigEnd) {
1532 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1533 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1534 "ObjCForCollectionStmt Statement stack mismatch");
1535 assert(!ObjCBcLabelNo.empty() &&
1536 "ObjCForCollectionStmt - Label No stack empty");
1537
1538 SourceLocation startLoc = S->getLocStart();
1539 const char *startBuf = SM->getCharacterData(startLoc);
1540 StringRef elementName;
1541 std::string elementTypeAsString;
1542 std::string buf;
1543 buf = "\n{\n\t";
1544 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1545 // type elem;
1546 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1547 QualType ElementType = cast<ValueDecl>(D)->getType();
1548 if (ElementType->isObjCQualifiedIdType() ||
1549 ElementType->isObjCQualifiedInterfaceType())
1550 // Simply use 'id' for all qualified types.
1551 elementTypeAsString = "id";
1552 else
1553 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1554 buf += elementTypeAsString;
1555 buf += " ";
1556 elementName = D->getName();
1557 buf += elementName;
1558 buf += ";\n\t";
1559 }
1560 else {
1561 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1562 elementName = DR->getDecl()->getName();
1563 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1564 if (VD->getType()->isObjCQualifiedIdType() ||
1565 VD->getType()->isObjCQualifiedInterfaceType())
1566 // Simply use 'id' for all qualified types.
1567 elementTypeAsString = "id";
1568 else
1569 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1570 }
1571
1572 // struct __objcFastEnumerationState enumState = { 0 };
1573 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1574 // id __rw_items[16];
1575 buf += "id __rw_items[16];\n\t";
1576 // id l_collection = (id)
1577 buf += "id l_collection = (id)";
1578 // Find start location of 'collection' the hard way!
1579 const char *startCollectionBuf = startBuf;
1580 startCollectionBuf += 3; // skip 'for'
1581 startCollectionBuf = strchr(startCollectionBuf, '(');
1582 startCollectionBuf++; // skip '('
1583 // find 'in' and skip it.
1584 while (*startCollectionBuf != ' ' ||
1585 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1586 (*(startCollectionBuf+3) != ' ' &&
1587 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1588 startCollectionBuf++;
1589 startCollectionBuf += 3;
1590
1591 // Replace: "for (type element in" with string constructed thus far.
1592 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1593 // Replace ')' in for '(' type elem in collection ')' with ';'
1594 SourceLocation rightParenLoc = S->getRParenLoc();
1595 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1596 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1597 buf = ";\n\t";
1598
1599 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1600 // objects:__rw_items count:16];
1601 // which is synthesized into:
1602 // unsigned int limit =
1603 // ((unsigned int (*)
1604 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1605 // (void *)objc_msgSend)((id)l_collection,
1606 // sel_registerName(
1607 // "countByEnumeratingWithState:objects:count:"),
1608 // (struct __objcFastEnumerationState *)&state,
1609 // (id *)__rw_items, (unsigned int)16);
1610 buf += "unsigned long limit =\n\t\t";
1611 SynthCountByEnumWithState(buf);
1612 buf += ";\n\t";
1613 /// if (limit) {
1614 /// unsigned long startMutations = *enumState.mutationsPtr;
1615 /// do {
1616 /// unsigned long counter = 0;
1617 /// do {
1618 /// if (startMutations != *enumState.mutationsPtr)
1619 /// objc_enumerationMutation(l_collection);
1620 /// elem = (type)enumState.itemsPtr[counter++];
1621 buf += "if (limit) {\n\t";
1622 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1623 buf += "do {\n\t\t";
1624 buf += "unsigned long counter = 0;\n\t\t";
1625 buf += "do {\n\t\t\t";
1626 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1627 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1628 buf += elementName;
1629 buf += " = (";
1630 buf += elementTypeAsString;
1631 buf += ")enumState.itemsPtr[counter++];";
1632 // Replace ')' in for '(' type elem in collection ')' with all of these.
1633 ReplaceText(lparenLoc, 1, buf);
1634
1635 /// __continue_label: ;
1636 /// } while (counter < limit);
1637 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1638 /// objects:__rw_items count:16]);
1639 /// elem = nil;
1640 /// __break_label: ;
1641 /// }
1642 /// else
1643 /// elem = nil;
1644 /// }
1645 ///
1646 buf = ";\n\t";
1647 buf += "__continue_label_";
1648 buf += utostr(ObjCBcLabelNo.back());
1649 buf += ": ;";
1650 buf += "\n\t\t";
1651 buf += "} while (counter < limit);\n\t";
1652 buf += "} while (limit = ";
1653 SynthCountByEnumWithState(buf);
1654 buf += ");\n\t";
1655 buf += elementName;
1656 buf += " = ((";
1657 buf += elementTypeAsString;
1658 buf += ")0);\n\t";
1659 buf += "__break_label_";
1660 buf += utostr(ObjCBcLabelNo.back());
1661 buf += ": ;\n\t";
1662 buf += "}\n\t";
1663 buf += "else\n\t\t";
1664 buf += elementName;
1665 buf += " = ((";
1666 buf += elementTypeAsString;
1667 buf += ")0);\n\t";
1668 buf += "}\n";
1669
1670 // Insert all these *after* the statement body.
1671 // FIXME: If this should support Obj-C++, support CXXTryStmt
1672 if (isa<CompoundStmt>(S->getBody())) {
1673 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1674 InsertText(endBodyLoc, buf);
1675 } else {
1676 /* Need to treat single statements specially. For example:
1677 *
1678 * for (A *a in b) if (stuff()) break;
1679 * for (A *a in b) xxxyy;
1680 *
1681 * The following code simply scans ahead to the semi to find the actual end.
1682 */
1683 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1684 const char *semiBuf = strchr(stmtBuf, ';');
1685 assert(semiBuf && "Can't find ';'");
1686 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1687 InsertText(endBodyLoc, buf);
1688 }
1689 Stmts.pop_back();
1690 ObjCBcLabelNo.pop_back();
1691 return 0;
1692}
1693
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001694static void Write_RethrowObject(std::string &buf) {
1695 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1696 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1697 buf += "\tid rethrow;\n";
1698 buf += "\t} _fin_force_rethow(_rethrow);";
1699}
1700
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001701/// RewriteObjCSynchronizedStmt -
1702/// This routine rewrites @synchronized(expr) stmt;
1703/// into:
1704/// objc_sync_enter(expr);
1705/// @try stmt @finally { objc_sync_exit(expr); }
1706///
1707Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1708 // Get the start location and compute the semi location.
1709 SourceLocation startLoc = S->getLocStart();
1710 const char *startBuf = SM->getCharacterData(startLoc);
1711
1712 assert((*startBuf == '@') && "bogus @synchronized location");
1713
1714 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001715 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001716
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001717 const char *lparenBuf = startBuf;
1718 while (*lparenBuf != '(') lparenBuf++;
1719 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001720
1721 buf = "; objc_sync_enter(_sync_obj);\n";
1722 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1723 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1724 buf += "\n\tid sync_exit;";
1725 buf += "\n\t} _sync_exit(_sync_obj);\n";
1726
1727 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1728 // the sync expression is typically a message expression that's already
1729 // been rewritten! (which implies the SourceLocation's are invalid).
1730 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1731 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1732 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1733 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1734
1735 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1736 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1737 assert (*LBraceLocBuf == '{');
1738 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001739
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001740 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001741 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1742 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001743
1744 buf = "} catch (id e) {_rethrow = e;}\n";
1745 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001746 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001747 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001748
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001749 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001750
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001751 return 0;
1752}
1753
1754void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1755{
1756 // Perform a bottom up traversal of all children.
1757 for (Stmt::child_range CI = S->children(); CI; ++CI)
1758 if (*CI)
1759 WarnAboutReturnGotoStmts(*CI);
1760
1761 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1762 Diags.Report(Context->getFullLoc(S->getLocStart()),
1763 TryFinallyContainsReturnDiag);
1764 }
1765 return;
1766}
1767
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001768Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001769 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001770 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001771 std::string buf;
1772
1773 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001774 if (noCatch)
1775 buf = "{ id volatile _rethrow = 0;\n";
1776 else {
1777 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1778 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001779 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001780 // Get the start location and compute the semi location.
1781 SourceLocation startLoc = S->getLocStart();
1782 const char *startBuf = SM->getCharacterData(startLoc);
1783
1784 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001785 if (finalStmt)
1786 ReplaceText(startLoc, 1, buf);
1787 else
1788 // @try -> try
1789 ReplaceText(startLoc, 1, "");
1790
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001791 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1792 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001793 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001794
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001795 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001796 bool AtRemoved = false;
1797 if (catchDecl) {
1798 QualType t = catchDecl->getType();
1799 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1800 // Should be a pointer to a class.
1801 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1802 if (IDecl) {
1803 std::string Result;
1804 startBuf = SM->getCharacterData(startLoc);
1805 assert((*startBuf == '@') && "bogus @catch location");
1806 SourceLocation rParenLoc = Catch->getRParenLoc();
1807 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1808
1809 // _objc_exc_Foo *_e as argument to catch.
1810 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1811 Result += " *_"; Result += catchDecl->getNameAsString();
1812 Result += ")";
1813 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1814 // Foo *e = (Foo *)_e;
1815 Result.clear();
1816 Result = "{ ";
1817 Result += IDecl->getNameAsString();
1818 Result += " *"; Result += catchDecl->getNameAsString();
1819 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1820 Result += "_"; Result += catchDecl->getNameAsString();
1821
1822 Result += "; ";
1823 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1824 ReplaceText(lBraceLoc, 1, Result);
1825 AtRemoved = true;
1826 }
1827 }
1828 }
1829 if (!AtRemoved)
1830 // @catch -> catch
1831 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001832
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001833 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001834 if (finalStmt) {
1835 buf.clear();
1836 if (noCatch)
1837 buf = "catch (id e) {_rethrow = e;}\n";
1838 else
1839 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1840
1841 SourceLocation startFinalLoc = finalStmt->getLocStart();
1842 ReplaceText(startFinalLoc, 8, buf);
1843 Stmt *body = finalStmt->getFinallyBody();
1844 SourceLocation startFinalBodyLoc = body->getLocStart();
1845 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001846 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001847 ReplaceText(startFinalBodyLoc, 1, buf);
1848
1849 SourceLocation endFinalBodyLoc = body->getLocEnd();
1850 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001851 // Now check for any return/continue/go statements within the @try.
1852 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001853 }
1854
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001855 return 0;
1856}
1857
1858// This can't be done with ReplaceStmt(S, ThrowExpr), since
1859// the throw expression is typically a message expression that's already
1860// been rewritten! (which implies the SourceLocation's are invalid).
1861Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1862 // Get the start location and compute the semi location.
1863 SourceLocation startLoc = S->getLocStart();
1864 const char *startBuf = SM->getCharacterData(startLoc);
1865
1866 assert((*startBuf == '@') && "bogus @throw location");
1867
1868 std::string buf;
1869 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1870 if (S->getThrowExpr())
1871 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001872 else
1873 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001874
1875 // handle "@ throw" correctly.
1876 const char *wBuf = strchr(startBuf, 'w');
1877 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1878 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1879
1880 const char *semiBuf = strchr(startBuf, ';');
1881 assert((*semiBuf == ';') && "@throw: can't find ';'");
1882 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001883 if (S->getThrowExpr())
1884 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001885 return 0;
1886}
1887
1888Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1889 // Create a new string expression.
1890 QualType StrType = Context->getPointerType(Context->CharTy);
1891 std::string StrEncoding;
1892 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1893 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1894 StringLiteral::Ascii, false,
1895 StrType, SourceLocation());
1896 ReplaceStmt(Exp, Replacement);
1897
1898 // Replace this subexpr in the parent.
1899 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1900 return Replacement;
1901}
1902
1903Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1904 if (!SelGetUidFunctionDecl)
1905 SynthSelGetUidFunctionDecl();
1906 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1907 // Create a call to sel_registerName("selName").
1908 SmallVector<Expr*, 8> SelExprs;
1909 QualType argType = Context->getPointerType(Context->CharTy);
1910 SelExprs.push_back(StringLiteral::Create(*Context,
1911 Exp->getSelector().getAsString(),
1912 StringLiteral::Ascii, false,
1913 argType, SourceLocation()));
1914 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1915 &SelExprs[0], SelExprs.size());
1916 ReplaceStmt(Exp, SelExp);
1917 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1918 return SelExp;
1919}
1920
1921CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1922 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1923 SourceLocation EndLoc) {
1924 // Get the type, we will need to reference it in a couple spots.
1925 QualType msgSendType = FD->getType();
1926
1927 // Create a reference to the objc_msgSend() declaration.
1928 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001929 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001930
1931 // Now, we cast the reference to a pointer to the objc_msgSend type.
1932 QualType pToFunc = Context->getPointerType(msgSendType);
1933 ImplicitCastExpr *ICE =
1934 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1935 DRE, 0, VK_RValue);
1936
1937 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1938
1939 CallExpr *Exp =
1940 new (Context) CallExpr(*Context, ICE, args, nargs,
1941 FT->getCallResultType(*Context),
1942 VK_RValue, EndLoc);
1943 return Exp;
1944}
1945
1946static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1947 const char *&startRef, const char *&endRef) {
1948 while (startBuf < endBuf) {
1949 if (*startBuf == '<')
1950 startRef = startBuf; // mark the start.
1951 if (*startBuf == '>') {
1952 if (startRef && *startRef == '<') {
1953 endRef = startBuf; // mark the end.
1954 return true;
1955 }
1956 return false;
1957 }
1958 startBuf++;
1959 }
1960 return false;
1961}
1962
1963static void scanToNextArgument(const char *&argRef) {
1964 int angle = 0;
1965 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1966 if (*argRef == '<')
1967 angle++;
1968 else if (*argRef == '>')
1969 angle--;
1970 argRef++;
1971 }
1972 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1973}
1974
1975bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1976 if (T->isObjCQualifiedIdType())
1977 return true;
1978 if (const PointerType *PT = T->getAs<PointerType>()) {
1979 if (PT->getPointeeType()->isObjCQualifiedIdType())
1980 return true;
1981 }
1982 if (T->isObjCObjectPointerType()) {
1983 T = T->getPointeeType();
1984 return T->isObjCQualifiedInterfaceType();
1985 }
1986 if (T->isArrayType()) {
1987 QualType ElemTy = Context->getBaseElementType(T);
1988 return needToScanForQualifiers(ElemTy);
1989 }
1990 return false;
1991}
1992
1993void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1994 QualType Type = E->getType();
1995 if (needToScanForQualifiers(Type)) {
1996 SourceLocation Loc, EndLoc;
1997
1998 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1999 Loc = ECE->getLParenLoc();
2000 EndLoc = ECE->getRParenLoc();
2001 } else {
2002 Loc = E->getLocStart();
2003 EndLoc = E->getLocEnd();
2004 }
2005 // This will defend against trying to rewrite synthesized expressions.
2006 if (Loc.isInvalid() || EndLoc.isInvalid())
2007 return;
2008
2009 const char *startBuf = SM->getCharacterData(Loc);
2010 const char *endBuf = SM->getCharacterData(EndLoc);
2011 const char *startRef = 0, *endRef = 0;
2012 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2013 // Get the locations of the startRef, endRef.
2014 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2015 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2016 // Comment out the protocol references.
2017 InsertText(LessLoc, "/*");
2018 InsertText(GreaterLoc, "*/");
2019 }
2020 }
2021}
2022
2023void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2024 SourceLocation Loc;
2025 QualType Type;
2026 const FunctionProtoType *proto = 0;
2027 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2028 Loc = VD->getLocation();
2029 Type = VD->getType();
2030 }
2031 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2032 Loc = FD->getLocation();
2033 // Check for ObjC 'id' and class types that have been adorned with protocol
2034 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2035 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2036 assert(funcType && "missing function type");
2037 proto = dyn_cast<FunctionProtoType>(funcType);
2038 if (!proto)
2039 return;
2040 Type = proto->getResultType();
2041 }
2042 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2043 Loc = FD->getLocation();
2044 Type = FD->getType();
2045 }
2046 else
2047 return;
2048
2049 if (needToScanForQualifiers(Type)) {
2050 // Since types are unique, we need to scan the buffer.
2051
2052 const char *endBuf = SM->getCharacterData(Loc);
2053 const char *startBuf = endBuf;
2054 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2055 startBuf--; // scan backward (from the decl location) for return type.
2056 const char *startRef = 0, *endRef = 0;
2057 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2058 // Get the locations of the startRef, endRef.
2059 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2060 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2061 // Comment out the protocol references.
2062 InsertText(LessLoc, "/*");
2063 InsertText(GreaterLoc, "*/");
2064 }
2065 }
2066 if (!proto)
2067 return; // most likely, was a variable
2068 // Now check arguments.
2069 const char *startBuf = SM->getCharacterData(Loc);
2070 const char *startFuncBuf = startBuf;
2071 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2072 if (needToScanForQualifiers(proto->getArgType(i))) {
2073 // Since types are unique, we need to scan the buffer.
2074
2075 const char *endBuf = startBuf;
2076 // scan forward (from the decl location) for argument types.
2077 scanToNextArgument(endBuf);
2078 const char *startRef = 0, *endRef = 0;
2079 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2080 // Get the locations of the startRef, endRef.
2081 SourceLocation LessLoc =
2082 Loc.getLocWithOffset(startRef-startFuncBuf);
2083 SourceLocation GreaterLoc =
2084 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2085 // Comment out the protocol references.
2086 InsertText(LessLoc, "/*");
2087 InsertText(GreaterLoc, "*/");
2088 }
2089 startBuf = ++endBuf;
2090 }
2091 else {
2092 // If the function name is derived from a macro expansion, then the
2093 // argument buffer will not follow the name. Need to speak with Chris.
2094 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2095 startBuf++; // scan forward (from the decl location) for argument types.
2096 startBuf++;
2097 }
2098 }
2099}
2100
2101void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2102 QualType QT = ND->getType();
2103 const Type* TypePtr = QT->getAs<Type>();
2104 if (!isa<TypeOfExprType>(TypePtr))
2105 return;
2106 while (isa<TypeOfExprType>(TypePtr)) {
2107 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2108 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2109 TypePtr = QT->getAs<Type>();
2110 }
2111 // FIXME. This will not work for multiple declarators; as in:
2112 // __typeof__(a) b,c,d;
2113 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2114 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2115 const char *startBuf = SM->getCharacterData(DeclLoc);
2116 if (ND->getInit()) {
2117 std::string Name(ND->getNameAsString());
2118 TypeAsString += " " + Name + " = ";
2119 Expr *E = ND->getInit();
2120 SourceLocation startLoc;
2121 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2122 startLoc = ECE->getLParenLoc();
2123 else
2124 startLoc = E->getLocStart();
2125 startLoc = SM->getExpansionLoc(startLoc);
2126 const char *endBuf = SM->getCharacterData(startLoc);
2127 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2128 }
2129 else {
2130 SourceLocation X = ND->getLocEnd();
2131 X = SM->getExpansionLoc(X);
2132 const char *endBuf = SM->getCharacterData(X);
2133 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2134 }
2135}
2136
2137// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2138void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2139 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2140 SmallVector<QualType, 16> ArgTys;
2141 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2142 QualType getFuncType =
2143 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2144 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2145 SourceLocation(),
2146 SourceLocation(),
2147 SelGetUidIdent, getFuncType, 0,
2148 SC_Extern,
2149 SC_None, false);
2150}
2151
2152void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2153 // declared in <objc/objc.h>
2154 if (FD->getIdentifier() &&
2155 FD->getName() == "sel_registerName") {
2156 SelGetUidFunctionDecl = FD;
2157 return;
2158 }
2159 RewriteObjCQualifiedInterfaceTypes(FD);
2160}
2161
2162void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2163 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2164 const char *argPtr = TypeString.c_str();
2165 if (!strchr(argPtr, '^')) {
2166 Str += TypeString;
2167 return;
2168 }
2169 while (*argPtr) {
2170 Str += (*argPtr == '^' ? '*' : *argPtr);
2171 argPtr++;
2172 }
2173}
2174
2175// FIXME. Consolidate this routine with RewriteBlockPointerType.
2176void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2177 ValueDecl *VD) {
2178 QualType Type = VD->getType();
2179 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2180 const char *argPtr = TypeString.c_str();
2181 int paren = 0;
2182 while (*argPtr) {
2183 switch (*argPtr) {
2184 case '(':
2185 Str += *argPtr;
2186 paren++;
2187 break;
2188 case ')':
2189 Str += *argPtr;
2190 paren--;
2191 break;
2192 case '^':
2193 Str += '*';
2194 if (paren == 1)
2195 Str += VD->getNameAsString();
2196 break;
2197 default:
2198 Str += *argPtr;
2199 break;
2200 }
2201 argPtr++;
2202 }
2203}
2204
2205
2206void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2207 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2208 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2209 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2210 if (!proto)
2211 return;
2212 QualType Type = proto->getResultType();
2213 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2214 FdStr += " ";
2215 FdStr += FD->getName();
2216 FdStr += "(";
2217 unsigned numArgs = proto->getNumArgs();
2218 for (unsigned i = 0; i < numArgs; i++) {
2219 QualType ArgType = proto->getArgType(i);
2220 RewriteBlockPointerType(FdStr, ArgType);
2221 if (i+1 < numArgs)
2222 FdStr += ", ";
2223 }
2224 FdStr += ");\n";
2225 InsertText(FunLocStart, FdStr);
2226 CurFunctionDeclToDeclareForBlock = 0;
2227}
2228
2229// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2230void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2231 if (SuperContructorFunctionDecl)
2232 return;
2233 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2234 SmallVector<QualType, 16> ArgTys;
2235 QualType argT = Context->getObjCIdType();
2236 assert(!argT.isNull() && "Can't find 'id' type");
2237 ArgTys.push_back(argT);
2238 ArgTys.push_back(argT);
2239 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2240 &ArgTys[0], ArgTys.size());
2241 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2242 SourceLocation(),
2243 SourceLocation(),
2244 msgSendIdent, msgSendType, 0,
2245 SC_Extern,
2246 SC_None, false);
2247}
2248
2249// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2250void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2251 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2252 SmallVector<QualType, 16> ArgTys;
2253 QualType argT = Context->getObjCIdType();
2254 assert(!argT.isNull() && "Can't find 'id' type");
2255 ArgTys.push_back(argT);
2256 argT = Context->getObjCSelType();
2257 assert(!argT.isNull() && "Can't find 'SEL' type");
2258 ArgTys.push_back(argT);
2259 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2260 &ArgTys[0], ArgTys.size(),
2261 true /*isVariadic*/);
2262 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2263 SourceLocation(),
2264 SourceLocation(),
2265 msgSendIdent, msgSendType, 0,
2266 SC_Extern,
2267 SC_None, false);
2268}
2269
2270// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2271void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2272 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2273 SmallVector<QualType, 16> ArgTys;
2274 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2275 SourceLocation(), SourceLocation(),
2276 &Context->Idents.get("objc_super"));
2277 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2278 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2279 ArgTys.push_back(argT);
2280 argT = Context->getObjCSelType();
2281 assert(!argT.isNull() && "Can't find 'SEL' type");
2282 ArgTys.push_back(argT);
2283 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2284 &ArgTys[0], ArgTys.size(),
2285 true /*isVariadic*/);
2286 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2287 SourceLocation(),
2288 SourceLocation(),
2289 msgSendIdent, msgSendType, 0,
2290 SC_Extern,
2291 SC_None, false);
2292}
2293
2294// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2295void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2296 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2297 SmallVector<QualType, 16> ArgTys;
2298 QualType argT = Context->getObjCIdType();
2299 assert(!argT.isNull() && "Can't find 'id' type");
2300 ArgTys.push_back(argT);
2301 argT = Context->getObjCSelType();
2302 assert(!argT.isNull() && "Can't find 'SEL' type");
2303 ArgTys.push_back(argT);
2304 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2305 &ArgTys[0], ArgTys.size(),
2306 true /*isVariadic*/);
2307 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2308 SourceLocation(),
2309 SourceLocation(),
2310 msgSendIdent, msgSendType, 0,
2311 SC_Extern,
2312 SC_None, false);
2313}
2314
2315// SynthMsgSendSuperStretFunctionDecl -
2316// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2317void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2318 IdentifierInfo *msgSendIdent =
2319 &Context->Idents.get("objc_msgSendSuper_stret");
2320 SmallVector<QualType, 16> ArgTys;
2321 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2322 SourceLocation(), SourceLocation(),
2323 &Context->Idents.get("objc_super"));
2324 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2325 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2326 ArgTys.push_back(argT);
2327 argT = Context->getObjCSelType();
2328 assert(!argT.isNull() && "Can't find 'SEL' type");
2329 ArgTys.push_back(argT);
2330 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2331 &ArgTys[0], ArgTys.size(),
2332 true /*isVariadic*/);
2333 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2334 SourceLocation(),
2335 SourceLocation(),
2336 msgSendIdent, msgSendType, 0,
2337 SC_Extern,
2338 SC_None, false);
2339}
2340
2341// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2342void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2343 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2344 SmallVector<QualType, 16> ArgTys;
2345 QualType argT = Context->getObjCIdType();
2346 assert(!argT.isNull() && "Can't find 'id' type");
2347 ArgTys.push_back(argT);
2348 argT = Context->getObjCSelType();
2349 assert(!argT.isNull() && "Can't find 'SEL' type");
2350 ArgTys.push_back(argT);
2351 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2352 &ArgTys[0], ArgTys.size(),
2353 true /*isVariadic*/);
2354 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2355 SourceLocation(),
2356 SourceLocation(),
2357 msgSendIdent, msgSendType, 0,
2358 SC_Extern,
2359 SC_None, false);
2360}
2361
2362// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2363void RewriteModernObjC::SynthGetClassFunctionDecl() {
2364 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2365 SmallVector<QualType, 16> ArgTys;
2366 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2367 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2368 &ArgTys[0], ArgTys.size());
2369 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2370 SourceLocation(),
2371 SourceLocation(),
2372 getClassIdent, getClassType, 0,
2373 SC_Extern,
2374 SC_None, false);
2375}
2376
2377// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2378void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2379 IdentifierInfo *getSuperClassIdent =
2380 &Context->Idents.get("class_getSuperclass");
2381 SmallVector<QualType, 16> ArgTys;
2382 ArgTys.push_back(Context->getObjCClassType());
2383 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2384 &ArgTys[0], ArgTys.size());
2385 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2386 SourceLocation(),
2387 SourceLocation(),
2388 getSuperClassIdent,
2389 getClassType, 0,
2390 SC_Extern,
2391 SC_None,
2392 false);
2393}
2394
2395// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2396void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2397 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2398 SmallVector<QualType, 16> ArgTys;
2399 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2400 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2401 &ArgTys[0], ArgTys.size());
2402 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2403 SourceLocation(),
2404 SourceLocation(),
2405 getClassIdent, getClassType, 0,
2406 SC_Extern,
2407 SC_None, false);
2408}
2409
2410Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2411 QualType strType = getConstantStringStructType();
2412
2413 std::string S = "__NSConstantStringImpl_";
2414
2415 std::string tmpName = InFileName;
2416 unsigned i;
2417 for (i=0; i < tmpName.length(); i++) {
2418 char c = tmpName.at(i);
2419 // replace any non alphanumeric characters with '_'.
2420 if (!isalpha(c) && (c < '0' || c > '9'))
2421 tmpName[i] = '_';
2422 }
2423 S += tmpName;
2424 S += "_";
2425 S += utostr(NumObjCStringLiterals++);
2426
2427 Preamble += "static __NSConstantStringImpl " + S;
2428 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2429 Preamble += "0x000007c8,"; // utf8_str
2430 // The pretty printer for StringLiteral handles escape characters properly.
2431 std::string prettyBufS;
2432 llvm::raw_string_ostream prettyBuf(prettyBufS);
2433 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2434 PrintingPolicy(LangOpts));
2435 Preamble += prettyBuf.str();
2436 Preamble += ",";
2437 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2438
2439 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2440 SourceLocation(), &Context->Idents.get(S),
2441 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002442 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002443 SourceLocation());
2444 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2445 Context->getPointerType(DRE->getType()),
2446 VK_RValue, OK_Ordinary,
2447 SourceLocation());
2448 // cast to NSConstantString *
2449 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2450 CK_CPointerToObjCPointerCast, Unop);
2451 ReplaceStmt(Exp, cast);
2452 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2453 return cast;
2454}
2455
Fariborz Jahanian55947042012-03-27 20:17:30 +00002456Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2457 unsigned IntSize =
2458 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2459
2460 Expr *FlagExp = IntegerLiteral::Create(*Context,
2461 llvm::APInt(IntSize, Exp->getValue()),
2462 Context->IntTy, Exp->getLocation());
2463 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2464 CK_BitCast, FlagExp);
2465 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2466 cast);
2467 ReplaceStmt(Exp, PE);
2468 return PE;
2469}
2470
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002471Stmt *RewriteModernObjC::RewriteObjCNumericLiteralExpr(ObjCNumericLiteral *Exp) {
2472 // synthesize declaration of helper functions needed in this routine.
2473 if (!SelGetUidFunctionDecl)
2474 SynthSelGetUidFunctionDecl();
2475 // use objc_msgSend() for all.
2476 if (!MsgSendFunctionDecl)
2477 SynthMsgSendFunctionDecl();
2478 if (!GetClassFunctionDecl)
2479 SynthGetClassFunctionDecl();
2480
2481 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2482 SourceLocation StartLoc = Exp->getLocStart();
2483 SourceLocation EndLoc = Exp->getLocEnd();
2484
2485 // Synthesize a call to objc_msgSend().
2486 SmallVector<Expr*, 4> MsgExprs;
2487 SmallVector<Expr*, 4> ClsExprs;
2488 QualType argType = Context->getPointerType(Context->CharTy);
2489 QualType expType = Exp->getType();
2490
2491 // Create a call to objc_getClass("NSNumber"). It will be th 1st argument.
2492 ObjCInterfaceDecl *Class =
2493 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2494
2495 IdentifierInfo *clsName = Class->getIdentifier();
2496 ClsExprs.push_back(StringLiteral::Create(*Context,
2497 clsName->getName(),
2498 StringLiteral::Ascii, false,
2499 argType, SourceLocation()));
2500 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2501 &ClsExprs[0],
2502 ClsExprs.size(),
2503 StartLoc, EndLoc);
2504 MsgExprs.push_back(Cls);
2505
2506 // Create a call to sel_registerName("numberWithBool:"), etc.
2507 // it will be the 2nd argument.
2508 SmallVector<Expr*, 4> SelExprs;
2509 ObjCMethodDecl *NumericMethod = Exp->getObjCNumericLiteralMethod();
2510 SelExprs.push_back(StringLiteral::Create(*Context,
2511 NumericMethod->getSelector().getAsString(),
2512 StringLiteral::Ascii, false,
2513 argType, SourceLocation()));
2514 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2515 &SelExprs[0], SelExprs.size(),
2516 StartLoc, EndLoc);
2517 MsgExprs.push_back(SelExp);
2518
2519 // User provided numeric literal is the 3rd, and last, argument.
2520 Expr *userExpr = Exp->getNumber();
2521 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2522 QualType type = ICE->getType();
2523 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2524 CastKind CK = CK_BitCast;
2525 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2526 CK = CK_IntegralToBoolean;
2527 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2528 }
2529 MsgExprs.push_back(userExpr);
2530
2531 SmallVector<QualType, 4> ArgTypes;
2532 ArgTypes.push_back(Context->getObjCIdType());
2533 ArgTypes.push_back(Context->getObjCSelType());
2534 for (ObjCMethodDecl::param_iterator PI = NumericMethod->param_begin(),
2535 E = NumericMethod->param_end(); PI != E; ++PI)
2536 ArgTypes.push_back((*PI)->getType());
2537
2538 QualType returnType = Exp->getType();
2539 // Get the type, we will need to reference it in a couple spots.
2540 QualType msgSendType = MsgSendFlavor->getType();
2541
2542 // Create a reference to the objc_msgSend() declaration.
2543 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2544 VK_LValue, SourceLocation());
2545
2546 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2547 Context->getPointerType(Context->VoidTy),
2548 CK_BitCast, DRE);
2549
2550 // Now do the "normal" pointer to function cast.
2551 QualType castType =
2552 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2553 NumericMethod->isVariadic());
2554 castType = Context->getPointerType(castType);
2555 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2556 cast);
2557
2558 // Don't forget the parens to enforce the proper binding.
2559 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2560
2561 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2562 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2563 MsgExprs.size(),
2564 FT->getResultType(), VK_RValue,
2565 EndLoc);
2566 ReplaceStmt(Exp, CE);
2567 return CE;
2568}
2569
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002570Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2571 // synthesize declaration of helper functions needed in this routine.
2572 if (!SelGetUidFunctionDecl)
2573 SynthSelGetUidFunctionDecl();
2574 // use objc_msgSend() for all.
2575 if (!MsgSendFunctionDecl)
2576 SynthMsgSendFunctionDecl();
2577 if (!GetClassFunctionDecl)
2578 SynthGetClassFunctionDecl();
2579
2580 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2581 SourceLocation StartLoc = Exp->getLocStart();
2582 SourceLocation EndLoc = Exp->getLocEnd();
2583
2584 // Synthesize a call to objc_msgSend().
2585 SmallVector<Expr*, 32> MsgExprs;
2586 SmallVector<Expr*, 4> ClsExprs;
2587 QualType argType = Context->getPointerType(Context->CharTy);
2588 QualType expType = Exp->getType();
2589
2590 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2591 ObjCInterfaceDecl *Class =
2592 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2593
2594 IdentifierInfo *clsName = Class->getIdentifier();
2595 ClsExprs.push_back(StringLiteral::Create(*Context,
2596 clsName->getName(),
2597 StringLiteral::Ascii, false,
2598 argType, SourceLocation()));
2599 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2600 &ClsExprs[0],
2601 ClsExprs.size(),
2602 StartLoc, EndLoc);
2603 MsgExprs.push_back(Cls);
2604
2605 // Create a call to sel_registerName("arrayWithObjects:count:").
2606 // it will be the 2nd argument.
2607 SmallVector<Expr*, 4> SelExprs;
2608 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2609 SelExprs.push_back(StringLiteral::Create(*Context,
2610 ArrayMethod->getSelector().getAsString(),
2611 StringLiteral::Ascii, false,
2612 argType, SourceLocation()));
2613 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2614 &SelExprs[0], SelExprs.size(),
2615 StartLoc, EndLoc);
2616 MsgExprs.push_back(SelExp);
2617
2618 unsigned NumElements = Exp->getNumElements();
2619
2620 // FIXME. Incomplete.
2621 InitListExpr *ILE =
2622 new (Context) InitListExpr(*Context, SourceLocation(),
2623 Exp->getElements(), NumElements,
2624 SourceLocation());
2625 MsgExprs.push_back(ILE);
2626 unsigned UnsignedIntSize =
2627 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2628
2629 Expr *count = IntegerLiteral::Create(*Context,
2630 llvm::APInt(UnsignedIntSize, NumElements),
2631 Context->UnsignedIntTy,
2632 SourceLocation());
2633 MsgExprs.push_back(count);
2634
2635
2636 SmallVector<QualType, 4> ArgTypes;
2637 ArgTypes.push_back(Context->getObjCIdType());
2638 ArgTypes.push_back(Context->getObjCSelType());
2639 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2640 E = ArrayMethod->param_end(); PI != E; ++PI)
2641 ArgTypes.push_back((*PI)->getType());
2642
2643 QualType returnType = Exp->getType();
2644 // Get the type, we will need to reference it in a couple spots.
2645 QualType msgSendType = MsgSendFlavor->getType();
2646
2647 // Create a reference to the objc_msgSend() declaration.
2648 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2649 VK_LValue, SourceLocation());
2650
2651 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2652 Context->getPointerType(Context->VoidTy),
2653 CK_BitCast, DRE);
2654
2655 // Now do the "normal" pointer to function cast.
2656 QualType castType =
2657 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2658 ArrayMethod->isVariadic());
2659 castType = Context->getPointerType(castType);
2660 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2661 cast);
2662
2663 // Don't forget the parens to enforce the proper binding.
2664 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2665
2666 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2667 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2668 MsgExprs.size(),
2669 FT->getResultType(), VK_RValue,
2670 EndLoc);
2671 ReplaceStmt(Exp, CE);
2672 return CE;
2673}
2674
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002675// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2676QualType RewriteModernObjC::getSuperStructType() {
2677 if (!SuperStructDecl) {
2678 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2679 SourceLocation(), SourceLocation(),
2680 &Context->Idents.get("objc_super"));
2681 QualType FieldTypes[2];
2682
2683 // struct objc_object *receiver;
2684 FieldTypes[0] = Context->getObjCIdType();
2685 // struct objc_class *super;
2686 FieldTypes[1] = Context->getObjCClassType();
2687
2688 // Create fields
2689 for (unsigned i = 0; i < 2; ++i) {
2690 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2691 SourceLocation(),
2692 SourceLocation(), 0,
2693 FieldTypes[i], 0,
2694 /*BitWidth=*/0,
2695 /*Mutable=*/false,
2696 /*HasInit=*/false));
2697 }
2698
2699 SuperStructDecl->completeDefinition();
2700 }
2701 return Context->getTagDeclType(SuperStructDecl);
2702}
2703
2704QualType RewriteModernObjC::getConstantStringStructType() {
2705 if (!ConstantStringDecl) {
2706 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2707 SourceLocation(), SourceLocation(),
2708 &Context->Idents.get("__NSConstantStringImpl"));
2709 QualType FieldTypes[4];
2710
2711 // struct objc_object *receiver;
2712 FieldTypes[0] = Context->getObjCIdType();
2713 // int flags;
2714 FieldTypes[1] = Context->IntTy;
2715 // char *str;
2716 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2717 // long length;
2718 FieldTypes[3] = Context->LongTy;
2719
2720 // Create fields
2721 for (unsigned i = 0; i < 4; ++i) {
2722 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2723 ConstantStringDecl,
2724 SourceLocation(),
2725 SourceLocation(), 0,
2726 FieldTypes[i], 0,
2727 /*BitWidth=*/0,
2728 /*Mutable=*/true,
2729 /*HasInit=*/false));
2730 }
2731
2732 ConstantStringDecl->completeDefinition();
2733 }
2734 return Context->getTagDeclType(ConstantStringDecl);
2735}
2736
2737Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2738 SourceLocation StartLoc,
2739 SourceLocation EndLoc) {
2740 if (!SelGetUidFunctionDecl)
2741 SynthSelGetUidFunctionDecl();
2742 if (!MsgSendFunctionDecl)
2743 SynthMsgSendFunctionDecl();
2744 if (!MsgSendSuperFunctionDecl)
2745 SynthMsgSendSuperFunctionDecl();
2746 if (!MsgSendStretFunctionDecl)
2747 SynthMsgSendStretFunctionDecl();
2748 if (!MsgSendSuperStretFunctionDecl)
2749 SynthMsgSendSuperStretFunctionDecl();
2750 if (!MsgSendFpretFunctionDecl)
2751 SynthMsgSendFpretFunctionDecl();
2752 if (!GetClassFunctionDecl)
2753 SynthGetClassFunctionDecl();
2754 if (!GetSuperClassFunctionDecl)
2755 SynthGetSuperClassFunctionDecl();
2756 if (!GetMetaClassFunctionDecl)
2757 SynthGetMetaClassFunctionDecl();
2758
2759 // default to objc_msgSend().
2760 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2761 // May need to use objc_msgSend_stret() as well.
2762 FunctionDecl *MsgSendStretFlavor = 0;
2763 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2764 QualType resultType = mDecl->getResultType();
2765 if (resultType->isRecordType())
2766 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2767 else if (resultType->isRealFloatingType())
2768 MsgSendFlavor = MsgSendFpretFunctionDecl;
2769 }
2770
2771 // Synthesize a call to objc_msgSend().
2772 SmallVector<Expr*, 8> MsgExprs;
2773 switch (Exp->getReceiverKind()) {
2774 case ObjCMessageExpr::SuperClass: {
2775 MsgSendFlavor = MsgSendSuperFunctionDecl;
2776 if (MsgSendStretFlavor)
2777 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2778 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2779
2780 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2781
2782 SmallVector<Expr*, 4> InitExprs;
2783
2784 // set the receiver to self, the first argument to all methods.
2785 InitExprs.push_back(
2786 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2787 CK_BitCast,
2788 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002789 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002790 Context->getObjCIdType(),
2791 VK_RValue,
2792 SourceLocation()))
2793 ); // set the 'receiver'.
2794
2795 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2796 SmallVector<Expr*, 8> ClsExprs;
2797 QualType argType = Context->getPointerType(Context->CharTy);
2798 ClsExprs.push_back(StringLiteral::Create(*Context,
2799 ClassDecl->getIdentifier()->getName(),
2800 StringLiteral::Ascii, false,
2801 argType, SourceLocation()));
2802 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2803 &ClsExprs[0],
2804 ClsExprs.size(),
2805 StartLoc,
2806 EndLoc);
2807 // (Class)objc_getClass("CurrentClass")
2808 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2809 Context->getObjCClassType(),
2810 CK_BitCast, Cls);
2811 ClsExprs.clear();
2812 ClsExprs.push_back(ArgExpr);
2813 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2814 &ClsExprs[0], ClsExprs.size(),
2815 StartLoc, EndLoc);
2816
2817 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2818 // To turn off a warning, type-cast to 'id'
2819 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2820 NoTypeInfoCStyleCastExpr(Context,
2821 Context->getObjCIdType(),
2822 CK_BitCast, Cls));
2823 // struct objc_super
2824 QualType superType = getSuperStructType();
2825 Expr *SuperRep;
2826
2827 if (LangOpts.MicrosoftExt) {
2828 SynthSuperContructorFunctionDecl();
2829 // Simulate a contructor call...
2830 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002831 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002832 SourceLocation());
2833 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2834 InitExprs.size(),
2835 superType, VK_LValue,
2836 SourceLocation());
2837 // The code for super is a little tricky to prevent collision with
2838 // the structure definition in the header. The rewriter has it's own
2839 // internal definition (__rw_objc_super) that is uses. This is why
2840 // we need the cast below. For example:
2841 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2842 //
2843 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2844 Context->getPointerType(SuperRep->getType()),
2845 VK_RValue, OK_Ordinary,
2846 SourceLocation());
2847 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2848 Context->getPointerType(superType),
2849 CK_BitCast, SuperRep);
2850 } else {
2851 // (struct objc_super) { <exprs from above> }
2852 InitListExpr *ILE =
2853 new (Context) InitListExpr(*Context, SourceLocation(),
2854 &InitExprs[0], InitExprs.size(),
2855 SourceLocation());
2856 TypeSourceInfo *superTInfo
2857 = Context->getTrivialTypeSourceInfo(superType);
2858 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2859 superType, VK_LValue,
2860 ILE, false);
2861 // struct objc_super *
2862 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2863 Context->getPointerType(SuperRep->getType()),
2864 VK_RValue, OK_Ordinary,
2865 SourceLocation());
2866 }
2867 MsgExprs.push_back(SuperRep);
2868 break;
2869 }
2870
2871 case ObjCMessageExpr::Class: {
2872 SmallVector<Expr*, 8> ClsExprs;
2873 QualType argType = Context->getPointerType(Context->CharTy);
2874 ObjCInterfaceDecl *Class
2875 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2876 IdentifierInfo *clsName = Class->getIdentifier();
2877 ClsExprs.push_back(StringLiteral::Create(*Context,
2878 clsName->getName(),
2879 StringLiteral::Ascii, false,
2880 argType, SourceLocation()));
2881 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2882 &ClsExprs[0],
2883 ClsExprs.size(),
2884 StartLoc, EndLoc);
2885 MsgExprs.push_back(Cls);
2886 break;
2887 }
2888
2889 case ObjCMessageExpr::SuperInstance:{
2890 MsgSendFlavor = MsgSendSuperFunctionDecl;
2891 if (MsgSendStretFlavor)
2892 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2893 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2894 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2895 SmallVector<Expr*, 4> InitExprs;
2896
2897 InitExprs.push_back(
2898 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2899 CK_BitCast,
2900 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002901 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002902 Context->getObjCIdType(),
2903 VK_RValue, SourceLocation()))
2904 ); // set the 'receiver'.
2905
2906 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2907 SmallVector<Expr*, 8> ClsExprs;
2908 QualType argType = Context->getPointerType(Context->CharTy);
2909 ClsExprs.push_back(StringLiteral::Create(*Context,
2910 ClassDecl->getIdentifier()->getName(),
2911 StringLiteral::Ascii, false, argType,
2912 SourceLocation()));
2913 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2914 &ClsExprs[0],
2915 ClsExprs.size(),
2916 StartLoc, EndLoc);
2917 // (Class)objc_getClass("CurrentClass")
2918 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2919 Context->getObjCClassType(),
2920 CK_BitCast, Cls);
2921 ClsExprs.clear();
2922 ClsExprs.push_back(ArgExpr);
2923 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2924 &ClsExprs[0], ClsExprs.size(),
2925 StartLoc, EndLoc);
2926
2927 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2928 // To turn off a warning, type-cast to 'id'
2929 InitExprs.push_back(
2930 // set 'super class', using class_getSuperclass().
2931 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2932 CK_BitCast, Cls));
2933 // struct objc_super
2934 QualType superType = getSuperStructType();
2935 Expr *SuperRep;
2936
2937 if (LangOpts.MicrosoftExt) {
2938 SynthSuperContructorFunctionDecl();
2939 // Simulate a contructor call...
2940 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002941 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002942 SourceLocation());
2943 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2944 InitExprs.size(),
2945 superType, VK_LValue, SourceLocation());
2946 // The code for super is a little tricky to prevent collision with
2947 // the structure definition in the header. The rewriter has it's own
2948 // internal definition (__rw_objc_super) that is uses. This is why
2949 // we need the cast below. For example:
2950 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2951 //
2952 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2953 Context->getPointerType(SuperRep->getType()),
2954 VK_RValue, OK_Ordinary,
2955 SourceLocation());
2956 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2957 Context->getPointerType(superType),
2958 CK_BitCast, SuperRep);
2959 } else {
2960 // (struct objc_super) { <exprs from above> }
2961 InitListExpr *ILE =
2962 new (Context) InitListExpr(*Context, SourceLocation(),
2963 &InitExprs[0], InitExprs.size(),
2964 SourceLocation());
2965 TypeSourceInfo *superTInfo
2966 = Context->getTrivialTypeSourceInfo(superType);
2967 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2968 superType, VK_RValue, ILE,
2969 false);
2970 }
2971 MsgExprs.push_back(SuperRep);
2972 break;
2973 }
2974
2975 case ObjCMessageExpr::Instance: {
2976 // Remove all type-casts because it may contain objc-style types; e.g.
2977 // Foo<Proto> *.
2978 Expr *recExpr = Exp->getInstanceReceiver();
2979 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2980 recExpr = CE->getSubExpr();
2981 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2982 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2983 ? CK_BlockPointerToObjCPointerCast
2984 : CK_CPointerToObjCPointerCast;
2985
2986 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2987 CK, recExpr);
2988 MsgExprs.push_back(recExpr);
2989 break;
2990 }
2991 }
2992
2993 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2994 SmallVector<Expr*, 8> SelExprs;
2995 QualType argType = Context->getPointerType(Context->CharTy);
2996 SelExprs.push_back(StringLiteral::Create(*Context,
2997 Exp->getSelector().getAsString(),
2998 StringLiteral::Ascii, false,
2999 argType, SourceLocation()));
3000 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3001 &SelExprs[0], SelExprs.size(),
3002 StartLoc,
3003 EndLoc);
3004 MsgExprs.push_back(SelExp);
3005
3006 // Now push any user supplied arguments.
3007 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3008 Expr *userExpr = Exp->getArg(i);
3009 // Make all implicit casts explicit...ICE comes in handy:-)
3010 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3011 // Reuse the ICE type, it is exactly what the doctor ordered.
3012 QualType type = ICE->getType();
3013 if (needToScanForQualifiers(type))
3014 type = Context->getObjCIdType();
3015 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3016 (void)convertBlockPointerToFunctionPointer(type);
3017 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3018 CastKind CK;
3019 if (SubExpr->getType()->isIntegralType(*Context) &&
3020 type->isBooleanType()) {
3021 CK = CK_IntegralToBoolean;
3022 } else if (type->isObjCObjectPointerType()) {
3023 if (SubExpr->getType()->isBlockPointerType()) {
3024 CK = CK_BlockPointerToObjCPointerCast;
3025 } else if (SubExpr->getType()->isPointerType()) {
3026 CK = CK_CPointerToObjCPointerCast;
3027 } else {
3028 CK = CK_BitCast;
3029 }
3030 } else {
3031 CK = CK_BitCast;
3032 }
3033
3034 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3035 }
3036 // Make id<P...> cast into an 'id' cast.
3037 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3038 if (CE->getType()->isObjCQualifiedIdType()) {
3039 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3040 userExpr = CE->getSubExpr();
3041 CastKind CK;
3042 if (userExpr->getType()->isIntegralType(*Context)) {
3043 CK = CK_IntegralToPointer;
3044 } else if (userExpr->getType()->isBlockPointerType()) {
3045 CK = CK_BlockPointerToObjCPointerCast;
3046 } else if (userExpr->getType()->isPointerType()) {
3047 CK = CK_CPointerToObjCPointerCast;
3048 } else {
3049 CK = CK_BitCast;
3050 }
3051 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3052 CK, userExpr);
3053 }
3054 }
3055 MsgExprs.push_back(userExpr);
3056 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3057 // out the argument in the original expression (since we aren't deleting
3058 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3059 //Exp->setArg(i, 0);
3060 }
3061 // Generate the funky cast.
3062 CastExpr *cast;
3063 SmallVector<QualType, 8> ArgTypes;
3064 QualType returnType;
3065
3066 // Push 'id' and 'SEL', the 2 implicit arguments.
3067 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3068 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3069 else
3070 ArgTypes.push_back(Context->getObjCIdType());
3071 ArgTypes.push_back(Context->getObjCSelType());
3072 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3073 // Push any user argument types.
3074 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3075 E = OMD->param_end(); PI != E; ++PI) {
3076 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3077 ? Context->getObjCIdType()
3078 : (*PI)->getType();
3079 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3080 (void)convertBlockPointerToFunctionPointer(t);
3081 ArgTypes.push_back(t);
3082 }
3083 returnType = Exp->getType();
3084 convertToUnqualifiedObjCType(returnType);
3085 (void)convertBlockPointerToFunctionPointer(returnType);
3086 } else {
3087 returnType = Context->getObjCIdType();
3088 }
3089 // Get the type, we will need to reference it in a couple spots.
3090 QualType msgSendType = MsgSendFlavor->getType();
3091
3092 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003093 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003094 VK_LValue, SourceLocation());
3095
3096 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3097 // If we don't do this cast, we get the following bizarre warning/note:
3098 // xx.m:13: warning: function called through a non-compatible type
3099 // xx.m:13: note: if this code is reached, the program will abort
3100 cast = NoTypeInfoCStyleCastExpr(Context,
3101 Context->getPointerType(Context->VoidTy),
3102 CK_BitCast, DRE);
3103
3104 // Now do the "normal" pointer to function cast.
3105 QualType castType =
3106 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3107 // If we don't have a method decl, force a variadic cast.
3108 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3109 castType = Context->getPointerType(castType);
3110 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3111 cast);
3112
3113 // Don't forget the parens to enforce the proper binding.
3114 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3115
3116 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3117 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3118 MsgExprs.size(),
3119 FT->getResultType(), VK_RValue,
3120 EndLoc);
3121 Stmt *ReplacingStmt = CE;
3122 if (MsgSendStretFlavor) {
3123 // We have the method which returns a struct/union. Must also generate
3124 // call to objc_msgSend_stret and hang both varieties on a conditional
3125 // expression which dictate which one to envoke depending on size of
3126 // method's return type.
3127
3128 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003129 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
3130 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003131 VK_LValue, SourceLocation());
3132 // Need to cast objc_msgSend_stret to "void *" (see above comment).
3133 cast = NoTypeInfoCStyleCastExpr(Context,
3134 Context->getPointerType(Context->VoidTy),
3135 CK_BitCast, STDRE);
3136 // Now do the "normal" pointer to function cast.
3137 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3138 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
3139 castType = Context->getPointerType(castType);
3140 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3141 cast);
3142
3143 // Don't forget the parens to enforce the proper binding.
3144 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
3145
3146 FT = msgSendType->getAs<FunctionType>();
3147 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
3148 MsgExprs.size(),
3149 FT->getResultType(), VK_RValue,
3150 SourceLocation());
3151
3152 // Build sizeof(returnType)
3153 UnaryExprOrTypeTraitExpr *sizeofExpr =
3154 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3155 Context->getTrivialTypeSourceInfo(returnType),
3156 Context->getSizeType(), SourceLocation(),
3157 SourceLocation());
3158 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3159 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3160 // For X86 it is more complicated and some kind of target specific routine
3161 // is needed to decide what to do.
3162 unsigned IntSize =
3163 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3164 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3165 llvm::APInt(IntSize, 8),
3166 Context->IntTy,
3167 SourceLocation());
3168 BinaryOperator *lessThanExpr =
3169 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3170 VK_RValue, OK_Ordinary, SourceLocation());
3171 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3172 ConditionalOperator *CondExpr =
3173 new (Context) ConditionalOperator(lessThanExpr,
3174 SourceLocation(), CE,
3175 SourceLocation(), STCE,
3176 returnType, VK_RValue, OK_Ordinary);
3177 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3178 CondExpr);
3179 }
3180 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3181 return ReplacingStmt;
3182}
3183
3184Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3185 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3186 Exp->getLocEnd());
3187
3188 // Now do the actual rewrite.
3189 ReplaceStmt(Exp, ReplacingStmt);
3190
3191 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3192 return ReplacingStmt;
3193}
3194
3195// typedef struct objc_object Protocol;
3196QualType RewriteModernObjC::getProtocolType() {
3197 if (!ProtocolTypeDecl) {
3198 TypeSourceInfo *TInfo
3199 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3200 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3201 SourceLocation(), SourceLocation(),
3202 &Context->Idents.get("Protocol"),
3203 TInfo);
3204 }
3205 return Context->getTypeDeclType(ProtocolTypeDecl);
3206}
3207
3208/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3209/// a synthesized/forward data reference (to the protocol's metadata).
3210/// The forward references (and metadata) are generated in
3211/// RewriteModernObjC::HandleTranslationUnit().
3212Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003213 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3214 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003215 IdentifierInfo *ID = &Context->Idents.get(Name);
3216 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3217 SourceLocation(), ID, getProtocolType(), 0,
3218 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003219 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3220 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003221 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3222 Context->getPointerType(DRE->getType()),
3223 VK_RValue, OK_Ordinary, SourceLocation());
3224 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3225 CK_BitCast,
3226 DerefExpr);
3227 ReplaceStmt(Exp, castExpr);
3228 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3229 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3230 return castExpr;
3231
3232}
3233
3234bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3235 const char *endBuf) {
3236 while (startBuf < endBuf) {
3237 if (*startBuf == '#') {
3238 // Skip whitespace.
3239 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3240 ;
3241 if (!strncmp(startBuf, "if", strlen("if")) ||
3242 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3243 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3244 !strncmp(startBuf, "define", strlen("define")) ||
3245 !strncmp(startBuf, "undef", strlen("undef")) ||
3246 !strncmp(startBuf, "else", strlen("else")) ||
3247 !strncmp(startBuf, "elif", strlen("elif")) ||
3248 !strncmp(startBuf, "endif", strlen("endif")) ||
3249 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3250 !strncmp(startBuf, "include", strlen("include")) ||
3251 !strncmp(startBuf, "import", strlen("import")) ||
3252 !strncmp(startBuf, "include_next", strlen("include_next")))
3253 return true;
3254 }
3255 startBuf++;
3256 }
3257 return false;
3258}
3259
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003260/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003261/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003262bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3263 std::string &Result) {
3264 if (Type->isArrayType()) {
3265 QualType ElemTy = Context->getBaseElementType(Type);
3266 return RewriteObjCFieldDeclType(ElemTy, Result);
3267 }
3268 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003269 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3270 if (RD->isCompleteDefinition()) {
3271 if (RD->isStruct())
3272 Result += "\n\tstruct ";
3273 else if (RD->isUnion())
3274 Result += "\n\tunion ";
3275 else
3276 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003277
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003278 Result += RD->getName();
3279 if (TagsDefinedInIvarDecls.count(RD)) {
3280 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003281 Result += " ";
3282 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003283 }
3284 TagsDefinedInIvarDecls.insert(RD);
3285 Result += " {\n";
3286 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003287 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003288 FieldDecl *FD = *i;
3289 RewriteObjCFieldDecl(FD, Result);
3290 }
3291 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003292 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003293 }
3294 }
3295 else if (Type->isEnumeralType()) {
3296 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3297 if (ED->isCompleteDefinition()) {
3298 Result += "\n\tenum ";
3299 Result += ED->getName();
3300 if (TagsDefinedInIvarDecls.count(ED)) {
3301 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003302 Result += " ";
3303 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003304 }
3305 TagsDefinedInIvarDecls.insert(ED);
3306
3307 Result += " {\n";
3308 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3309 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3310 Result += "\t"; Result += EC->getName(); Result += " = ";
3311 llvm::APSInt Val = EC->getInitVal();
3312 Result += Val.toString(10);
3313 Result += ",\n";
3314 }
3315 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003316 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003317 }
3318 }
3319
3320 Result += "\t";
3321 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003322 return false;
3323}
3324
3325
3326/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3327/// It handles elaborated types, as well as enum types in the process.
3328void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3329 std::string &Result) {
3330 QualType Type = fieldDecl->getType();
3331 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003332
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003333 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3334 if (!EleboratedType)
3335 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003336 Result += Name;
3337 if (fieldDecl->isBitField()) {
3338 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3339 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003340 else if (EleboratedType && Type->isArrayType()) {
3341 CanQualType CType = Context->getCanonicalType(Type);
3342 while (isa<ArrayType>(CType)) {
3343 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3344 Result += "[";
3345 llvm::APInt Dim = CAT->getSize();
3346 Result += utostr(Dim.getZExtValue());
3347 Result += "]";
3348 }
3349 CType = CType->getAs<ArrayType>()->getElementType();
3350 }
3351 }
3352
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003353 Result += ";\n";
3354}
3355
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003356/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3357/// an objective-c class with ivars.
3358void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3359 std::string &Result) {
3360 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3361 assert(CDecl->getName() != "" &&
3362 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003363 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003364 SmallVector<ObjCIvarDecl *, 8> IVars;
3365 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003366 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003367 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003368
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003369 SourceLocation LocStart = CDecl->getLocStart();
3370 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003371
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003372 const char *startBuf = SM->getCharacterData(LocStart);
3373 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003374
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003375 // If no ivars and no root or if its root, directly or indirectly,
3376 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003377 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003378 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3379 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3380 ReplaceText(LocStart, endBuf-startBuf, Result);
3381 return;
3382 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003383
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003384 Result += "\nstruct ";
3385 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003386 Result += "_IMPL {\n";
3387
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003388 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003389 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3390 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3391 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003392 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003393 TagsDefinedInIvarDecls.clear();
3394 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3395 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003396
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003397 Result += "};\n";
3398 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3399 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003400 // Mark this struct as having been generated.
3401 if (!ObjCSynthesizedStructs.insert(CDecl))
3402 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003403}
3404
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003405static void WriteInternalIvarName(ObjCInterfaceDecl *IDecl,
3406 ObjCIvarDecl *IvarDecl, std::string &Result) {
3407 Result += "OBJC_IVAR_$_";
3408 Result += IDecl->getName();
3409 Result += "$";
3410 Result += IvarDecl->getName();
3411}
3412
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003413/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3414/// have been referenced in an ivar access expression.
3415void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3416 std::string &Result) {
3417 // write out ivar offset symbols which have been referenced in an ivar
3418 // access expression.
3419 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3420 if (Ivars.empty())
3421 return;
3422 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3423 e = Ivars.end(); i != e; i++) {
3424 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003425 Result += "\n";
3426 if (LangOpts.MicrosoftExt)
3427 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003428 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003429 if (LangOpts.MicrosoftExt &&
3430 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00003431 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
3432 Result += "__declspec(dllimport) ";
3433
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00003434 Result += "unsigned long ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00003435 WriteInternalIvarName(CDecl, IvarDecl, Result);
3436 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003437 }
3438}
3439
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003440//===----------------------------------------------------------------------===//
3441// Meta Data Emission
3442//===----------------------------------------------------------------------===//
3443
3444
3445/// RewriteImplementations - This routine rewrites all method implementations
3446/// and emits meta-data.
3447
3448void RewriteModernObjC::RewriteImplementations() {
3449 int ClsDefCount = ClassImplementation.size();
3450 int CatDefCount = CategoryImplementation.size();
3451
3452 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003453 for (int i = 0; i < ClsDefCount; i++) {
3454 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3455 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3456 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003457 assert(false &&
3458 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003459 RewriteImplementationDecl(OIMP);
3460 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003461
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003462 for (int i = 0; i < CatDefCount; i++) {
3463 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3464 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3465 if (CDecl->isImplicitInterfaceDecl())
3466 assert(false &&
3467 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003468 RewriteImplementationDecl(CIMP);
3469 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003470}
3471
3472void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3473 const std::string &Name,
3474 ValueDecl *VD, bool def) {
3475 assert(BlockByRefDeclNo.count(VD) &&
3476 "RewriteByRefString: ByRef decl missing");
3477 if (def)
3478 ResultStr += "struct ";
3479 ResultStr += "__Block_byref_" + Name +
3480 "_" + utostr(BlockByRefDeclNo[VD]) ;
3481}
3482
3483static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3484 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3485 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3486 return false;
3487}
3488
3489std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3490 StringRef funcName,
3491 std::string Tag) {
3492 const FunctionType *AFT = CE->getFunctionType();
3493 QualType RT = AFT->getResultType();
3494 std::string StructRef = "struct " + Tag;
3495 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003496 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003497
3498 BlockDecl *BD = CE->getBlockDecl();
3499
3500 if (isa<FunctionNoProtoType>(AFT)) {
3501 // No user-supplied arguments. Still need to pass in a pointer to the
3502 // block (to reference imported block decl refs).
3503 S += "(" + StructRef + " *__cself)";
3504 } else if (BD->param_empty()) {
3505 S += "(" + StructRef + " *__cself)";
3506 } else {
3507 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3508 assert(FT && "SynthesizeBlockFunc: No function proto");
3509 S += '(';
3510 // first add the implicit argument.
3511 S += StructRef + " *__cself, ";
3512 std::string ParamStr;
3513 for (BlockDecl::param_iterator AI = BD->param_begin(),
3514 E = BD->param_end(); AI != E; ++AI) {
3515 if (AI != BD->param_begin()) S += ", ";
3516 ParamStr = (*AI)->getNameAsString();
3517 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00003518 (void)convertBlockPointerToFunctionPointer(QT);
3519 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003520 S += ParamStr;
3521 }
3522 if (FT->isVariadic()) {
3523 if (!BD->param_empty()) S += ", ";
3524 S += "...";
3525 }
3526 S += ')';
3527 }
3528 S += " {\n";
3529
3530 // Create local declarations to avoid rewriting all closure decl ref exprs.
3531 // First, emit a declaration for all "by ref" decls.
3532 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3533 E = BlockByRefDecls.end(); I != E; ++I) {
3534 S += " ";
3535 std::string Name = (*I)->getNameAsString();
3536 std::string TypeString;
3537 RewriteByRefString(TypeString, Name, (*I));
3538 TypeString += " *";
3539 Name = TypeString + Name;
3540 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3541 }
3542 // Next, emit a declaration for all "by copy" declarations.
3543 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3544 E = BlockByCopyDecls.end(); I != E; ++I) {
3545 S += " ";
3546 // Handle nested closure invocation. For example:
3547 //
3548 // void (^myImportedClosure)(void);
3549 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3550 //
3551 // void (^anotherClosure)(void);
3552 // anotherClosure = ^(void) {
3553 // myImportedClosure(); // import and invoke the closure
3554 // };
3555 //
3556 if (isTopLevelBlockPointerType((*I)->getType())) {
3557 RewriteBlockPointerTypeVariable(S, (*I));
3558 S += " = (";
3559 RewriteBlockPointerType(S, (*I)->getType());
3560 S += ")";
3561 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3562 }
3563 else {
3564 std::string Name = (*I)->getNameAsString();
3565 QualType QT = (*I)->getType();
3566 if (HasLocalVariableExternalStorage(*I))
3567 QT = Context->getPointerType(QT);
3568 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3569 S += Name + " = __cself->" +
3570 (*I)->getNameAsString() + "; // bound by copy\n";
3571 }
3572 }
3573 std::string RewrittenStr = RewrittenBlockExprs[CE];
3574 const char *cstr = RewrittenStr.c_str();
3575 while (*cstr++ != '{') ;
3576 S += cstr;
3577 S += "\n";
3578 return S;
3579}
3580
3581std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3582 StringRef funcName,
3583 std::string Tag) {
3584 std::string StructRef = "struct " + Tag;
3585 std::string S = "static void __";
3586
3587 S += funcName;
3588 S += "_block_copy_" + utostr(i);
3589 S += "(" + StructRef;
3590 S += "*dst, " + StructRef;
3591 S += "*src) {";
3592 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3593 E = ImportedBlockDecls.end(); I != E; ++I) {
3594 ValueDecl *VD = (*I);
3595 S += "_Block_object_assign((void*)&dst->";
3596 S += (*I)->getNameAsString();
3597 S += ", (void*)src->";
3598 S += (*I)->getNameAsString();
3599 if (BlockByRefDeclsPtrSet.count((*I)))
3600 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3601 else if (VD->getType()->isBlockPointerType())
3602 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3603 else
3604 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3605 }
3606 S += "}\n";
3607
3608 S += "\nstatic void __";
3609 S += funcName;
3610 S += "_block_dispose_" + utostr(i);
3611 S += "(" + StructRef;
3612 S += "*src) {";
3613 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3614 E = ImportedBlockDecls.end(); I != E; ++I) {
3615 ValueDecl *VD = (*I);
3616 S += "_Block_object_dispose((void*)src->";
3617 S += (*I)->getNameAsString();
3618 if (BlockByRefDeclsPtrSet.count((*I)))
3619 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3620 else if (VD->getType()->isBlockPointerType())
3621 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3622 else
3623 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3624 }
3625 S += "}\n";
3626 return S;
3627}
3628
3629std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3630 std::string Desc) {
3631 std::string S = "\nstruct " + Tag;
3632 std::string Constructor = " " + Tag;
3633
3634 S += " {\n struct __block_impl impl;\n";
3635 S += " struct " + Desc;
3636 S += "* Desc;\n";
3637
3638 Constructor += "(void *fp, "; // Invoke function pointer.
3639 Constructor += "struct " + Desc; // Descriptor pointer.
3640 Constructor += " *desc";
3641
3642 if (BlockDeclRefs.size()) {
3643 // Output all "by copy" declarations.
3644 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3645 E = BlockByCopyDecls.end(); I != E; ++I) {
3646 S += " ";
3647 std::string FieldName = (*I)->getNameAsString();
3648 std::string ArgName = "_" + FieldName;
3649 // Handle nested closure invocation. For example:
3650 //
3651 // void (^myImportedBlock)(void);
3652 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3653 //
3654 // void (^anotherBlock)(void);
3655 // anotherBlock = ^(void) {
3656 // myImportedBlock(); // import and invoke the closure
3657 // };
3658 //
3659 if (isTopLevelBlockPointerType((*I)->getType())) {
3660 S += "struct __block_impl *";
3661 Constructor += ", void *" + ArgName;
3662 } else {
3663 QualType QT = (*I)->getType();
3664 if (HasLocalVariableExternalStorage(*I))
3665 QT = Context->getPointerType(QT);
3666 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3667 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3668 Constructor += ", " + ArgName;
3669 }
3670 S += FieldName + ";\n";
3671 }
3672 // Output all "by ref" declarations.
3673 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3674 E = BlockByRefDecls.end(); I != E; ++I) {
3675 S += " ";
3676 std::string FieldName = (*I)->getNameAsString();
3677 std::string ArgName = "_" + FieldName;
3678 {
3679 std::string TypeString;
3680 RewriteByRefString(TypeString, FieldName, (*I));
3681 TypeString += " *";
3682 FieldName = TypeString + FieldName;
3683 ArgName = TypeString + ArgName;
3684 Constructor += ", " + ArgName;
3685 }
3686 S += FieldName + "; // by ref\n";
3687 }
3688 // Finish writing the constructor.
3689 Constructor += ", int flags=0)";
3690 // Initialize all "by copy" arguments.
3691 bool firsTime = true;
3692 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3693 E = BlockByCopyDecls.end(); I != E; ++I) {
3694 std::string Name = (*I)->getNameAsString();
3695 if (firsTime) {
3696 Constructor += " : ";
3697 firsTime = false;
3698 }
3699 else
3700 Constructor += ", ";
3701 if (isTopLevelBlockPointerType((*I)->getType()))
3702 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3703 else
3704 Constructor += Name + "(_" + Name + ")";
3705 }
3706 // Initialize all "by ref" arguments.
3707 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3708 E = BlockByRefDecls.end(); I != E; ++I) {
3709 std::string Name = (*I)->getNameAsString();
3710 if (firsTime) {
3711 Constructor += " : ";
3712 firsTime = false;
3713 }
3714 else
3715 Constructor += ", ";
3716 Constructor += Name + "(_" + Name + "->__forwarding)";
3717 }
3718
3719 Constructor += " {\n";
3720 if (GlobalVarDecl)
3721 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3722 else
3723 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3724 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3725
3726 Constructor += " Desc = desc;\n";
3727 } else {
3728 // Finish writing the constructor.
3729 Constructor += ", int flags=0) {\n";
3730 if (GlobalVarDecl)
3731 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3732 else
3733 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3734 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3735 Constructor += " Desc = desc;\n";
3736 }
3737 Constructor += " ";
3738 Constructor += "}\n";
3739 S += Constructor;
3740 S += "};\n";
3741 return S;
3742}
3743
3744std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3745 std::string ImplTag, int i,
3746 StringRef FunName,
3747 unsigned hasCopy) {
3748 std::string S = "\nstatic struct " + DescTag;
3749
3750 S += " {\n unsigned long reserved;\n";
3751 S += " unsigned long Block_size;\n";
3752 if (hasCopy) {
3753 S += " void (*copy)(struct ";
3754 S += ImplTag; S += "*, struct ";
3755 S += ImplTag; S += "*);\n";
3756
3757 S += " void (*dispose)(struct ";
3758 S += ImplTag; S += "*);\n";
3759 }
3760 S += "} ";
3761
3762 S += DescTag + "_DATA = { 0, sizeof(struct ";
3763 S += ImplTag + ")";
3764 if (hasCopy) {
3765 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3766 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3767 }
3768 S += "};\n";
3769 return S;
3770}
3771
3772void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3773 StringRef FunName) {
3774 // Insert declaration for the function in which block literal is used.
3775 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3776 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3777 bool RewriteSC = (GlobalVarDecl &&
3778 !Blocks.empty() &&
3779 GlobalVarDecl->getStorageClass() == SC_Static &&
3780 GlobalVarDecl->getType().getCVRQualifiers());
3781 if (RewriteSC) {
3782 std::string SC(" void __");
3783 SC += GlobalVarDecl->getNameAsString();
3784 SC += "() {}";
3785 InsertText(FunLocStart, SC);
3786 }
3787
3788 // Insert closures that were part of the function.
3789 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3790 CollectBlockDeclRefInfo(Blocks[i]);
3791 // Need to copy-in the inner copied-in variables not actually used in this
3792 // block.
3793 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003794 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003795 ValueDecl *VD = Exp->getDecl();
3796 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003797 if (!VD->hasAttr<BlocksAttr>()) {
3798 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3799 BlockByCopyDeclsPtrSet.insert(VD);
3800 BlockByCopyDecls.push_back(VD);
3801 }
3802 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003803 }
John McCallf4b88a42012-03-10 09:33:50 +00003804
3805 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003806 BlockByRefDeclsPtrSet.insert(VD);
3807 BlockByRefDecls.push_back(VD);
3808 }
John McCallf4b88a42012-03-10 09:33:50 +00003809
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003810 // imported objects in the inner blocks not used in the outer
3811 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003812 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003813 VD->getType()->isBlockPointerType())
3814 ImportedBlockDecls.insert(VD);
3815 }
3816
3817 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3818 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3819
3820 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3821
3822 InsertText(FunLocStart, CI);
3823
3824 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3825
3826 InsertText(FunLocStart, CF);
3827
3828 if (ImportedBlockDecls.size()) {
3829 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3830 InsertText(FunLocStart, HF);
3831 }
3832 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3833 ImportedBlockDecls.size() > 0);
3834 InsertText(FunLocStart, BD);
3835
3836 BlockDeclRefs.clear();
3837 BlockByRefDecls.clear();
3838 BlockByRefDeclsPtrSet.clear();
3839 BlockByCopyDecls.clear();
3840 BlockByCopyDeclsPtrSet.clear();
3841 ImportedBlockDecls.clear();
3842 }
3843 if (RewriteSC) {
3844 // Must insert any 'const/volatile/static here. Since it has been
3845 // removed as result of rewriting of block literals.
3846 std::string SC;
3847 if (GlobalVarDecl->getStorageClass() == SC_Static)
3848 SC = "static ";
3849 if (GlobalVarDecl->getType().isConstQualified())
3850 SC += "const ";
3851 if (GlobalVarDecl->getType().isVolatileQualified())
3852 SC += "volatile ";
3853 if (GlobalVarDecl->getType().isRestrictQualified())
3854 SC += "restrict ";
3855 InsertText(FunLocStart, SC);
3856 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003857 if (GlobalConstructionExp) {
3858 // extra fancy dance for global literal expression.
3859
3860 // Always the latest block expression on the block stack.
3861 std::string Tag = "__";
3862 Tag += FunName;
3863 Tag += "_block_impl_";
3864 Tag += utostr(Blocks.size()-1);
3865 std::string globalBuf = "static ";
3866 globalBuf += Tag; globalBuf += " ";
3867 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003868
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00003869 llvm::raw_string_ostream constructorExprBuf(SStr);
3870 GlobalConstructionExp->printPretty(constructorExprBuf, *Context, 0,
3871 PrintingPolicy(LangOpts));
3872 globalBuf += constructorExprBuf.str();
3873 globalBuf += ";\n";
3874 InsertText(FunLocStart, globalBuf);
3875 GlobalConstructionExp = 0;
3876 }
3877
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003878 Blocks.clear();
3879 InnerDeclRefsCount.clear();
3880 InnerDeclRefs.clear();
3881 RewrittenBlockExprs.clear();
3882}
3883
3884void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3885 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3886 StringRef FuncName = FD->getName();
3887
3888 SynthesizeBlockLiterals(FunLocStart, FuncName);
3889}
3890
3891static void BuildUniqueMethodName(std::string &Name,
3892 ObjCMethodDecl *MD) {
3893 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3894 Name = IFace->getName();
3895 Name += "__" + MD->getSelector().getAsString();
3896 // Convert colons to underscores.
3897 std::string::size_type loc = 0;
3898 while ((loc = Name.find(":", loc)) != std::string::npos)
3899 Name.replace(loc, 1, "_");
3900}
3901
3902void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3903 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3904 //SourceLocation FunLocStart = MD->getLocStart();
3905 SourceLocation FunLocStart = MD->getLocStart();
3906 std::string FuncName;
3907 BuildUniqueMethodName(FuncName, MD);
3908 SynthesizeBlockLiterals(FunLocStart, FuncName);
3909}
3910
3911void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3912 for (Stmt::child_range CI = S->children(); CI; ++CI)
3913 if (*CI) {
3914 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3915 GetBlockDeclRefExprs(CBE->getBody());
3916 else
3917 GetBlockDeclRefExprs(*CI);
3918 }
3919 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003920 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3921 if (DRE->refersToEnclosingLocal() &&
3922 HasLocalVariableExternalStorage(DRE->getDecl())) {
3923 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003924 }
3925
3926 return;
3927}
3928
3929void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003930 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003931 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3932 for (Stmt::child_range CI = S->children(); CI; ++CI)
3933 if (*CI) {
3934 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3935 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3936 GetInnerBlockDeclRefExprs(CBE->getBody(),
3937 InnerBlockDeclRefs,
3938 InnerContexts);
3939 }
3940 else
3941 GetInnerBlockDeclRefExprs(*CI,
3942 InnerBlockDeclRefs,
3943 InnerContexts);
3944
3945 }
3946 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003947 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3948 if (DRE->refersToEnclosingLocal()) {
3949 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3950 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3951 InnerBlockDeclRefs.push_back(DRE);
3952 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3953 if (Var->isFunctionOrMethodVarDecl())
3954 ImportedLocalExternalDecls.insert(Var);
3955 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003956 }
3957
3958 return;
3959}
3960
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003961/// convertObjCTypeToCStyleType - This routine converts such objc types
3962/// as qualified objects, and blocks to their closest c/c++ types that
3963/// it can. It returns true if input type was modified.
3964bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3965 QualType oldT = T;
3966 convertBlockPointerToFunctionPointer(T);
3967 if (T->isFunctionPointerType()) {
3968 QualType PointeeTy;
3969 if (const PointerType* PT = T->getAs<PointerType>()) {
3970 PointeeTy = PT->getPointeeType();
3971 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3972 T = convertFunctionTypeOfBlocks(FT);
3973 T = Context->getPointerType(T);
3974 }
3975 }
3976 }
3977
3978 convertToUnqualifiedObjCType(T);
3979 return T != oldT;
3980}
3981
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003982/// convertFunctionTypeOfBlocks - This routine converts a function type
3983/// whose result type may be a block pointer or whose argument type(s)
3984/// might be block pointers to an equivalent function type replacing
3985/// all block pointers to function pointers.
3986QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3987 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3988 // FTP will be null for closures that don't take arguments.
3989 // Generate a funky cast.
3990 SmallVector<QualType, 8> ArgTypes;
3991 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003992 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003993
3994 if (FTP) {
3995 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3996 E = FTP->arg_type_end(); I && (I != E); ++I) {
3997 QualType t = *I;
3998 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003999 if (convertObjCTypeToCStyleType(t))
4000 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004001 ArgTypes.push_back(t);
4002 }
4003 }
4004 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004005 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004006 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4007 else FuncType = QualType(FT, 0);
4008 return FuncType;
4009}
4010
4011Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4012 // Navigate to relevant type information.
4013 const BlockPointerType *CPT = 0;
4014
4015 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4016 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004017 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4018 CPT = MExpr->getType()->getAs<BlockPointerType>();
4019 }
4020 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4021 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4022 }
4023 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4024 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4025 else if (const ConditionalOperator *CEXPR =
4026 dyn_cast<ConditionalOperator>(BlockExp)) {
4027 Expr *LHSExp = CEXPR->getLHS();
4028 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4029 Expr *RHSExp = CEXPR->getRHS();
4030 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4031 Expr *CONDExp = CEXPR->getCond();
4032 ConditionalOperator *CondExpr =
4033 new (Context) ConditionalOperator(CONDExp,
4034 SourceLocation(), cast<Expr>(LHSStmt),
4035 SourceLocation(), cast<Expr>(RHSStmt),
4036 Exp->getType(), VK_RValue, OK_Ordinary);
4037 return CondExpr;
4038 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4039 CPT = IRE->getType()->getAs<BlockPointerType>();
4040 } else if (const PseudoObjectExpr *POE
4041 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4042 CPT = POE->getType()->castAs<BlockPointerType>();
4043 } else {
4044 assert(1 && "RewriteBlockClass: Bad type");
4045 }
4046 assert(CPT && "RewriteBlockClass: Bad type");
4047 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4048 assert(FT && "RewriteBlockClass: Bad type");
4049 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4050 // FTP will be null for closures that don't take arguments.
4051
4052 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4053 SourceLocation(), SourceLocation(),
4054 &Context->Idents.get("__block_impl"));
4055 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4056
4057 // Generate a funky cast.
4058 SmallVector<QualType, 8> ArgTypes;
4059
4060 // Push the block argument type.
4061 ArgTypes.push_back(PtrBlock);
4062 if (FTP) {
4063 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4064 E = FTP->arg_type_end(); I && (I != E); ++I) {
4065 QualType t = *I;
4066 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4067 if (!convertBlockPointerToFunctionPointer(t))
4068 convertToUnqualifiedObjCType(t);
4069 ArgTypes.push_back(t);
4070 }
4071 }
4072 // Now do the pointer to function cast.
4073 QualType PtrToFuncCastType
4074 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4075
4076 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4077
4078 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4079 CK_BitCast,
4080 const_cast<Expr*>(BlockExp));
4081 // Don't forget the parens to enforce the proper binding.
4082 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4083 BlkCast);
4084 //PE->dump();
4085
4086 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4087 SourceLocation(),
4088 &Context->Idents.get("FuncPtr"),
4089 Context->VoidPtrTy, 0,
4090 /*BitWidth=*/0, /*Mutable=*/true,
4091 /*HasInit=*/false);
4092 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4093 FD->getType(), VK_LValue,
4094 OK_Ordinary);
4095
4096
4097 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4098 CK_BitCast, ME);
4099 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4100
4101 SmallVector<Expr*, 8> BlkExprs;
4102 // Add the implicit argument.
4103 BlkExprs.push_back(BlkCast);
4104 // Add the user arguments.
4105 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4106 E = Exp->arg_end(); I != E; ++I) {
4107 BlkExprs.push_back(*I);
4108 }
4109 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
4110 BlkExprs.size(),
4111 Exp->getType(), VK_RValue,
4112 SourceLocation());
4113 return CE;
4114}
4115
4116// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004117// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004118// For example:
4119//
4120// int main() {
4121// __block Foo *f;
4122// __block int i;
4123//
4124// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004125// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004126// i = 77;
4127// };
4128//}
John McCallf4b88a42012-03-10 09:33:50 +00004129Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004130 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4131 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004132 ValueDecl *VD = DeclRefExp->getDecl();
4133 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004134
4135 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4136 SourceLocation(),
4137 &Context->Idents.get("__forwarding"),
4138 Context->VoidPtrTy, 0,
4139 /*BitWidth=*/0, /*Mutable=*/true,
4140 /*HasInit=*/false);
4141 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4142 FD, SourceLocation(),
4143 FD->getType(), VK_LValue,
4144 OK_Ordinary);
4145
4146 StringRef Name = VD->getName();
4147 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4148 &Context->Idents.get(Name),
4149 Context->VoidPtrTy, 0,
4150 /*BitWidth=*/0, /*Mutable=*/true,
4151 /*HasInit=*/false);
4152 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4153 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4154
4155
4156
4157 // Need parens to enforce precedence.
4158 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4159 DeclRefExp->getExprLoc(),
4160 ME);
4161 ReplaceStmt(DeclRefExp, PE);
4162 return PE;
4163}
4164
4165// Rewrites the imported local variable V with external storage
4166// (static, extern, etc.) as *V
4167//
4168Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4169 ValueDecl *VD = DRE->getDecl();
4170 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4171 if (!ImportedLocalExternalDecls.count(Var))
4172 return DRE;
4173 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4174 VK_LValue, OK_Ordinary,
4175 DRE->getLocation());
4176 // Need parens to enforce precedence.
4177 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4178 Exp);
4179 ReplaceStmt(DRE, PE);
4180 return PE;
4181}
4182
4183void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4184 SourceLocation LocStart = CE->getLParenLoc();
4185 SourceLocation LocEnd = CE->getRParenLoc();
4186
4187 // Need to avoid trying to rewrite synthesized casts.
4188 if (LocStart.isInvalid())
4189 return;
4190 // Need to avoid trying to rewrite casts contained in macros.
4191 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4192 return;
4193
4194 const char *startBuf = SM->getCharacterData(LocStart);
4195 const char *endBuf = SM->getCharacterData(LocEnd);
4196 QualType QT = CE->getType();
4197 const Type* TypePtr = QT->getAs<Type>();
4198 if (isa<TypeOfExprType>(TypePtr)) {
4199 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4200 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4201 std::string TypeAsString = "(";
4202 RewriteBlockPointerType(TypeAsString, QT);
4203 TypeAsString += ")";
4204 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4205 return;
4206 }
4207 // advance the location to startArgList.
4208 const char *argPtr = startBuf;
4209
4210 while (*argPtr++ && (argPtr < endBuf)) {
4211 switch (*argPtr) {
4212 case '^':
4213 // Replace the '^' with '*'.
4214 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4215 ReplaceText(LocStart, 1, "*");
4216 break;
4217 }
4218 }
4219 return;
4220}
4221
4222void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4223 SourceLocation DeclLoc = FD->getLocation();
4224 unsigned parenCount = 0;
4225
4226 // We have 1 or more arguments that have closure pointers.
4227 const char *startBuf = SM->getCharacterData(DeclLoc);
4228 const char *startArgList = strchr(startBuf, '(');
4229
4230 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4231
4232 parenCount++;
4233 // advance the location to startArgList.
4234 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4235 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4236
4237 const char *argPtr = startArgList;
4238
4239 while (*argPtr++ && parenCount) {
4240 switch (*argPtr) {
4241 case '^':
4242 // Replace the '^' with '*'.
4243 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4244 ReplaceText(DeclLoc, 1, "*");
4245 break;
4246 case '(':
4247 parenCount++;
4248 break;
4249 case ')':
4250 parenCount--;
4251 break;
4252 }
4253 }
4254 return;
4255}
4256
4257bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4258 const FunctionProtoType *FTP;
4259 const PointerType *PT = QT->getAs<PointerType>();
4260 if (PT) {
4261 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4262 } else {
4263 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4264 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4265 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4266 }
4267 if (FTP) {
4268 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4269 E = FTP->arg_type_end(); I != E; ++I)
4270 if (isTopLevelBlockPointerType(*I))
4271 return true;
4272 }
4273 return false;
4274}
4275
4276bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4277 const FunctionProtoType *FTP;
4278 const PointerType *PT = QT->getAs<PointerType>();
4279 if (PT) {
4280 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4281 } else {
4282 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4283 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4284 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4285 }
4286 if (FTP) {
4287 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4288 E = FTP->arg_type_end(); I != E; ++I) {
4289 if ((*I)->isObjCQualifiedIdType())
4290 return true;
4291 if ((*I)->isObjCObjectPointerType() &&
4292 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4293 return true;
4294 }
4295
4296 }
4297 return false;
4298}
4299
4300void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4301 const char *&RParen) {
4302 const char *argPtr = strchr(Name, '(');
4303 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4304
4305 LParen = argPtr; // output the start.
4306 argPtr++; // skip past the left paren.
4307 unsigned parenCount = 1;
4308
4309 while (*argPtr && parenCount) {
4310 switch (*argPtr) {
4311 case '(': parenCount++; break;
4312 case ')': parenCount--; break;
4313 default: break;
4314 }
4315 if (parenCount) argPtr++;
4316 }
4317 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4318 RParen = argPtr; // output the end
4319}
4320
4321void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4322 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4323 RewriteBlockPointerFunctionArgs(FD);
4324 return;
4325 }
4326 // Handle Variables and Typedefs.
4327 SourceLocation DeclLoc = ND->getLocation();
4328 QualType DeclT;
4329 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4330 DeclT = VD->getType();
4331 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4332 DeclT = TDD->getUnderlyingType();
4333 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4334 DeclT = FD->getType();
4335 else
4336 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4337
4338 const char *startBuf = SM->getCharacterData(DeclLoc);
4339 const char *endBuf = startBuf;
4340 // scan backward (from the decl location) for the end of the previous decl.
4341 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4342 startBuf--;
4343 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4344 std::string buf;
4345 unsigned OrigLength=0;
4346 // *startBuf != '^' if we are dealing with a pointer to function that
4347 // may take block argument types (which will be handled below).
4348 if (*startBuf == '^') {
4349 // Replace the '^' with '*', computing a negative offset.
4350 buf = '*';
4351 startBuf++;
4352 OrigLength++;
4353 }
4354 while (*startBuf != ')') {
4355 buf += *startBuf;
4356 startBuf++;
4357 OrigLength++;
4358 }
4359 buf += ')';
4360 OrigLength++;
4361
4362 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4363 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4364 // Replace the '^' with '*' for arguments.
4365 // Replace id<P> with id/*<>*/
4366 DeclLoc = ND->getLocation();
4367 startBuf = SM->getCharacterData(DeclLoc);
4368 const char *argListBegin, *argListEnd;
4369 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4370 while (argListBegin < argListEnd) {
4371 if (*argListBegin == '^')
4372 buf += '*';
4373 else if (*argListBegin == '<') {
4374 buf += "/*";
4375 buf += *argListBegin++;
4376 OrigLength++;;
4377 while (*argListBegin != '>') {
4378 buf += *argListBegin++;
4379 OrigLength++;
4380 }
4381 buf += *argListBegin;
4382 buf += "*/";
4383 }
4384 else
4385 buf += *argListBegin;
4386 argListBegin++;
4387 OrigLength++;
4388 }
4389 buf += ')';
4390 OrigLength++;
4391 }
4392 ReplaceText(Start, OrigLength, buf);
4393
4394 return;
4395}
4396
4397
4398/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4399/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4400/// struct Block_byref_id_object *src) {
4401/// _Block_object_assign (&_dest->object, _src->object,
4402/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4403/// [|BLOCK_FIELD_IS_WEAK]) // object
4404/// _Block_object_assign(&_dest->object, _src->object,
4405/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4406/// [|BLOCK_FIELD_IS_WEAK]) // block
4407/// }
4408/// And:
4409/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4410/// _Block_object_dispose(_src->object,
4411/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4412/// [|BLOCK_FIELD_IS_WEAK]) // object
4413/// _Block_object_dispose(_src->object,
4414/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4415/// [|BLOCK_FIELD_IS_WEAK]) // block
4416/// }
4417
4418std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4419 int flag) {
4420 std::string S;
4421 if (CopyDestroyCache.count(flag))
4422 return S;
4423 CopyDestroyCache.insert(flag);
4424 S = "static void __Block_byref_id_object_copy_";
4425 S += utostr(flag);
4426 S += "(void *dst, void *src) {\n";
4427
4428 // offset into the object pointer is computed as:
4429 // void * + void* + int + int + void* + void *
4430 unsigned IntSize =
4431 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4432 unsigned VoidPtrSize =
4433 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4434
4435 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4436 S += " _Block_object_assign((char*)dst + ";
4437 S += utostr(offset);
4438 S += ", *(void * *) ((char*)src + ";
4439 S += utostr(offset);
4440 S += "), ";
4441 S += utostr(flag);
4442 S += ");\n}\n";
4443
4444 S += "static void __Block_byref_id_object_dispose_";
4445 S += utostr(flag);
4446 S += "(void *src) {\n";
4447 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4448 S += utostr(offset);
4449 S += "), ";
4450 S += utostr(flag);
4451 S += ");\n}\n";
4452 return S;
4453}
4454
4455/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4456/// the declaration into:
4457/// struct __Block_byref_ND {
4458/// void *__isa; // NULL for everything except __weak pointers
4459/// struct __Block_byref_ND *__forwarding;
4460/// int32_t __flags;
4461/// int32_t __size;
4462/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4463/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4464/// typex ND;
4465/// };
4466///
4467/// It then replaces declaration of ND variable with:
4468/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4469/// __size=sizeof(struct __Block_byref_ND),
4470/// ND=initializer-if-any};
4471///
4472///
4473void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4474 // Insert declaration for the function in which block literal is
4475 // used.
4476 if (CurFunctionDeclToDeclareForBlock)
4477 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4478 int flag = 0;
4479 int isa = 0;
4480 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4481 if (DeclLoc.isInvalid())
4482 // If type location is missing, it is because of missing type (a warning).
4483 // Use variable's location which is good for this case.
4484 DeclLoc = ND->getLocation();
4485 const char *startBuf = SM->getCharacterData(DeclLoc);
4486 SourceLocation X = ND->getLocEnd();
4487 X = SM->getExpansionLoc(X);
4488 const char *endBuf = SM->getCharacterData(X);
4489 std::string Name(ND->getNameAsString());
4490 std::string ByrefType;
4491 RewriteByRefString(ByrefType, Name, ND, true);
4492 ByrefType += " {\n";
4493 ByrefType += " void *__isa;\n";
4494 RewriteByRefString(ByrefType, Name, ND);
4495 ByrefType += " *__forwarding;\n";
4496 ByrefType += " int __flags;\n";
4497 ByrefType += " int __size;\n";
4498 // Add void *__Block_byref_id_object_copy;
4499 // void *__Block_byref_id_object_dispose; if needed.
4500 QualType Ty = ND->getType();
4501 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4502 if (HasCopyAndDispose) {
4503 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4504 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4505 }
4506
4507 QualType T = Ty;
4508 (void)convertBlockPointerToFunctionPointer(T);
4509 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4510
4511 ByrefType += " " + Name + ";\n";
4512 ByrefType += "};\n";
4513 // Insert this type in global scope. It is needed by helper function.
4514 SourceLocation FunLocStart;
4515 if (CurFunctionDef)
4516 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4517 else {
4518 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4519 FunLocStart = CurMethodDef->getLocStart();
4520 }
4521 InsertText(FunLocStart, ByrefType);
4522 if (Ty.isObjCGCWeak()) {
4523 flag |= BLOCK_FIELD_IS_WEAK;
4524 isa = 1;
4525 }
4526
4527 if (HasCopyAndDispose) {
4528 flag = BLOCK_BYREF_CALLER;
4529 QualType Ty = ND->getType();
4530 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4531 if (Ty->isBlockPointerType())
4532 flag |= BLOCK_FIELD_IS_BLOCK;
4533 else
4534 flag |= BLOCK_FIELD_IS_OBJECT;
4535 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4536 if (!HF.empty())
4537 InsertText(FunLocStart, HF);
4538 }
4539
4540 // struct __Block_byref_ND ND =
4541 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4542 // initializer-if-any};
4543 bool hasInit = (ND->getInit() != 0);
4544 unsigned flags = 0;
4545 if (HasCopyAndDispose)
4546 flags |= BLOCK_HAS_COPY_DISPOSE;
4547 Name = ND->getNameAsString();
4548 ByrefType.clear();
4549 RewriteByRefString(ByrefType, Name, ND);
4550 std::string ForwardingCastType("(");
4551 ForwardingCastType += ByrefType + " *)";
4552 if (!hasInit) {
4553 ByrefType += " " + Name + " = {(void*)";
4554 ByrefType += utostr(isa);
4555 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4556 ByrefType += utostr(flags);
4557 ByrefType += ", ";
4558 ByrefType += "sizeof(";
4559 RewriteByRefString(ByrefType, Name, ND);
4560 ByrefType += ")";
4561 if (HasCopyAndDispose) {
4562 ByrefType += ", __Block_byref_id_object_copy_";
4563 ByrefType += utostr(flag);
4564 ByrefType += ", __Block_byref_id_object_dispose_";
4565 ByrefType += utostr(flag);
4566 }
4567 ByrefType += "};\n";
4568 unsigned nameSize = Name.size();
4569 // for block or function pointer declaration. Name is aleady
4570 // part of the declaration.
4571 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4572 nameSize = 1;
4573 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4574 }
4575 else {
4576 SourceLocation startLoc;
4577 Expr *E = ND->getInit();
4578 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4579 startLoc = ECE->getLParenLoc();
4580 else
4581 startLoc = E->getLocStart();
4582 startLoc = SM->getExpansionLoc(startLoc);
4583 endBuf = SM->getCharacterData(startLoc);
4584 ByrefType += " " + Name;
4585 ByrefType += " = {(void*)";
4586 ByrefType += utostr(isa);
4587 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4588 ByrefType += utostr(flags);
4589 ByrefType += ", ";
4590 ByrefType += "sizeof(";
4591 RewriteByRefString(ByrefType, Name, ND);
4592 ByrefType += "), ";
4593 if (HasCopyAndDispose) {
4594 ByrefType += "__Block_byref_id_object_copy_";
4595 ByrefType += utostr(flag);
4596 ByrefType += ", __Block_byref_id_object_dispose_";
4597 ByrefType += utostr(flag);
4598 ByrefType += ", ";
4599 }
4600 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4601
4602 // Complete the newly synthesized compound expression by inserting a right
4603 // curly brace before the end of the declaration.
4604 // FIXME: This approach avoids rewriting the initializer expression. It
4605 // also assumes there is only one declarator. For example, the following
4606 // isn't currently supported by this routine (in general):
4607 //
4608 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4609 //
4610 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4611 const char *semiBuf = strchr(startInitializerBuf, ';');
4612 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4613 SourceLocation semiLoc =
4614 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4615
4616 InsertText(semiLoc, "}");
4617 }
4618 return;
4619}
4620
4621void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4622 // Add initializers for any closure decl refs.
4623 GetBlockDeclRefExprs(Exp->getBody());
4624 if (BlockDeclRefs.size()) {
4625 // Unique all "by copy" declarations.
4626 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004627 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004628 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4629 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4630 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4631 }
4632 }
4633 // Unique all "by ref" declarations.
4634 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004635 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004636 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4637 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4638 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4639 }
4640 }
4641 // Find any imported blocks...they will need special attention.
4642 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004643 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004644 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4645 BlockDeclRefs[i]->getType()->isBlockPointerType())
4646 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4647 }
4648}
4649
4650FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4651 IdentifierInfo *ID = &Context->Idents.get(name);
4652 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4653 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4654 SourceLocation(), ID, FType, 0, SC_Extern,
4655 SC_None, false, false);
4656}
4657
4658Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004659 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004660
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004661 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00004662
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004663 Blocks.push_back(Exp);
4664
4665 CollectBlockDeclRefInfo(Exp);
4666
4667 // Add inner imported variables now used in current block.
4668 int countOfInnerDecls = 0;
4669 if (!InnerBlockDeclRefs.empty()) {
4670 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004671 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004672 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004673 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004674 // We need to save the copied-in variables in nested
4675 // blocks because it is needed at the end for some of the API generations.
4676 // See SynthesizeBlockLiterals routine.
4677 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4678 BlockDeclRefs.push_back(Exp);
4679 BlockByCopyDeclsPtrSet.insert(VD);
4680 BlockByCopyDecls.push_back(VD);
4681 }
John McCallf4b88a42012-03-10 09:33:50 +00004682 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004683 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4684 BlockDeclRefs.push_back(Exp);
4685 BlockByRefDeclsPtrSet.insert(VD);
4686 BlockByRefDecls.push_back(VD);
4687 }
4688 }
4689 // Find any imported blocks...they will need special attention.
4690 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004691 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004692 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4693 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4694 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4695 }
4696 InnerDeclRefsCount.push_back(countOfInnerDecls);
4697
4698 std::string FuncName;
4699
4700 if (CurFunctionDef)
4701 FuncName = CurFunctionDef->getNameAsString();
4702 else if (CurMethodDef)
4703 BuildUniqueMethodName(FuncName, CurMethodDef);
4704 else if (GlobalVarDecl)
4705 FuncName = std::string(GlobalVarDecl->getNameAsString());
4706
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004707 bool GlobalBlockExpr =
4708 block->getDeclContext()->getRedeclContext()->isFileContext();
4709
4710 if (GlobalBlockExpr && !GlobalVarDecl) {
4711 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
4712 GlobalBlockExpr = false;
4713 }
4714
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004715 std::string BlockNumber = utostr(Blocks.size()-1);
4716
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004717 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4718
4719 // Get a pointer to the function type so we can cast appropriately.
4720 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4721 QualType FType = Context->getPointerType(BFT);
4722
4723 FunctionDecl *FD;
4724 Expr *NewRep;
4725
4726 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004727 std::string Tag;
4728
4729 if (GlobalBlockExpr)
4730 Tag = "__global_";
4731 else
4732 Tag = "__";
4733 Tag += FuncName + "_block_impl_" + BlockNumber;
4734
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004735 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004736 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004737 SourceLocation());
4738
4739 SmallVector<Expr*, 4> InitExprs;
4740
4741 // Initialize the block function.
4742 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004743 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4744 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004745 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4746 CK_BitCast, Arg);
4747 InitExprs.push_back(castExpr);
4748
4749 // Initialize the block descriptor.
4750 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4751
4752 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4753 SourceLocation(), SourceLocation(),
4754 &Context->Idents.get(DescData.c_str()),
4755 Context->VoidPtrTy, 0,
4756 SC_Static, SC_None);
4757 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004758 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004759 Context->VoidPtrTy,
4760 VK_LValue,
4761 SourceLocation()),
4762 UO_AddrOf,
4763 Context->getPointerType(Context->VoidPtrTy),
4764 VK_RValue, OK_Ordinary,
4765 SourceLocation());
4766 InitExprs.push_back(DescRefExpr);
4767
4768 // Add initializers for any closure decl refs.
4769 if (BlockDeclRefs.size()) {
4770 Expr *Exp;
4771 // Output all "by copy" declarations.
4772 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4773 E = BlockByCopyDecls.end(); I != E; ++I) {
4774 if (isObjCType((*I)->getType())) {
4775 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4776 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004777 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4778 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004779 if (HasLocalVariableExternalStorage(*I)) {
4780 QualType QT = (*I)->getType();
4781 QT = Context->getPointerType(QT);
4782 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4783 OK_Ordinary, SourceLocation());
4784 }
4785 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4786 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004787 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4788 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004789 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4790 CK_BitCast, Arg);
4791 } else {
4792 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004793 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4794 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004795 if (HasLocalVariableExternalStorage(*I)) {
4796 QualType QT = (*I)->getType();
4797 QT = Context->getPointerType(QT);
4798 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4799 OK_Ordinary, SourceLocation());
4800 }
4801
4802 }
4803 InitExprs.push_back(Exp);
4804 }
4805 // Output all "by ref" declarations.
4806 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4807 E = BlockByRefDecls.end(); I != E; ++I) {
4808 ValueDecl *ND = (*I);
4809 std::string Name(ND->getNameAsString());
4810 std::string RecName;
4811 RewriteByRefString(RecName, Name, ND, true);
4812 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4813 + sizeof("struct"));
4814 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4815 SourceLocation(), SourceLocation(),
4816 II);
4817 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4818 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4819
4820 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004821 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004822 SourceLocation());
4823 bool isNestedCapturedVar = false;
4824 if (block)
4825 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4826 ce = block->capture_end(); ci != ce; ++ci) {
4827 const VarDecl *variable = ci->getVariable();
4828 if (variable == ND && ci->isNested()) {
4829 assert (ci->isByRef() &&
4830 "SynthBlockInitExpr - captured block variable is not byref");
4831 isNestedCapturedVar = true;
4832 break;
4833 }
4834 }
4835 // captured nested byref variable has its address passed. Do not take
4836 // its address again.
4837 if (!isNestedCapturedVar)
4838 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4839 Context->getPointerType(Exp->getType()),
4840 VK_RValue, OK_Ordinary, SourceLocation());
4841 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4842 InitExprs.push_back(Exp);
4843 }
4844 }
4845 if (ImportedBlockDecls.size()) {
4846 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4847 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4848 unsigned IntSize =
4849 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4850 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4851 Context->IntTy, SourceLocation());
4852 InitExprs.push_back(FlagExp);
4853 }
4854 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4855 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004856
4857 if (GlobalBlockExpr) {
4858 assert (GlobalConstructionExp == 0 &&
4859 "SynthBlockInitExpr - GlobalConstructionExp must be null");
4860 GlobalConstructionExp = NewRep;
4861 NewRep = DRE;
4862 }
4863
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004864 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4865 Context->getPointerType(NewRep->getType()),
4866 VK_RValue, OK_Ordinary, SourceLocation());
4867 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4868 NewRep);
4869 BlockDeclRefs.clear();
4870 BlockByRefDecls.clear();
4871 BlockByRefDeclsPtrSet.clear();
4872 BlockByCopyDecls.clear();
4873 BlockByCopyDeclsPtrSet.clear();
4874 ImportedBlockDecls.clear();
4875 return NewRep;
4876}
4877
4878bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4879 if (const ObjCForCollectionStmt * CS =
4880 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4881 return CS->getElement() == DS;
4882 return false;
4883}
4884
4885//===----------------------------------------------------------------------===//
4886// Function Body / Expression rewriting
4887//===----------------------------------------------------------------------===//
4888
4889Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4890 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4891 isa<DoStmt>(S) || isa<ForStmt>(S))
4892 Stmts.push_back(S);
4893 else if (isa<ObjCForCollectionStmt>(S)) {
4894 Stmts.push_back(S);
4895 ObjCBcLabelNo.push_back(++BcLabelCount);
4896 }
4897
4898 // Pseudo-object operations and ivar references need special
4899 // treatment because we're going to recursively rewrite them.
4900 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4901 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4902 return RewritePropertyOrImplicitSetter(PseudoOp);
4903 } else {
4904 return RewritePropertyOrImplicitGetter(PseudoOp);
4905 }
4906 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4907 return RewriteObjCIvarRefExpr(IvarRefExpr);
4908 }
4909
4910 SourceRange OrigStmtRange = S->getSourceRange();
4911
4912 // Perform a bottom up rewrite of all children.
4913 for (Stmt::child_range CI = S->children(); CI; ++CI)
4914 if (*CI) {
4915 Stmt *childStmt = (*CI);
4916 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4917 if (newStmt) {
4918 *CI = newStmt;
4919 }
4920 }
4921
4922 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004923 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004924 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4925 InnerContexts.insert(BE->getBlockDecl());
4926 ImportedLocalExternalDecls.clear();
4927 GetInnerBlockDeclRefExprs(BE->getBody(),
4928 InnerBlockDeclRefs, InnerContexts);
4929 // Rewrite the block body in place.
4930 Stmt *SaveCurrentBody = CurrentBody;
4931 CurrentBody = BE->getBody();
4932 PropParentMap = 0;
4933 // block literal on rhs of a property-dot-sytax assignment
4934 // must be replaced by its synthesize ast so getRewrittenText
4935 // works as expected. In this case, what actually ends up on RHS
4936 // is the blockTranscribed which is the helper function for the
4937 // block literal; as in: self.c = ^() {[ace ARR];};
4938 bool saveDisableReplaceStmt = DisableReplaceStmt;
4939 DisableReplaceStmt = false;
4940 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4941 DisableReplaceStmt = saveDisableReplaceStmt;
4942 CurrentBody = SaveCurrentBody;
4943 PropParentMap = 0;
4944 ImportedLocalExternalDecls.clear();
4945 // Now we snarf the rewritten text and stash it away for later use.
4946 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4947 RewrittenBlockExprs[BE] = Str;
4948
4949 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4950
4951 //blockTranscribed->dump();
4952 ReplaceStmt(S, blockTranscribed);
4953 return blockTranscribed;
4954 }
4955 // Handle specific things.
4956 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4957 return RewriteAtEncode(AtEncode);
4958
4959 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4960 return RewriteAtSelector(AtSelector);
4961
4962 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4963 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00004964
4965 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
4966 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00004967
4968 if (ObjCNumericLiteral *NumericLitExpr = dyn_cast<ObjCNumericLiteral>(S))
4969 return RewriteObjCNumericLiteralExpr(NumericLitExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00004970
4971 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
4972 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004973
4974 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4975#if 0
4976 // Before we rewrite it, put the original message expression in a comment.
4977 SourceLocation startLoc = MessExpr->getLocStart();
4978 SourceLocation endLoc = MessExpr->getLocEnd();
4979
4980 const char *startBuf = SM->getCharacterData(startLoc);
4981 const char *endBuf = SM->getCharacterData(endLoc);
4982
4983 std::string messString;
4984 messString += "// ";
4985 messString.append(startBuf, endBuf-startBuf+1);
4986 messString += "\n";
4987
4988 // FIXME: Missing definition of
4989 // InsertText(clang::SourceLocation, char const*, unsigned int).
4990 // InsertText(startLoc, messString.c_str(), messString.size());
4991 // Tried this, but it didn't work either...
4992 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4993#endif
4994 return RewriteMessageExpr(MessExpr);
4995 }
4996
4997 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4998 return RewriteObjCTryStmt(StmtTry);
4999
5000 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5001 return RewriteObjCSynchronizedStmt(StmtTry);
5002
5003 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5004 return RewriteObjCThrowStmt(StmtThrow);
5005
5006 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5007 return RewriteObjCProtocolExpr(ProtocolExp);
5008
5009 if (ObjCForCollectionStmt *StmtForCollection =
5010 dyn_cast<ObjCForCollectionStmt>(S))
5011 return RewriteObjCForCollectionStmt(StmtForCollection,
5012 OrigStmtRange.getEnd());
5013 if (BreakStmt *StmtBreakStmt =
5014 dyn_cast<BreakStmt>(S))
5015 return RewriteBreakStmt(StmtBreakStmt);
5016 if (ContinueStmt *StmtContinueStmt =
5017 dyn_cast<ContinueStmt>(S))
5018 return RewriteContinueStmt(StmtContinueStmt);
5019
5020 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5021 // and cast exprs.
5022 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5023 // FIXME: What we're doing here is modifying the type-specifier that
5024 // precedes the first Decl. In the future the DeclGroup should have
5025 // a separate type-specifier that we can rewrite.
5026 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5027 // the context of an ObjCForCollectionStmt. For example:
5028 // NSArray *someArray;
5029 // for (id <FooProtocol> index in someArray) ;
5030 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5031 // and it depends on the original text locations/positions.
5032 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5033 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5034
5035 // Blocks rewrite rules.
5036 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5037 DI != DE; ++DI) {
5038 Decl *SD = *DI;
5039 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5040 if (isTopLevelBlockPointerType(ND->getType()))
5041 RewriteBlockPointerDecl(ND);
5042 else if (ND->getType()->isFunctionPointerType())
5043 CheckFunctionPointerDecl(ND->getType(), ND);
5044 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5045 if (VD->hasAttr<BlocksAttr>()) {
5046 static unsigned uniqueByrefDeclCount = 0;
5047 assert(!BlockByRefDeclNo.count(ND) &&
5048 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5049 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5050 RewriteByRefVar(VD);
5051 }
5052 else
5053 RewriteTypeOfDecl(VD);
5054 }
5055 }
5056 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5057 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5058 RewriteBlockPointerDecl(TD);
5059 else if (TD->getUnderlyingType()->isFunctionPointerType())
5060 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5061 }
5062 }
5063 }
5064
5065 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5066 RewriteObjCQualifiedInterfaceTypes(CE);
5067
5068 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5069 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5070 assert(!Stmts.empty() && "Statement stack is empty");
5071 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5072 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5073 && "Statement stack mismatch");
5074 Stmts.pop_back();
5075 }
5076 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005077 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5078 ValueDecl *VD = DRE->getDecl();
5079 if (VD->hasAttr<BlocksAttr>())
5080 return RewriteBlockDeclRefExpr(DRE);
5081 if (HasLocalVariableExternalStorage(VD))
5082 return RewriteLocalVariableExternalStorage(DRE);
5083 }
5084
5085 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5086 if (CE->getCallee()->getType()->isBlockPointerType()) {
5087 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5088 ReplaceStmt(S, BlockCall);
5089 return BlockCall;
5090 }
5091 }
5092 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5093 RewriteCastExpr(CE);
5094 }
5095#if 0
5096 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5097 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5098 ICE->getSubExpr(),
5099 SourceLocation());
5100 // Get the new text.
5101 std::string SStr;
5102 llvm::raw_string_ostream Buf(SStr);
5103 Replacement->printPretty(Buf, *Context);
5104 const std::string &Str = Buf.str();
5105
5106 printf("CAST = %s\n", &Str[0]);
5107 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5108 delete S;
5109 return Replacement;
5110 }
5111#endif
5112 // Return this stmt unmodified.
5113 return S;
5114}
5115
5116void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5117 for (RecordDecl::field_iterator i = RD->field_begin(),
5118 e = RD->field_end(); i != e; ++i) {
5119 FieldDecl *FD = *i;
5120 if (isTopLevelBlockPointerType(FD->getType()))
5121 RewriteBlockPointerDecl(FD);
5122 if (FD->getType()->isObjCQualifiedIdType() ||
5123 FD->getType()->isObjCQualifiedInterfaceType())
5124 RewriteObjCQualifiedInterfaceTypes(FD);
5125 }
5126}
5127
5128/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5129/// main file of the input.
5130void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5131 switch (D->getKind()) {
5132 case Decl::Function: {
5133 FunctionDecl *FD = cast<FunctionDecl>(D);
5134 if (FD->isOverloadedOperator())
5135 return;
5136
5137 // Since function prototypes don't have ParmDecl's, we check the function
5138 // prototype. This enables us to rewrite function declarations and
5139 // definitions using the same code.
5140 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5141
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005142 if (!FD->isThisDeclarationADefinition())
5143 break;
5144
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005145 // FIXME: If this should support Obj-C++, support CXXTryStmt
5146 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5147 CurFunctionDef = FD;
5148 CurFunctionDeclToDeclareForBlock = FD;
5149 CurrentBody = Body;
5150 Body =
5151 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5152 FD->setBody(Body);
5153 CurrentBody = 0;
5154 if (PropParentMap) {
5155 delete PropParentMap;
5156 PropParentMap = 0;
5157 }
5158 // This synthesizes and inserts the block "impl" struct, invoke function,
5159 // and any copy/dispose helper functions.
5160 InsertBlockLiteralsWithinFunction(FD);
5161 CurFunctionDef = 0;
5162 CurFunctionDeclToDeclareForBlock = 0;
5163 }
5164 break;
5165 }
5166 case Decl::ObjCMethod: {
5167 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5168 if (CompoundStmt *Body = MD->getCompoundBody()) {
5169 CurMethodDef = MD;
5170 CurrentBody = Body;
5171 Body =
5172 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5173 MD->setBody(Body);
5174 CurrentBody = 0;
5175 if (PropParentMap) {
5176 delete PropParentMap;
5177 PropParentMap = 0;
5178 }
5179 InsertBlockLiteralsWithinMethod(MD);
5180 CurMethodDef = 0;
5181 }
5182 break;
5183 }
5184 case Decl::ObjCImplementation: {
5185 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5186 ClassImplementation.push_back(CI);
5187 break;
5188 }
5189 case Decl::ObjCCategoryImpl: {
5190 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5191 CategoryImplementation.push_back(CI);
5192 break;
5193 }
5194 case Decl::Var: {
5195 VarDecl *VD = cast<VarDecl>(D);
5196 RewriteObjCQualifiedInterfaceTypes(VD);
5197 if (isTopLevelBlockPointerType(VD->getType()))
5198 RewriteBlockPointerDecl(VD);
5199 else if (VD->getType()->isFunctionPointerType()) {
5200 CheckFunctionPointerDecl(VD->getType(), VD);
5201 if (VD->getInit()) {
5202 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5203 RewriteCastExpr(CE);
5204 }
5205 }
5206 } else if (VD->getType()->isRecordType()) {
5207 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5208 if (RD->isCompleteDefinition())
5209 RewriteRecordBody(RD);
5210 }
5211 if (VD->getInit()) {
5212 GlobalVarDecl = VD;
5213 CurrentBody = VD->getInit();
5214 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5215 CurrentBody = 0;
5216 if (PropParentMap) {
5217 delete PropParentMap;
5218 PropParentMap = 0;
5219 }
5220 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5221 GlobalVarDecl = 0;
5222
5223 // This is needed for blocks.
5224 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5225 RewriteCastExpr(CE);
5226 }
5227 }
5228 break;
5229 }
5230 case Decl::TypeAlias:
5231 case Decl::Typedef: {
5232 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5233 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5234 RewriteBlockPointerDecl(TD);
5235 else if (TD->getUnderlyingType()->isFunctionPointerType())
5236 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5237 }
5238 break;
5239 }
5240 case Decl::CXXRecord:
5241 case Decl::Record: {
5242 RecordDecl *RD = cast<RecordDecl>(D);
5243 if (RD->isCompleteDefinition())
5244 RewriteRecordBody(RD);
5245 break;
5246 }
5247 default:
5248 break;
5249 }
5250 // Nothing yet.
5251}
5252
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005253/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5254/// protocol reference symbols in the for of:
5255/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5256static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5257 ObjCProtocolDecl *PDecl,
5258 std::string &Result) {
5259 // Also output .objc_protorefs$B section and its meta-data.
5260 if (Context->getLangOpts().MicrosoftExt)
5261 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
5262 Result += "struct _protocol_t *";
5263 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5264 Result += PDecl->getNameAsString();
5265 Result += " = &";
5266 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5267 Result += ";\n";
5268}
5269
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005270void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5271 if (Diags.hasErrorOccurred())
5272 return;
5273
5274 RewriteInclude();
5275
5276 // Here's a great place to add any extra declarations that may be needed.
5277 // Write out meta data for each @protocol(<expr>).
5278 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005279 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005280 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005281 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5282 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005283
5284 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00005285 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5286 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5287 // Write struct declaration for the class matching its ivar declarations.
5288 // Note that for modern abi, this is postponed until the end of TU
5289 // because class extensions and the implementation might declare their own
5290 // private ivars.
5291 RewriteInterfaceDecl(CDecl);
5292 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005293
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005294 if (ClassImplementation.size() || CategoryImplementation.size())
5295 RewriteImplementations();
5296
5297 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5298 // we are done.
5299 if (const RewriteBuffer *RewriteBuf =
5300 Rewrite.getRewriteBufferFor(MainFileID)) {
5301 //printf("Changed:\n");
5302 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5303 } else {
5304 llvm::errs() << "No changes\n";
5305 }
5306
5307 if (ClassImplementation.size() || CategoryImplementation.size() ||
5308 ProtocolExprDecls.size()) {
5309 // Rewrite Objective-c meta data*
5310 std::string ResultStr;
5311 RewriteMetaDataIntoBuffer(ResultStr);
5312 // Emit metadata.
5313 *OutFile << ResultStr;
5314 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005315 // Emit ImageInfo;
5316 {
5317 std::string ResultStr;
5318 WriteImageInfo(ResultStr);
5319 *OutFile << ResultStr;
5320 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005321 OutFile->flush();
5322}
5323
5324void RewriteModernObjC::Initialize(ASTContext &context) {
5325 InitializeCommon(context);
5326
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005327 Preamble += "#ifndef __OBJC2__\n";
5328 Preamble += "#define __OBJC2__\n";
5329 Preamble += "#endif\n";
5330
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005331 // declaring objc_selector outside the parameter list removes a silly
5332 // scope related warning...
5333 if (IsHeader)
5334 Preamble = "#pragma once\n";
5335 Preamble += "struct objc_selector; struct objc_class;\n";
5336 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5337 Preamble += "struct objc_object *superClass; ";
5338 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005339 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005340 // These are currently generated.
5341 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005342 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005343 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5344 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005345 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5346 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005347 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005348 // These are generated but not necessary for functionality.
5349 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5350 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005351 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5352 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005353 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005354
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005355 // These need be generated for performance. Currently they are not,
5356 // using API calls instead.
5357 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5358 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5359 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5360
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005361 // Add a constructor for creating temporary objects.
5362 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5363 ": ";
5364 Preamble += "object(o), superClass(s) {} ";
5365 }
5366 Preamble += "};\n";
5367 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5368 Preamble += "typedef struct objc_object Protocol;\n";
5369 Preamble += "#define _REWRITER_typedef_Protocol\n";
5370 Preamble += "#endif\n";
5371 if (LangOpts.MicrosoftExt) {
5372 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5373 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005374 }
5375 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005376 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00005377
5378 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
5379 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
5380 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
5381 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
5382 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
5383
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005384 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5385 Preamble += "(const char *);\n";
5386 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5387 Preamble += "(struct objc_class *);\n";
5388 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5389 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005390 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005391 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005392 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5393 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005394 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5395 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5396 Preamble += "struct __objcFastEnumerationState {\n\t";
5397 Preamble += "unsigned long state;\n\t";
5398 Preamble += "void **itemsPtr;\n\t";
5399 Preamble += "unsigned long *mutationsPtr;\n\t";
5400 Preamble += "unsigned long extra[5];\n};\n";
5401 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5402 Preamble += "#define __FASTENUMERATIONSTATE\n";
5403 Preamble += "#endif\n";
5404 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5405 Preamble += "struct __NSConstantStringImpl {\n";
5406 Preamble += " int *isa;\n";
5407 Preamble += " int flags;\n";
5408 Preamble += " char *str;\n";
5409 Preamble += " long length;\n";
5410 Preamble += "};\n";
5411 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5412 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5413 Preamble += "#else\n";
5414 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5415 Preamble += "#endif\n";
5416 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5417 Preamble += "#endif\n";
5418 // Blocks preamble.
5419 Preamble += "#ifndef BLOCK_IMPL\n";
5420 Preamble += "#define BLOCK_IMPL\n";
5421 Preamble += "struct __block_impl {\n";
5422 Preamble += " void *isa;\n";
5423 Preamble += " int Flags;\n";
5424 Preamble += " int Reserved;\n";
5425 Preamble += " void *FuncPtr;\n";
5426 Preamble += "};\n";
5427 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5428 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5429 Preamble += "extern \"C\" __declspec(dllexport) "
5430 "void _Block_object_assign(void *, const void *, const int);\n";
5431 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5432 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5433 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5434 Preamble += "#else\n";
5435 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5436 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5437 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5438 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5439 Preamble += "#endif\n";
5440 Preamble += "#endif\n";
5441 if (LangOpts.MicrosoftExt) {
5442 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5443 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5444 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5445 Preamble += "#define __attribute__(X)\n";
5446 Preamble += "#endif\n";
5447 Preamble += "#define __weak\n";
5448 }
5449 else {
5450 Preamble += "#define __block\n";
5451 Preamble += "#define __weak\n";
5452 }
5453 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5454 // as this avoids warning in any 64bit/32bit compilation model.
5455 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5456}
5457
5458/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5459/// ivar offset.
5460void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5461 std::string &Result) {
5462 if (ivar->isBitField()) {
5463 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5464 // place all bitfields at offset 0.
5465 Result += "0";
5466 } else {
5467 Result += "__OFFSETOFIVAR__(struct ";
5468 Result += ivar->getContainingInterface()->getNameAsString();
5469 if (LangOpts.MicrosoftExt)
5470 Result += "_IMPL";
5471 Result += ", ";
5472 Result += ivar->getNameAsString();
5473 Result += ")";
5474 }
5475}
5476
5477/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5478/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005479/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005480/// char *attributes;
5481/// }
5482
5483/// struct _prop_list_t {
5484/// uint32_t entsize; // sizeof(struct _prop_t)
5485/// uint32_t count_of_properties;
5486/// struct _prop_t prop_list[count_of_properties];
5487/// }
5488
5489/// struct _protocol_t;
5490
5491/// struct _protocol_list_t {
5492/// long protocol_count; // Note, this is 32/64 bit
5493/// struct _protocol_t * protocol_list[protocol_count];
5494/// }
5495
5496/// struct _objc_method {
5497/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005498/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005499/// char *_imp;
5500/// }
5501
5502/// struct _method_list_t {
5503/// uint32_t entsize; // sizeof(struct _objc_method)
5504/// uint32_t method_count;
5505/// struct _objc_method method_list[method_count];
5506/// }
5507
5508/// struct _protocol_t {
5509/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005510/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005511/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005512/// const struct method_list_t *instance_methods;
5513/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005514/// const struct method_list_t *optionalInstanceMethods;
5515/// const struct method_list_t *optionalClassMethods;
5516/// const struct _prop_list_t * properties;
5517/// const uint32_t size; // sizeof(struct _protocol_t)
5518/// const uint32_t flags; // = 0
5519/// const char ** extendedMethodTypes;
5520/// }
5521
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005522/// struct _ivar_t {
5523/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005524/// const char *name;
5525/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005526/// uint32_t alignment;
5527/// uint32_t size;
5528/// }
5529
5530/// struct _ivar_list_t {
5531/// uint32 entsize; // sizeof(struct _ivar_t)
5532/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005533/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005534/// }
5535
5536/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005537/// uint32_t flags;
5538/// uint32_t instanceStart;
5539/// uint32_t instanceSize;
5540/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005541/// const uint8_t *ivarLayout;
5542/// const char *name;
5543/// const struct _method_list_t *baseMethods;
5544/// const struct _protocol_list_t *baseProtocols;
5545/// const struct _ivar_list_t *ivars;
5546/// const uint8_t *weakIvarLayout;
5547/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005548/// }
5549
5550/// struct _class_t {
5551/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005552/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005553/// void *cache;
5554/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005555/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005556/// }
5557
5558/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005559/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005560/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005561/// const struct _method_list_t *instance_methods;
5562/// const struct _method_list_t *class_methods;
5563/// const struct _protocol_list_t *protocols;
5564/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005565/// }
5566
5567/// MessageRefTy - LLVM for:
5568/// struct _message_ref_t {
5569/// IMP messenger;
5570/// SEL name;
5571/// };
5572
5573/// SuperMessageRefTy - LLVM for:
5574/// struct _super_message_ref_t {
5575/// SUPER_IMP messenger;
5576/// SEL name;
5577/// };
5578
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005579static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005580 static bool meta_data_declared = false;
5581 if (meta_data_declared)
5582 return;
5583
5584 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005585 Result += "\tconst char *name;\n";
5586 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005587 Result += "};\n";
5588
5589 Result += "\nstruct _protocol_t;\n";
5590
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005591 Result += "\nstruct _objc_method {\n";
5592 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005593 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005594 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005595 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005596
5597 Result += "\nstruct _protocol_t {\n";
5598 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005599 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005600 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005601 Result += "\tconst struct method_list_t *instance_methods;\n";
5602 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005603 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5604 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5605 Result += "\tconst struct _prop_list_t * properties;\n";
5606 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5607 Result += "\tconst unsigned int flags; // = 0\n";
5608 Result += "\tconst char ** extendedMethodTypes;\n";
5609 Result += "};\n";
5610
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005611 Result += "\nstruct _ivar_t {\n";
5612 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005613 Result += "\tconst char *name;\n";
5614 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005615 Result += "\tunsigned int alignment;\n";
5616 Result += "\tunsigned int size;\n";
5617 Result += "};\n";
5618
5619 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005620 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005621 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005622 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005623 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5624 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00005625 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005626 Result += "\tconst unsigned char *ivarLayout;\n";
5627 Result += "\tconst char *name;\n";
5628 Result += "\tconst struct _method_list_t *baseMethods;\n";
5629 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
5630 Result += "\tconst struct _ivar_list_t *ivars;\n";
5631 Result += "\tconst unsigned char *weakIvarLayout;\n";
5632 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005633 Result += "};\n";
5634
5635 Result += "\nstruct _class_t {\n";
5636 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00005637 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005638 Result += "\tvoid *cache;\n";
5639 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005640 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005641 Result += "};\n";
5642
5643 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005644 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00005645 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00005646 Result += "\tconst struct _method_list_t *instance_methods;\n";
5647 Result += "\tconst struct _method_list_t *class_methods;\n";
5648 Result += "\tconst struct _protocol_list_t *protocols;\n";
5649 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005650 Result += "};\n";
5651
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005652 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005653 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005654 meta_data_declared = true;
5655}
5656
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005657static void Write_protocol_list_t_TypeDecl(std::string &Result,
5658 long super_protocol_count) {
5659 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5660 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5661 Result += "\tstruct _protocol_t *super_protocols[";
5662 Result += utostr(super_protocol_count); Result += "];\n";
5663 Result += "}";
5664}
5665
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005666static void Write_method_list_t_TypeDecl(std::string &Result,
5667 unsigned int method_count) {
5668 Result += "struct /*_method_list_t*/"; Result += " {\n";
5669 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5670 Result += "\tunsigned int method_count;\n";
5671 Result += "\tstruct _objc_method method_list[";
5672 Result += utostr(method_count); Result += "];\n";
5673 Result += "}";
5674}
5675
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005676static void Write__prop_list_t_TypeDecl(std::string &Result,
5677 unsigned int property_count) {
5678 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5679 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5680 Result += "\tunsigned int count_of_properties;\n";
5681 Result += "\tstruct _prop_t prop_list[";
5682 Result += utostr(property_count); Result += "];\n";
5683 Result += "}";
5684}
5685
Fariborz Jahanianae932952012-02-10 20:47:10 +00005686static void Write__ivar_list_t_TypeDecl(std::string &Result,
5687 unsigned int ivar_count) {
5688 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5689 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5690 Result += "\tunsigned int count;\n";
5691 Result += "\tstruct _ivar_t ivar_list[";
5692 Result += utostr(ivar_count); Result += "];\n";
5693 Result += "}";
5694}
5695
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005696static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5697 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5698 StringRef VarName,
5699 StringRef ProtocolName) {
5700 if (SuperProtocols.size() > 0) {
5701 Result += "\nstatic ";
5702 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5703 Result += " "; Result += VarName;
5704 Result += ProtocolName;
5705 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5706 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5707 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5708 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5709 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5710 Result += SuperPD->getNameAsString();
5711 if (i == e-1)
5712 Result += "\n};\n";
5713 else
5714 Result += ",\n";
5715 }
5716 }
5717}
5718
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005719static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5720 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005721 ArrayRef<ObjCMethodDecl *> Methods,
5722 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005723 StringRef TopLevelDeclName,
5724 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005725 if (Methods.size() > 0) {
5726 Result += "\nstatic ";
5727 Write_method_list_t_TypeDecl(Result, Methods.size());
5728 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005729 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005730 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5731 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5732 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5733 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5734 ObjCMethodDecl *MD = Methods[i];
5735 if (i == 0)
5736 Result += "\t{{(struct objc_selector *)\"";
5737 else
5738 Result += "\t{(struct objc_selector *)\"";
5739 Result += (MD)->getSelector().getAsString(); Result += "\"";
5740 Result += ", ";
5741 std::string MethodTypeString;
5742 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5743 Result += "\""; Result += MethodTypeString; Result += "\"";
5744 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005745 if (!MethodImpl)
5746 Result += "0";
5747 else {
5748 Result += "(void *)";
5749 Result += RewriteObj.MethodInternalNames[MD];
5750 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005751 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005752 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005753 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005754 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005755 }
5756 Result += "};\n";
5757 }
5758}
5759
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005760static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005761 ASTContext *Context, std::string &Result,
5762 ArrayRef<ObjCPropertyDecl *> Properties,
5763 const Decl *Container,
5764 StringRef VarName,
5765 StringRef ProtocolName) {
5766 if (Properties.size() > 0) {
5767 Result += "\nstatic ";
5768 Write__prop_list_t_TypeDecl(Result, Properties.size());
5769 Result += " "; Result += VarName;
5770 Result += ProtocolName;
5771 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5772 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5773 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5774 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5775 ObjCPropertyDecl *PropDecl = Properties[i];
5776 if (i == 0)
5777 Result += "\t{{\"";
5778 else
5779 Result += "\t{\"";
5780 Result += PropDecl->getName(); Result += "\",";
5781 std::string PropertyTypeString, QuotePropertyTypeString;
5782 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5783 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5784 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5785 if (i == e-1)
5786 Result += "}}\n";
5787 else
5788 Result += "},\n";
5789 }
5790 Result += "};\n";
5791 }
5792}
5793
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005794// Metadata flags
5795enum MetaDataDlags {
5796 CLS = 0x0,
5797 CLS_META = 0x1,
5798 CLS_ROOT = 0x2,
5799 OBJC2_CLS_HIDDEN = 0x10,
5800 CLS_EXCEPTION = 0x20,
5801
5802 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5803 CLS_HAS_IVAR_RELEASER = 0x40,
5804 /// class was compiled with -fobjc-arr
5805 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5806};
5807
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005808static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5809 unsigned int flags,
5810 const std::string &InstanceStart,
5811 const std::string &InstanceSize,
5812 ArrayRef<ObjCMethodDecl *>baseMethods,
5813 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5814 ArrayRef<ObjCIvarDecl *>ivars,
5815 ArrayRef<ObjCPropertyDecl *>Properties,
5816 StringRef VarName,
5817 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005818 Result += "\nstatic struct _class_ro_t ";
5819 Result += VarName; Result += ClassName;
5820 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5821 Result += "\t";
5822 Result += llvm::utostr(flags); Result += ", ";
5823 Result += InstanceStart; Result += ", ";
5824 Result += InstanceSize; Result += ", \n";
5825 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005826 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5827 if (Triple.getArch() == llvm::Triple::x86_64)
5828 // uint32_t const reserved; // only when building for 64bit targets
5829 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005830 // const uint8_t * const ivarLayout;
5831 Result += "0, \n\t";
5832 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005833 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005834 if (baseMethods.size() > 0) {
5835 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005836 if (metaclass)
5837 Result += "_OBJC_$_CLASS_METHODS_";
5838 else
5839 Result += "_OBJC_$_INSTANCE_METHODS_";
5840 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005841 Result += ",\n\t";
5842 }
5843 else
5844 Result += "0, \n\t";
5845
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005846 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005847 Result += "(const struct _objc_protocol_list *)&";
5848 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5849 Result += ",\n\t";
5850 }
5851 else
5852 Result += "0, \n\t";
5853
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005854 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005855 Result += "(const struct _ivar_list_t *)&";
5856 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5857 Result += ",\n\t";
5858 }
5859 else
5860 Result += "0, \n\t";
5861
5862 // weakIvarLayout
5863 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005864 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005865 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005866 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005867 Result += ",\n";
5868 }
5869 else
5870 Result += "0, \n";
5871
5872 Result += "};\n";
5873}
5874
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005875static void Write_class_t(ASTContext *Context, std::string &Result,
5876 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005877 const ObjCInterfaceDecl *CDecl, bool metaclass) {
5878 bool rootClass = (!CDecl->getSuperClass());
5879 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005880
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005881 if (!rootClass) {
5882 // Find the Root class
5883 RootClass = CDecl->getSuperClass();
5884 while (RootClass->getSuperClass()) {
5885 RootClass = RootClass->getSuperClass();
5886 }
5887 }
5888
5889 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005890 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005891 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005892 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005893 if (CDecl->getImplementation())
5894 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005895 else
5896 Result += "__declspec(dllimport) ";
5897
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005898 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005899 Result += CDecl->getNameAsString();
5900 Result += ";\n";
5901 }
5902 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005903 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005904 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005905 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005906 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005907 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005908 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005909 else
5910 Result += "__declspec(dllimport) ";
5911
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005912 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005913 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005914 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005915 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005916
Fariborz Jahanian868e9852012-03-29 19:04:10 +00005917 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005918 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005919 if (RootClass->getImplementation())
5920 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005921 else
5922 Result += "__declspec(dllimport) ";
5923
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00005924 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005925 Result += VarName;
5926 Result += RootClass->getNameAsString();
5927 Result += ";\n";
5928 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005929 }
5930
Fariborz Jahanian297976d2012-03-29 17:51:09 +00005931 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
5932 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005933 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5934 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005935 if (metaclass) {
5936 if (!rootClass) {
5937 Result += "0, // &"; Result += VarName;
5938 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005939 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005940 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005941 Result += CDecl->getSuperClass()->getNameAsString();
5942 Result += ",\n\t";
5943 }
5944 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005945 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005946 Result += CDecl->getNameAsString();
5947 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005948 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005949 Result += ",\n\t";
5950 }
5951 }
5952 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005953 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005954 Result += CDecl->getNameAsString();
5955 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005956 if (!rootClass) {
5957 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005958 Result += CDecl->getSuperClass()->getNameAsString();
5959 Result += ",\n\t";
5960 }
5961 else
5962 Result += "0,\n\t";
5963 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005964 Result += "0, // (void *)&_objc_empty_cache,\n\t";
5965 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
5966 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005967 Result += "&_OBJC_METACLASS_RO_$_";
5968 else
5969 Result += "&_OBJC_CLASS_RO_$_";
5970 Result += CDecl->getNameAsString();
5971 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005972
5973 // Add static function to initialize some of the meta-data fields.
5974 // avoid doing it twice.
5975 if (metaclass)
5976 return;
5977
5978 const ObjCInterfaceDecl *SuperClass =
5979 rootClass ? CDecl : CDecl->getSuperClass();
5980
5981 Result += "static void OBJC_CLASS_SETUP_$_";
5982 Result += CDecl->getNameAsString();
5983 Result += "(void ) {\n";
5984 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5985 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005986 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005987
5988 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00005989 Result += ".superclass = ";
5990 if (rootClass)
5991 Result += "&OBJC_CLASS_$_";
5992 else
5993 Result += "&OBJC_METACLASS_$_";
5994
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00005995 Result += SuperClass->getNameAsString(); Result += ";\n";
5996
5997 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
5998 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
5999
6000 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6001 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6002 Result += CDecl->getNameAsString(); Result += ";\n";
6003
6004 if (!rootClass) {
6005 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6006 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6007 Result += SuperClass->getNameAsString(); Result += ";\n";
6008 }
6009
6010 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6011 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6012 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006013}
6014
Fariborz Jahanian61186122012-02-17 18:40:41 +00006015static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6016 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006017 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006018 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006019 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6020 ArrayRef<ObjCMethodDecl *> ClassMethods,
6021 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6022 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006023 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006024 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006025 // must declare an extern class object in case this class is not implemented
6026 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006027 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006028 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006029 if (ClassDecl->getImplementation())
6030 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006031 else
6032 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006033
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006034 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006035 Result += "OBJC_CLASS_$_"; Result += ClassName;
6036 Result += ";\n";
6037
Fariborz Jahanian61186122012-02-17 18:40:41 +00006038 Result += "\nstatic struct _category_t ";
6039 Result += "_OBJC_$_CATEGORY_";
6040 Result += ClassName; Result += "_$_"; Result += CatName;
6041 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6042 Result += "{\n";
6043 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006044 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006045 Result += ",\n";
6046 if (InstanceMethods.size() > 0) {
6047 Result += "\t(const struct _method_list_t *)&";
6048 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6049 Result += ClassName; Result += "_$_"; Result += CatName;
6050 Result += ",\n";
6051 }
6052 else
6053 Result += "\t0,\n";
6054
6055 if (ClassMethods.size() > 0) {
6056 Result += "\t(const struct _method_list_t *)&";
6057 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6058 Result += ClassName; Result += "_$_"; Result += CatName;
6059 Result += ",\n";
6060 }
6061 else
6062 Result += "\t0,\n";
6063
6064 if (RefedProtocols.size() > 0) {
6065 Result += "\t(const struct _protocol_list_t *)&";
6066 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6067 Result += ClassName; Result += "_$_"; Result += CatName;
6068 Result += ",\n";
6069 }
6070 else
6071 Result += "\t0,\n";
6072
6073 if (ClassProperties.size() > 0) {
6074 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6075 Result += ClassName; Result += "_$_"; Result += CatName;
6076 Result += ",\n";
6077 }
6078 else
6079 Result += "\t0,\n";
6080
6081 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006082
6083 // Add static function to initialize the class pointer in the category structure.
6084 Result += "static void OBJC_CATEGORY_SETUP_$_";
6085 Result += ClassDecl->getNameAsString();
6086 Result += "_$_";
6087 Result += CatName;
6088 Result += "(void ) {\n";
6089 Result += "\t_OBJC_$_CATEGORY_";
6090 Result += ClassDecl->getNameAsString();
6091 Result += "_$_";
6092 Result += CatName;
6093 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6094 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006095}
6096
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006097static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6098 ASTContext *Context, std::string &Result,
6099 ArrayRef<ObjCMethodDecl *> Methods,
6100 StringRef VarName,
6101 StringRef ProtocolName) {
6102 if (Methods.size() == 0)
6103 return;
6104
6105 Result += "\nstatic const char *";
6106 Result += VarName; Result += ProtocolName;
6107 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6108 Result += "{\n";
6109 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6110 ObjCMethodDecl *MD = Methods[i];
6111 std::string MethodTypeString, QuoteMethodTypeString;
6112 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6113 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6114 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6115 if (i == e-1)
6116 Result += "\n};\n";
6117 else {
6118 Result += ",\n";
6119 }
6120 }
6121}
6122
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006123static void Write_IvarOffsetVar(ASTContext *Context,
6124 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006125 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006126 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006127 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6128 // this is what happens:
6129 /**
6130 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6131 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6132 Class->getVisibility() == HiddenVisibility)
6133 Visibility shoud be: HiddenVisibility;
6134 else
6135 Visibility shoud be: DefaultVisibility;
6136 */
6137
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006138 Result += "\n";
6139 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6140 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006141 if (Context->getLangOpts().MicrosoftExt)
6142 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6143
6144 if (!Context->getLangOpts().MicrosoftExt ||
6145 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006146 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006147 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006148 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006149 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006150 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006151 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6152 Result += " = ";
6153 if (IvarDecl->isBitField()) {
6154 // FIXME: The hack below doesn't work for bitfields. For now, we simply
6155 // place all bitfields at offset 0.
6156 Result += "0;\n";
6157 }
6158 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006159 Result += "__OFFSETOFIVAR__(struct ";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006160 Result += CDecl->getNameAsString();
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006161 Result += "_IMPL, ";
6162 Result += IvarDecl->getName(); Result += ");\n";
6163 }
6164 }
6165}
6166
Fariborz Jahanianae932952012-02-10 20:47:10 +00006167static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6168 ASTContext *Context, std::string &Result,
6169 ArrayRef<ObjCIvarDecl *> Ivars,
6170 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006171 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanianae932952012-02-10 20:47:10 +00006172 if (Ivars.size() > 0) {
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006173 Write_IvarOffsetVar(Context, Result, Ivars, CDecl);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006174
Fariborz Jahanianae932952012-02-10 20:47:10 +00006175 Result += "\nstatic ";
6176 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6177 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006178 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006179 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6180 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6181 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6182 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6183 ObjCIvarDecl *IvarDecl = Ivars[i];
6184 if (i == 0)
6185 Result += "\t{{";
6186 else
6187 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006188 Result += "(unsigned long int *)&";
6189 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006190 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006191
6192 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
6193 std::string IvarTypeString, QuoteIvarTypeString;
6194 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
6195 IvarDecl);
6196 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6197 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6198
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006199 // FIXME. this alignment represents the host alignment and need be changed to
6200 // represent the target alignment.
6201 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
6202 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006203 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00006204 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
6205 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00006206 if (i == e-1)
6207 Result += "}}\n";
6208 else
6209 Result += "},\n";
6210 }
6211 Result += "};\n";
6212 }
6213}
6214
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006215/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006216void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6217 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006218
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006219 // Do not synthesize the protocol more than once.
6220 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6221 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006222 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006223
6224 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6225 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006226 // Must write out all protocol definitions in current qualifier list,
6227 // and in their nested qualifiers before writing out current definition.
6228 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6229 E = PDecl->protocol_end(); I != E; ++I)
6230 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006231
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006232 // Construct method lists.
6233 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6234 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6235 for (ObjCProtocolDecl::instmeth_iterator
6236 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
6237 I != E; ++I) {
6238 ObjCMethodDecl *MD = *I;
6239 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6240 OptInstanceMethods.push_back(MD);
6241 } else {
6242 InstanceMethods.push_back(MD);
6243 }
6244 }
6245
6246 for (ObjCProtocolDecl::classmeth_iterator
6247 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
6248 I != E; ++I) {
6249 ObjCMethodDecl *MD = *I;
6250 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6251 OptClassMethods.push_back(MD);
6252 } else {
6253 ClassMethods.push_back(MD);
6254 }
6255 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006256 std::vector<ObjCMethodDecl *> AllMethods;
6257 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6258 AllMethods.push_back(InstanceMethods[i]);
6259 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6260 AllMethods.push_back(ClassMethods[i]);
6261 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6262 AllMethods.push_back(OptInstanceMethods[i]);
6263 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6264 AllMethods.push_back(OptClassMethods[i]);
6265
6266 Write__extendedMethodTypes_initializer(*this, Context, Result,
6267 AllMethods,
6268 "_OBJC_PROTOCOL_METHOD_TYPES_",
6269 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006270 // Protocol's super protocol list
6271 std::vector<ObjCProtocolDecl *> SuperProtocols;
6272 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
6273 E = PDecl->protocol_end(); I != E; ++I)
6274 SuperProtocols.push_back(*I);
6275
6276 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6277 "_OBJC_PROTOCOL_REFS_",
6278 PDecl->getNameAsString());
6279
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006280 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006281 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006282 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006283
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006284 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006285 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006286 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006287
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006288 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006289 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006290 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006291
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006292 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006293 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006294 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006295
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006296 // Protocol's property metadata.
6297 std::vector<ObjCPropertyDecl *> ProtocolProperties;
6298 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
6299 E = PDecl->prop_end(); I != E; ++I)
6300 ProtocolProperties.push_back(*I);
6301
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006302 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006303 /* Container */0,
6304 "_OBJC_PROTOCOL_PROPERTIES_",
6305 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006306
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006307 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006308 Result += "\n";
6309 if (LangOpts.MicrosoftExt)
6310 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006311 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006312 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006313 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
6314 Result += "\t0,\n"; // id is; is null
6315 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006316 if (SuperProtocols.size() > 0) {
6317 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
6318 Result += PDecl->getNameAsString(); Result += ",\n";
6319 }
6320 else
6321 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006322 if (InstanceMethods.size() > 0) {
6323 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
6324 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006325 }
6326 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006327 Result += "\t0,\n";
6328
6329 if (ClassMethods.size() > 0) {
6330 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
6331 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006332 }
6333 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006334 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006335
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006336 if (OptInstanceMethods.size() > 0) {
6337 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
6338 Result += PDecl->getNameAsString(); Result += ",\n";
6339 }
6340 else
6341 Result += "\t0,\n";
6342
6343 if (OptClassMethods.size() > 0) {
6344 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
6345 Result += PDecl->getNameAsString(); Result += ",\n";
6346 }
6347 else
6348 Result += "\t0,\n";
6349
6350 if (ProtocolProperties.size() > 0) {
6351 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
6352 Result += PDecl->getNameAsString(); Result += ",\n";
6353 }
6354 else
6355 Result += "\t0,\n";
6356
6357 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
6358 Result += "\t0,\n";
6359
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006360 if (AllMethods.size() > 0) {
6361 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
6362 Result += PDecl->getNameAsString();
6363 Result += "\n};\n";
6364 }
6365 else
6366 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006367
6368 // Use this protocol meta-data to build protocol list table in section
6369 // .objc_protolist$B
6370 // Unspecified visibility means 'private extern'.
6371 if (LangOpts.MicrosoftExt)
6372 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6373 Result += "struct _protocol_t *";
6374 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6375 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6376 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006377
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006378 // Mark this protocol as having been generated.
6379 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6380 llvm_unreachable("protocol already synthesized");
6381
6382}
6383
6384void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6385 const ObjCList<ObjCProtocolDecl> &Protocols,
6386 StringRef prefix, StringRef ClassName,
6387 std::string &Result) {
6388 if (Protocols.empty()) return;
6389
6390 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006391 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006392
6393 // Output the top lovel protocol meta-data for the class.
6394 /* struct _objc_protocol_list {
6395 struct _objc_protocol_list *next;
6396 int protocol_count;
6397 struct _objc_protocol *class_protocols[];
6398 }
6399 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006400 Result += "\n";
6401 if (LangOpts.MicrosoftExt)
6402 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6403 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006404 Result += "\tstruct _objc_protocol_list *next;\n";
6405 Result += "\tint protocol_count;\n";
6406 Result += "\tstruct _objc_protocol *class_protocols[";
6407 Result += utostr(Protocols.size());
6408 Result += "];\n} _OBJC_";
6409 Result += prefix;
6410 Result += "_PROTOCOLS_";
6411 Result += ClassName;
6412 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6413 "{\n\t0, ";
6414 Result += utostr(Protocols.size());
6415 Result += "\n";
6416
6417 Result += "\t,{&_OBJC_PROTOCOL_";
6418 Result += Protocols[0]->getNameAsString();
6419 Result += " \n";
6420
6421 for (unsigned i = 1; i != Protocols.size(); i++) {
6422 Result += "\t ,&_OBJC_PROTOCOL_";
6423 Result += Protocols[i]->getNameAsString();
6424 Result += "\n";
6425 }
6426 Result += "\t }\n};\n";
6427}
6428
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006429/// hasObjCExceptionAttribute - Return true if this class or any super
6430/// class has the __objc_exception__ attribute.
6431/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6432static bool hasObjCExceptionAttribute(ASTContext &Context,
6433 const ObjCInterfaceDecl *OID) {
6434 if (OID->hasAttr<ObjCExceptionAttr>())
6435 return true;
6436 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6437 return hasObjCExceptionAttribute(Context, Super);
6438 return false;
6439}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006440
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006441void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6442 std::string &Result) {
6443 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6444
6445 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006446 if (CDecl->isImplicitInterfaceDecl())
6447 assert(false &&
6448 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006449
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006450 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006451 SmallVector<ObjCIvarDecl *, 8> IVars;
6452
6453 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6454 IVD; IVD = IVD->getNextIvar()) {
6455 // Ignore unnamed bit-fields.
6456 if (!IVD->getDeclName())
6457 continue;
6458 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006459 }
6460
Fariborz Jahanianae932952012-02-10 20:47:10 +00006461 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006462 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006463 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006464
6465 // Build _objc_method_list for class's instance methods if needed
6466 SmallVector<ObjCMethodDecl *, 32>
6467 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6468
6469 // If any of our property implementations have associated getters or
6470 // setters, produce metadata for them as well.
6471 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6472 PropEnd = IDecl->propimpl_end();
6473 Prop != PropEnd; ++Prop) {
6474 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6475 continue;
6476 if (!(*Prop)->getPropertyIvarDecl())
6477 continue;
6478 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6479 if (!PD)
6480 continue;
6481 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6482 if (!Getter->isDefined())
6483 InstanceMethods.push_back(Getter);
6484 if (PD->isReadOnly())
6485 continue;
6486 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6487 if (!Setter->isDefined())
6488 InstanceMethods.push_back(Setter);
6489 }
6490
6491 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6492 "_OBJC_$_INSTANCE_METHODS_",
6493 IDecl->getNameAsString(), true);
6494
6495 SmallVector<ObjCMethodDecl *, 32>
6496 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6497
6498 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6499 "_OBJC_$_CLASS_METHODS_",
6500 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006501
6502 // Protocols referenced in class declaration?
6503 // Protocol's super protocol list
6504 std::vector<ObjCProtocolDecl *> RefedProtocols;
6505 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6506 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6507 E = Protocols.end();
6508 I != E; ++I) {
6509 RefedProtocols.push_back(*I);
6510 // Must write out all protocol definitions in current qualifier list,
6511 // and in their nested qualifiers before writing out current definition.
6512 RewriteObjCProtocolMetaData(*I, Result);
6513 }
6514
6515 Write_protocol_list_initializer(Context, Result,
6516 RefedProtocols,
6517 "_OBJC_CLASS_PROTOCOLS_$_",
6518 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006519
6520 // Protocol's property metadata.
6521 std::vector<ObjCPropertyDecl *> ClassProperties;
6522 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6523 E = CDecl->prop_end(); I != E; ++I)
6524 ClassProperties.push_back(*I);
6525
6526 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00006527 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006528 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006529 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006530
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006531
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006532 // Data for initializing _class_ro_t metaclass meta-data
6533 uint32_t flags = CLS_META;
6534 std::string InstanceSize;
6535 std::string InstanceStart;
6536
6537
6538 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6539 if (classIsHidden)
6540 flags |= OBJC2_CLS_HIDDEN;
6541
6542 if (!CDecl->getSuperClass())
6543 // class is root
6544 flags |= CLS_ROOT;
6545 InstanceSize = "sizeof(struct _class_t)";
6546 InstanceStart = InstanceSize;
6547 Write__class_ro_t_initializer(Context, Result, flags,
6548 InstanceStart, InstanceSize,
6549 ClassMethods,
6550 0,
6551 0,
6552 0,
6553 "_OBJC_METACLASS_RO_$_",
6554 CDecl->getNameAsString());
6555
6556
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006557 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006558 flags = CLS;
6559 if (classIsHidden)
6560 flags |= OBJC2_CLS_HIDDEN;
6561
6562 if (hasObjCExceptionAttribute(*Context, CDecl))
6563 flags |= CLS_EXCEPTION;
6564
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006565 if (!CDecl->getSuperClass())
6566 // class is root
6567 flags |= CLS_ROOT;
6568
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006569 InstanceSize.clear();
6570 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006571 if (!ObjCSynthesizedStructs.count(CDecl)) {
6572 InstanceSize = "0";
6573 InstanceStart = "0";
6574 }
6575 else {
6576 InstanceSize = "sizeof(struct ";
6577 InstanceSize += CDecl->getNameAsString();
6578 InstanceSize += "_IMPL)";
6579
6580 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6581 if (IVD) {
6582 InstanceStart += "__OFFSETOFIVAR__(struct ";
6583 InstanceStart += CDecl->getNameAsString();
6584 InstanceStart += "_IMPL, ";
6585 InstanceStart += IVD->getNameAsString();
6586 InstanceStart += ")";
6587 }
6588 else
6589 InstanceStart = InstanceSize;
6590 }
6591 Write__class_ro_t_initializer(Context, Result, flags,
6592 InstanceStart, InstanceSize,
6593 InstanceMethods,
6594 RefedProtocols,
6595 IVars,
6596 ClassProperties,
6597 "_OBJC_CLASS_RO_$_",
6598 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006599
6600 Write_class_t(Context, Result,
6601 "OBJC_METACLASS_$_",
6602 CDecl, /*metaclass*/true);
6603
6604 Write_class_t(Context, Result,
6605 "OBJC_CLASS_$_",
6606 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006607
6608 if (ImplementationIsNonLazy(IDecl))
6609 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006610
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006611}
6612
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006613void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
6614 int ClsDefCount = ClassImplementation.size();
6615 if (!ClsDefCount)
6616 return;
6617 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6618 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6619 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
6620 for (int i = 0; i < ClsDefCount; i++) {
6621 ObjCImplementationDecl *IDecl = ClassImplementation[i];
6622 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6623 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
6624 Result += CDecl->getName(); Result += ",\n";
6625 }
6626 Result += "};\n";
6627}
6628
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006629void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6630 int ClsDefCount = ClassImplementation.size();
6631 int CatDefCount = CategoryImplementation.size();
6632
6633 // For each implemented class, write out all its meta data.
6634 for (int i = 0; i < ClsDefCount; i++)
6635 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6636
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006637 RewriteClassSetupInitHook(Result);
6638
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006639 // For each implemented category, write out all its meta data.
6640 for (int i = 0; i < CatDefCount; i++)
6641 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6642
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006643 RewriteCategorySetupInitHook(Result);
6644
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006645 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006646 if (LangOpts.MicrosoftExt)
6647 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006648 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6649 Result += llvm::utostr(ClsDefCount); Result += "]";
6650 Result +=
6651 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6652 "regular,no_dead_strip\")))= {\n";
6653 for (int i = 0; i < ClsDefCount; i++) {
6654 Result += "\t&OBJC_CLASS_$_";
6655 Result += ClassImplementation[i]->getNameAsString();
6656 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006657 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006658 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006659
6660 if (!DefinedNonLazyClasses.empty()) {
6661 if (LangOpts.MicrosoftExt)
6662 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6663 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6664 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6665 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6666 Result += ",\n";
6667 }
6668 Result += "};\n";
6669 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006670 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006671
6672 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006673 if (LangOpts.MicrosoftExt)
6674 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006675 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6676 Result += llvm::utostr(CatDefCount); Result += "]";
6677 Result +=
6678 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6679 "regular,no_dead_strip\")))= {\n";
6680 for (int i = 0; i < CatDefCount; i++) {
6681 Result += "\t&_OBJC_$_CATEGORY_";
6682 Result +=
6683 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6684 Result += "_$_";
6685 Result += CategoryImplementation[i]->getNameAsString();
6686 Result += ",\n";
6687 }
6688 Result += "};\n";
6689 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006690
6691 if (!DefinedNonLazyCategories.empty()) {
6692 if (LangOpts.MicrosoftExt)
6693 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6694 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6695 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6696 Result += "\t&_OBJC_$_CATEGORY_";
6697 Result +=
6698 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6699 Result += "_$_";
6700 Result += DefinedNonLazyCategories[i]->getNameAsString();
6701 Result += ",\n";
6702 }
6703 Result += "};\n";
6704 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006705}
6706
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006707void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6708 if (LangOpts.MicrosoftExt)
6709 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6710
6711 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6712 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006713 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006714}
6715
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006716/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6717/// implementation.
6718void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6719 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006720 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006721 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6722 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006723 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006724 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6725 CDecl = CDecl->getNextClassCategory())
6726 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6727 break;
6728
6729 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006730 FullCategoryName += "_$_";
6731 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006732
6733 // Build _objc_method_list for class's instance methods if needed
6734 SmallVector<ObjCMethodDecl *, 32>
6735 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6736
6737 // If any of our property implementations have associated getters or
6738 // setters, produce metadata for them as well.
6739 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6740 PropEnd = IDecl->propimpl_end();
6741 Prop != PropEnd; ++Prop) {
6742 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6743 continue;
6744 if (!(*Prop)->getPropertyIvarDecl())
6745 continue;
6746 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6747 if (!PD)
6748 continue;
6749 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6750 InstanceMethods.push_back(Getter);
6751 if (PD->isReadOnly())
6752 continue;
6753 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6754 InstanceMethods.push_back(Setter);
6755 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006756
Fariborz Jahanian61186122012-02-17 18:40:41 +00006757 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6758 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6759 FullCategoryName, true);
6760
6761 SmallVector<ObjCMethodDecl *, 32>
6762 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6763
6764 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6765 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6766 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006767
6768 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006769 // Protocol's super protocol list
6770 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006771 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6772 E = CDecl->protocol_end();
6773
6774 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006775 RefedProtocols.push_back(*I);
6776 // Must write out all protocol definitions in current qualifier list,
6777 // and in their nested qualifiers before writing out current definition.
6778 RewriteObjCProtocolMetaData(*I, Result);
6779 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006780
Fariborz Jahanian61186122012-02-17 18:40:41 +00006781 Write_protocol_list_initializer(Context, Result,
6782 RefedProtocols,
6783 "_OBJC_CATEGORY_PROTOCOLS_$_",
6784 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006785
Fariborz Jahanian61186122012-02-17 18:40:41 +00006786 // Protocol's property metadata.
6787 std::vector<ObjCPropertyDecl *> ClassProperties;
6788 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6789 E = CDecl->prop_end(); I != E; ++I)
6790 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006791
Fariborz Jahanian61186122012-02-17 18:40:41 +00006792 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6793 /* Container */0,
6794 "_OBJC_$_PROP_LIST_",
6795 FullCategoryName);
6796
6797 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006798 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006799 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006800 InstanceMethods,
6801 ClassMethods,
6802 RefedProtocols,
6803 ClassProperties);
6804
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006805 // Determine if this category is also "non-lazy".
6806 if (ImplementationIsNonLazy(IDecl))
6807 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006808
6809}
6810
6811void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
6812 int CatDefCount = CategoryImplementation.size();
6813 if (!CatDefCount)
6814 return;
6815 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
6816 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
6817 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
6818 for (int i = 0; i < CatDefCount; i++) {
6819 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
6820 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
6821 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6822 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
6823 Result += ClassDecl->getName();
6824 Result += "_$_";
6825 Result += CatDecl->getName();
6826 Result += ",\n";
6827 }
6828 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006829}
6830
6831// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6832/// class methods.
6833template<typename MethodIterator>
6834void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6835 MethodIterator MethodEnd,
6836 bool IsInstanceMethod,
6837 StringRef prefix,
6838 StringRef ClassName,
6839 std::string &Result) {
6840 if (MethodBegin == MethodEnd) return;
6841
6842 if (!objc_impl_method) {
6843 /* struct _objc_method {
6844 SEL _cmd;
6845 char *method_types;
6846 void *_imp;
6847 }
6848 */
6849 Result += "\nstruct _objc_method {\n";
6850 Result += "\tSEL _cmd;\n";
6851 Result += "\tchar *method_types;\n";
6852 Result += "\tvoid *_imp;\n";
6853 Result += "};\n";
6854
6855 objc_impl_method = true;
6856 }
6857
6858 // Build _objc_method_list for class's methods if needed
6859
6860 /* struct {
6861 struct _objc_method_list *next_method;
6862 int method_count;
6863 struct _objc_method method_list[];
6864 }
6865 */
6866 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006867 Result += "\n";
6868 if (LangOpts.MicrosoftExt) {
6869 if (IsInstanceMethod)
6870 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6871 else
6872 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6873 }
6874 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006875 Result += "\tstruct _objc_method_list *next_method;\n";
6876 Result += "\tint method_count;\n";
6877 Result += "\tstruct _objc_method method_list[";
6878 Result += utostr(NumMethods);
6879 Result += "];\n} _OBJC_";
6880 Result += prefix;
6881 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6882 Result += "_METHODS_";
6883 Result += ClassName;
6884 Result += " __attribute__ ((used, section (\"__OBJC, __";
6885 Result += IsInstanceMethod ? "inst" : "cls";
6886 Result += "_meth\")))= ";
6887 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6888
6889 Result += "\t,{{(SEL)\"";
6890 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6891 std::string MethodTypeString;
6892 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6893 Result += "\", \"";
6894 Result += MethodTypeString;
6895 Result += "\", (void *)";
6896 Result += MethodInternalNames[*MethodBegin];
6897 Result += "}\n";
6898 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6899 Result += "\t ,{(SEL)\"";
6900 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6901 std::string MethodTypeString;
6902 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6903 Result += "\", \"";
6904 Result += MethodTypeString;
6905 Result += "\", (void *)";
6906 Result += MethodInternalNames[*MethodBegin];
6907 Result += "}\n";
6908 }
6909 Result += "\t }\n};\n";
6910}
6911
6912Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6913 SourceRange OldRange = IV->getSourceRange();
6914 Expr *BaseExpr = IV->getBase();
6915
6916 // Rewrite the base, but without actually doing replaces.
6917 {
6918 DisableReplaceStmtScope S(*this);
6919 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6920 IV->setBase(BaseExpr);
6921 }
6922
6923 ObjCIvarDecl *D = IV->getDecl();
6924
6925 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006926
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006927 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6928 const ObjCInterfaceType *iFaceDecl =
6929 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6930 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6931 // lookup which class implements the instance variable.
6932 ObjCInterfaceDecl *clsDeclared = 0;
6933 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6934 clsDeclared);
6935 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6936
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006937 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006938 std::string IvarOffsetName;
6939 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
6940
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006941 ReferencedIvars[clsDeclared].insert(D);
6942
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006943 // cast offset to "char *".
6944 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6945 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006946 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006947 BaseExpr);
6948 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6949 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6950 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006951 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6952 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006953 SourceLocation());
6954 BinaryOperator *addExpr =
6955 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6956 Context->getPointerType(Context->CharTy),
6957 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006958 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006959 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6960 SourceLocation(),
6961 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006962 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006963 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006964 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006965
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006966 castExpr = NoTypeInfoCStyleCastExpr(Context,
6967 castT,
6968 CK_BitCast,
6969 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006970 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006971 VK_LValue, OK_Ordinary,
6972 SourceLocation());
6973 PE = new (Context) ParenExpr(OldRange.getBegin(),
6974 OldRange.getEnd(),
6975 Exp);
6976
6977 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006978 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006979
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006980 ReplaceStmtWithRange(IV, Replacement, OldRange);
6981 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006982}