blob: d3d8622b701c9ca4fa799c22484fbb851d4fa378 [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;
76 unsigned RewriteFailedDiag;
77 // ObjC string constant support.
78 unsigned NumObjCStringLiterals;
79 VarDecl *ConstantStringClassReference;
80 RecordDecl *NSStringRecord;
81
82 // ObjC foreach break/continue generation support.
83 int BcLabelCount;
84
85 unsigned TryFinallyContainsReturnDiag;
86 // Needed for super.
87 ObjCMethodDecl *CurMethodDef;
88 RecordDecl *SuperStructDecl;
89 RecordDecl *ConstantStringDecl;
90
91 FunctionDecl *MsgSendFunctionDecl;
92 FunctionDecl *MsgSendSuperFunctionDecl;
93 FunctionDecl *MsgSendStretFunctionDecl;
94 FunctionDecl *MsgSendSuperStretFunctionDecl;
95 FunctionDecl *MsgSendFpretFunctionDecl;
96 FunctionDecl *GetClassFunctionDecl;
97 FunctionDecl *GetMetaClassFunctionDecl;
98 FunctionDecl *GetSuperClassFunctionDecl;
99 FunctionDecl *SelGetUidFunctionDecl;
100 FunctionDecl *CFStringFunctionDecl;
101 FunctionDecl *SuperContructorFunctionDecl;
102 FunctionDecl *CurFunctionDef;
103 FunctionDecl *CurFunctionDeclToDeclareForBlock;
104
105 /* Misc. containers needed for meta-data rewrite. */
106 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
107 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
108 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
109 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000110 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000111 llvm::SmallPtrSet<TagDecl*, 8> TagsDefinedInIvarDecls;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000112 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000113 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
114 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
115
116 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
117 llvm::SmallVector<ObjCCategoryDecl*, 8> DefinedNonLazyCategories;
118
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000119 SmallVector<Stmt *, 32> Stmts;
120 SmallVector<int, 8> ObjCBcLabelNo;
121 // Remember all the @protocol(<expr>) expressions.
122 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
123
124 llvm::DenseSet<uint64_t> CopyDestroyCache;
125
126 // Block expressions.
127 SmallVector<BlockExpr *, 32> Blocks;
128 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000129 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000130
John McCallf4b88a42012-03-10 09:33:50 +0000131 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000132
133 // Block related declarations.
134 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
135 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
136 SmallVector<ValueDecl *, 8> BlockByRefDecls;
137 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
138 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
139 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
140 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
141
142 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000143 llvm::DenseMap<ObjCInterfaceDecl *,
144 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
145
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000146 // This maps an original source AST to it's rewritten form. This allows
147 // us to avoid rewriting the same node twice (which is very uncommon).
148 // This is needed to support some of the exotic property rewriting.
149 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
150
151 // Needed for header files being rewritten
152 bool IsHeader;
153 bool SilenceRewriteMacroWarning;
154 bool objc_impl_method;
155
156 bool DisableReplaceStmt;
157 class DisableReplaceStmtScope {
158 RewriteModernObjC &R;
159 bool SavedValue;
160
161 public:
162 DisableReplaceStmtScope(RewriteModernObjC &R)
163 : R(R), SavedValue(R.DisableReplaceStmt) {
164 R.DisableReplaceStmt = true;
165 }
166 ~DisableReplaceStmtScope() {
167 R.DisableReplaceStmt = SavedValue;
168 }
169 };
170 void InitializeCommon(ASTContext &context);
171
172 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000173 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000174 // Top Level Driver code.
175 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
176 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
177 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
178 if (!Class->isThisDeclarationADefinition()) {
179 RewriteForwardClassDecl(D);
180 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000181 } else {
182 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000183 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000184 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000185 }
186 }
187
188 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
189 if (!Proto->isThisDeclarationADefinition()) {
190 RewriteForwardProtocolDecl(D);
191 break;
192 }
193 }
194
195 HandleTopLevelSingleDecl(*I);
196 }
197 return true;
198 }
199 void HandleTopLevelSingleDecl(Decl *D);
200 void HandleDeclInMainFile(Decl *D);
201 RewriteModernObjC(std::string inFile, raw_ostream *OS,
202 DiagnosticsEngine &D, const LangOptions &LOpts,
203 bool silenceMacroWarn);
204
205 ~RewriteModernObjC() {}
206
207 virtual void HandleTranslationUnit(ASTContext &C);
208
209 void ReplaceStmt(Stmt *Old, Stmt *New) {
210 Stmt *ReplacingStmt = ReplacedNodes[Old];
211
212 if (ReplacingStmt)
213 return; // We can't rewrite the same node twice.
214
215 if (DisableReplaceStmt)
216 return;
217
218 // If replacement succeeded or warning disabled return with no warning.
219 if (!Rewrite.ReplaceStmt(Old, New)) {
220 ReplacedNodes[Old] = New;
221 return;
222 }
223 if (SilenceRewriteMacroWarning)
224 return;
225 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
226 << Old->getSourceRange();
227 }
228
229 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
230 if (DisableReplaceStmt)
231 return;
232
233 // Measure the old text.
234 int Size = Rewrite.getRangeSize(SrcRange);
235 if (Size == -1) {
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
238 return;
239 }
240 // Get the new text.
241 std::string SStr;
242 llvm::raw_string_ostream S(SStr);
243 New->printPretty(S, *Context, 0, PrintingPolicy(LangOpts));
244 const std::string &Str = S.str();
245
246 // If replacement succeeded or warning disabled return with no warning.
247 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
248 ReplacedNodes[Old] = New;
249 return;
250 }
251 if (SilenceRewriteMacroWarning)
252 return;
253 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
254 << Old->getSourceRange();
255 }
256
257 void InsertText(SourceLocation Loc, StringRef Str,
258 bool InsertAfter = true) {
259 // If insertion succeeded or warning disabled return with no warning.
260 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
261 SilenceRewriteMacroWarning)
262 return;
263
264 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
265 }
266
267 void ReplaceText(SourceLocation Start, unsigned OrigLength,
268 StringRef Str) {
269 // If removal succeeded or warning disabled return with no warning.
270 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
271 SilenceRewriteMacroWarning)
272 return;
273
274 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
275 }
276
277 // Syntactic Rewriting.
278 void RewriteRecordBody(RecordDecl *RD);
279 void RewriteInclude();
280 void RewriteForwardClassDecl(DeclGroupRef D);
281 void RewriteForwardClassDecl(const llvm::SmallVector<Decl*, 8> &DG);
282 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
283 const std::string &typedefString);
284 void RewriteImplementations();
285 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
286 ObjCImplementationDecl *IMD,
287 ObjCCategoryImplDecl *CID);
288 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
289 void RewriteImplementationDecl(Decl *Dcl);
290 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
291 ObjCMethodDecl *MDecl, std::string &ResultStr);
292 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
293 const FunctionType *&FPRetType);
294 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
295 ValueDecl *VD, bool def=false);
296 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
297 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
298 void RewriteForwardProtocolDecl(DeclGroupRef D);
299 void RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG);
300 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
301 void RewriteProperty(ObjCPropertyDecl *prop);
302 void RewriteFunctionDecl(FunctionDecl *FD);
303 void RewriteBlockPointerType(std::string& Str, QualType Type);
304 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
305 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
306 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
307 void RewriteTypeOfDecl(VarDecl *VD);
308 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
309
310 // Expression Rewriting.
311 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
312 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
313 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
314 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
315 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
316 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
317 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
318 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000319 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
320 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
321 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
322 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
323 SourceLocation OrigEnd);
324 Stmt *RewriteBreakStmt(BreakStmt *S);
325 Stmt *RewriteContinueStmt(ContinueStmt *S);
326 void RewriteCastExpr(CStyleCastExpr *CE);
327
328 // Block rewriting.
329 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
330
331 // Block specific rewrite rules.
332 void RewriteBlockPointerDecl(NamedDecl *VD);
333 void RewriteByRefVar(VarDecl *VD);
John McCallf4b88a42012-03-10 09:33:50 +0000334 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000335 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
336 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
337
338 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
339 std::string &Result);
340
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000341 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
342
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000343 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
344
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000345 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
346 std::string &Result);
347
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000348 virtual void Initialize(ASTContext &context);
349
350 // Misc. AST transformation routines. Somtimes they end up calling
351 // rewriting routines on the new ASTs.
352 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
353 Expr **args, unsigned nargs,
354 SourceLocation StartLoc=SourceLocation(),
355 SourceLocation EndLoc=SourceLocation());
356
357 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
358 SourceLocation StartLoc=SourceLocation(),
359 SourceLocation EndLoc=SourceLocation());
360
361 void SynthCountByEnumWithState(std::string &buf);
362 void SynthMsgSendFunctionDecl();
363 void SynthMsgSendSuperFunctionDecl();
364 void SynthMsgSendStretFunctionDecl();
365 void SynthMsgSendFpretFunctionDecl();
366 void SynthMsgSendSuperStretFunctionDecl();
367 void SynthGetClassFunctionDecl();
368 void SynthGetMetaClassFunctionDecl();
369 void SynthGetSuperClassFunctionDecl();
370 void SynthSelGetUidFunctionDecl();
371 void SynthSuperContructorFunctionDecl();
372
373 // Rewriting metadata
374 template<typename MethodIterator>
375 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
376 MethodIterator MethodEnd,
377 bool IsInstanceMethod,
378 StringRef prefix,
379 StringRef ClassName,
380 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000381 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
382 std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000383 virtual void RewriteObjCProtocolListMetaData(
384 const ObjCList<ObjCProtocolDecl> &Prots,
385 StringRef prefix, StringRef ClassName, std::string &Result);
386 virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
387 std::string &Result);
388 virtual void RewriteMetaDataIntoBuffer(std::string &Result);
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +0000389 virtual void WriteImageInfo(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000390 virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
391 std::string &Result);
392
393 // Rewriting ivar
394 virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
395 std::string &Result);
396 virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
397
398
399 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
400 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
401 StringRef funcName, std::string Tag);
402 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
403 StringRef funcName, std::string Tag);
404 std::string SynthesizeBlockImpl(BlockExpr *CE,
405 std::string Tag, std::string Desc);
406 std::string SynthesizeBlockDescriptor(std::string DescTag,
407 std::string ImplTag,
408 int i, StringRef funcName,
409 unsigned hasCopy);
410 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
411 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
412 StringRef FunName);
413 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
414 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000415 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000416
417 // Misc. helper routines.
418 QualType getProtocolType();
419 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000420 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
421 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
422 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
423
424 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
425 void CollectBlockDeclRefInfo(BlockExpr *Exp);
426 void GetBlockDeclRefExprs(Stmt *S);
427 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000428 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000429 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
430
431 // We avoid calling Type::isBlockPointerType(), since it operates on the
432 // canonical type. We only care if the top-level type is a closure pointer.
433 bool isTopLevelBlockPointerType(QualType T) {
434 return isa<BlockPointerType>(T);
435 }
436
437 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
438 /// to a function pointer type and upon success, returns true; false
439 /// otherwise.
440 bool convertBlockPointerToFunctionPointer(QualType &T) {
441 if (isTopLevelBlockPointerType(T)) {
442 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
443 T = Context->getPointerType(BPT->getPointeeType());
444 return true;
445 }
446 return false;
447 }
448
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000449 bool convertObjCTypeToCStyleType(QualType &T);
450
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000451 bool needToScanForQualifiers(QualType T);
452 QualType getSuperStructType();
453 QualType getConstantStringStructType();
454 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
455 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
456
457 void convertToUnqualifiedObjCType(QualType &T) {
458 if (T->isObjCQualifiedIdType())
459 T = Context->getObjCIdType();
460 else if (T->isObjCQualifiedClassType())
461 T = Context->getObjCClassType();
462 else if (T->isObjCObjectPointerType() &&
463 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
464 if (const ObjCObjectPointerType * OBJPT =
465 T->getAsObjCInterfacePointerType()) {
466 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
467 T = QualType(IFaceT, 0);
468 T = Context->getPointerType(T);
469 }
470 }
471 }
472
473 // FIXME: This predicate seems like it would be useful to add to ASTContext.
474 bool isObjCType(QualType T) {
475 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
476 return false;
477
478 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
479
480 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
481 OCT == Context->getCanonicalType(Context->getObjCClassType()))
482 return true;
483
484 if (const PointerType *PT = OCT->getAs<PointerType>()) {
485 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
486 PT->getPointeeType()->isObjCQualifiedIdType())
487 return true;
488 }
489 return false;
490 }
491 bool PointerTypeTakesAnyBlockArguments(QualType QT);
492 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
493 void GetExtentOfArgList(const char *Name, const char *&LParen,
494 const char *&RParen);
495
496 void QuoteDoublequotes(std::string &From, std::string &To) {
497 for (unsigned i = 0; i < From.length(); i++) {
498 if (From[i] == '"')
499 To += "\\\"";
500 else
501 To += From[i];
502 }
503 }
504
505 QualType getSimpleFunctionType(QualType result,
506 const QualType *args,
507 unsigned numArgs,
508 bool variadic = false) {
509 if (result == Context->getObjCInstanceType())
510 result = Context->getObjCIdType();
511 FunctionProtoType::ExtProtoInfo fpi;
512 fpi.Variadic = variadic;
513 return Context->getFunctionType(result, args, numArgs, fpi);
514 }
515
516 // Helper function: create a CStyleCastExpr with trivial type source info.
517 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
518 CastKind Kind, Expr *E) {
519 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
520 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
521 SourceLocation(), SourceLocation());
522 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000523
524 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
525 IdentifierInfo* II = &Context->Idents.get("load");
526 Selector LoadSel = Context->Selectors.getSelector(0, &II);
527 return OD->getClassMethod(LoadSel) != 0;
528 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000529 };
530
531}
532
533void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
534 NamedDecl *D) {
535 if (const FunctionProtoType *fproto
536 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
537 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
538 E = fproto->arg_type_end(); I && (I != E); ++I)
539 if (isTopLevelBlockPointerType(*I)) {
540 // All the args are checked/rewritten. Don't call twice!
541 RewriteBlockPointerDecl(D);
542 break;
543 }
544 }
545}
546
547void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
548 const PointerType *PT = funcType->getAs<PointerType>();
549 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
550 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
551}
552
553static bool IsHeaderFile(const std::string &Filename) {
554 std::string::size_type DotPos = Filename.rfind('.');
555
556 if (DotPos == std::string::npos) {
557 // no file extension
558 return false;
559 }
560
561 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
562 // C header: .h
563 // C++ header: .hh or .H;
564 return Ext == "h" || Ext == "hh" || Ext == "H";
565}
566
567RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
568 DiagnosticsEngine &D, const LangOptions &LOpts,
569 bool silenceMacroWarn)
570 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
571 SilenceRewriteMacroWarning(silenceMacroWarn) {
572 IsHeader = IsHeaderFile(inFile);
573 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
574 "rewriting sub-expression within a macro (may not be correct)");
575 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
576 DiagnosticsEngine::Warning,
577 "rewriter doesn't support user-specified control flow semantics "
578 "for @try/@finally (code may not execute properly)");
579}
580
581ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
582 raw_ostream* OS,
583 DiagnosticsEngine &Diags,
584 const LangOptions &LOpts,
585 bool SilenceRewriteMacroWarning) {
586 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
587}
588
589void RewriteModernObjC::InitializeCommon(ASTContext &context) {
590 Context = &context;
591 SM = &Context->getSourceManager();
592 TUDecl = Context->getTranslationUnitDecl();
593 MsgSendFunctionDecl = 0;
594 MsgSendSuperFunctionDecl = 0;
595 MsgSendStretFunctionDecl = 0;
596 MsgSendSuperStretFunctionDecl = 0;
597 MsgSendFpretFunctionDecl = 0;
598 GetClassFunctionDecl = 0;
599 GetMetaClassFunctionDecl = 0;
600 GetSuperClassFunctionDecl = 0;
601 SelGetUidFunctionDecl = 0;
602 CFStringFunctionDecl = 0;
603 ConstantStringClassReference = 0;
604 NSStringRecord = 0;
605 CurMethodDef = 0;
606 CurFunctionDef = 0;
607 CurFunctionDeclToDeclareForBlock = 0;
608 GlobalVarDecl = 0;
609 SuperStructDecl = 0;
610 ProtocolTypeDecl = 0;
611 ConstantStringDecl = 0;
612 BcLabelCount = 0;
613 SuperContructorFunctionDecl = 0;
614 NumObjCStringLiterals = 0;
615 PropParentMap = 0;
616 CurrentBody = 0;
617 DisableReplaceStmt = false;
618 objc_impl_method = false;
619
620 // Get the ID and start/end of the main file.
621 MainFileID = SM->getMainFileID();
622 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
623 MainFileStart = MainBuf->getBufferStart();
624 MainFileEnd = MainBuf->getBufferEnd();
625
David Blaikie4e4d0842012-03-11 07:00:24 +0000626 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000627}
628
629//===----------------------------------------------------------------------===//
630// Top Level Driver Code
631//===----------------------------------------------------------------------===//
632
633void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
634 if (Diags.hasErrorOccurred())
635 return;
636
637 // Two cases: either the decl could be in the main file, or it could be in a
638 // #included file. If the former, rewrite it now. If the later, check to see
639 // if we rewrote the #include/#import.
640 SourceLocation Loc = D->getLocation();
641 Loc = SM->getExpansionLoc(Loc);
642
643 // If this is for a builtin, ignore it.
644 if (Loc.isInvalid()) return;
645
646 // Look for built-in declarations that we need to refer during the rewrite.
647 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
648 RewriteFunctionDecl(FD);
649 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
650 // declared in <Foundation/NSString.h>
651 if (FVD->getName() == "_NSConstantStringClassReference") {
652 ConstantStringClassReference = FVD;
653 return;
654 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000655 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
656 RewriteCategoryDecl(CD);
657 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
658 if (PD->isThisDeclarationADefinition())
659 RewriteProtocolDecl(PD);
660 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
661 // Recurse into linkage specifications
662 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
663 DIEnd = LSD->decls_end();
664 DI != DIEnd; ) {
665 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
666 if (!IFace->isThisDeclarationADefinition()) {
667 SmallVector<Decl *, 8> DG;
668 SourceLocation StartLoc = IFace->getLocStart();
669 do {
670 if (isa<ObjCInterfaceDecl>(*DI) &&
671 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
672 StartLoc == (*DI)->getLocStart())
673 DG.push_back(*DI);
674 else
675 break;
676
677 ++DI;
678 } while (DI != DIEnd);
679 RewriteForwardClassDecl(DG);
680 continue;
681 }
682 }
683
684 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
685 if (!Proto->isThisDeclarationADefinition()) {
686 SmallVector<Decl *, 8> DG;
687 SourceLocation StartLoc = Proto->getLocStart();
688 do {
689 if (isa<ObjCProtocolDecl>(*DI) &&
690 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
691 StartLoc == (*DI)->getLocStart())
692 DG.push_back(*DI);
693 else
694 break;
695
696 ++DI;
697 } while (DI != DIEnd);
698 RewriteForwardProtocolDecl(DG);
699 continue;
700 }
701 }
702
703 HandleTopLevelSingleDecl(*DI);
704 ++DI;
705 }
706 }
707 // If we have a decl in the main file, see if we should rewrite it.
708 if (SM->isFromMainFile(Loc))
709 return HandleDeclInMainFile(D);
710}
711
712//===----------------------------------------------------------------------===//
713// Syntactic (non-AST) Rewriting Code
714//===----------------------------------------------------------------------===//
715
716void RewriteModernObjC::RewriteInclude() {
717 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
718 StringRef MainBuf = SM->getBufferData(MainFileID);
719 const char *MainBufStart = MainBuf.begin();
720 const char *MainBufEnd = MainBuf.end();
721 size_t ImportLen = strlen("import");
722
723 // Loop over the whole file, looking for includes.
724 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
725 if (*BufPtr == '#') {
726 if (++BufPtr == MainBufEnd)
727 return;
728 while (*BufPtr == ' ' || *BufPtr == '\t')
729 if (++BufPtr == MainBufEnd)
730 return;
731 if (!strncmp(BufPtr, "import", ImportLen)) {
732 // replace import with include
733 SourceLocation ImportLoc =
734 LocStart.getLocWithOffset(BufPtr-MainBufStart);
735 ReplaceText(ImportLoc, ImportLen, "include");
736 BufPtr += ImportLen;
737 }
738 }
739 }
740}
741
742static std::string getIvarAccessString(ObjCIvarDecl *OID) {
743 const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
744 std::string S;
745 S = "((struct ";
746 S += ClassDecl->getIdentifier()->getName();
747 S += "_IMPL *)self)->";
748 S += OID->getName();
749 return S;
750}
751
752void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
753 ObjCImplementationDecl *IMD,
754 ObjCCategoryImplDecl *CID) {
755 static bool objcGetPropertyDefined = false;
756 static bool objcSetPropertyDefined = false;
757 SourceLocation startLoc = PID->getLocStart();
758 InsertText(startLoc, "// ");
759 const char *startBuf = SM->getCharacterData(startLoc);
760 assert((*startBuf == '@') && "bogus @synthesize location");
761 const char *semiBuf = strchr(startBuf, ';');
762 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
763 SourceLocation onePastSemiLoc =
764 startLoc.getLocWithOffset(semiBuf-startBuf+1);
765
766 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
767 return; // FIXME: is this correct?
768
769 // Generate the 'getter' function.
770 ObjCPropertyDecl *PD = PID->getPropertyDecl();
771 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
772
773 if (!OID)
774 return;
775 unsigned Attributes = PD->getPropertyAttributes();
776 if (!PD->getGetterMethodDecl()->isDefined()) {
777 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
778 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
779 ObjCPropertyDecl::OBJC_PR_copy));
780 std::string Getr;
781 if (GenGetProperty && !objcGetPropertyDefined) {
782 objcGetPropertyDefined = true;
783 // FIXME. Is this attribute correct in all cases?
784 Getr = "\nextern \"C\" __declspec(dllimport) "
785 "id objc_getProperty(id, SEL, long, bool);\n";
786 }
787 RewriteObjCMethodDecl(OID->getContainingInterface(),
788 PD->getGetterMethodDecl(), Getr);
789 Getr += "{ ";
790 // Synthesize an explicit cast to gain access to the ivar.
791 // See objc-act.c:objc_synthesize_new_getter() for details.
792 if (GenGetProperty) {
793 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
794 Getr += "typedef ";
795 const FunctionType *FPRetType = 0;
796 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
797 FPRetType);
798 Getr += " _TYPE";
799 if (FPRetType) {
800 Getr += ")"; // close the precedence "scope" for "*".
801
802 // Now, emit the argument types (if any).
803 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
804 Getr += "(";
805 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
806 if (i) Getr += ", ";
807 std::string ParamStr = FT->getArgType(i).getAsString(
808 Context->getPrintingPolicy());
809 Getr += ParamStr;
810 }
811 if (FT->isVariadic()) {
812 if (FT->getNumArgs()) Getr += ", ";
813 Getr += "...";
814 }
815 Getr += ")";
816 } else
817 Getr += "()";
818 }
819 Getr += ";\n";
820 Getr += "return (_TYPE)";
821 Getr += "objc_getProperty(self, _cmd, ";
822 RewriteIvarOffsetComputation(OID, Getr);
823 Getr += ", 1)";
824 }
825 else
826 Getr += "return " + getIvarAccessString(OID);
827 Getr += "; }";
828 InsertText(onePastSemiLoc, Getr);
829 }
830
831 if (PD->isReadOnly() || PD->getSetterMethodDecl()->isDefined())
832 return;
833
834 // Generate the 'setter' function.
835 std::string Setr;
836 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
837 ObjCPropertyDecl::OBJC_PR_copy);
838 if (GenSetProperty && !objcSetPropertyDefined) {
839 objcSetPropertyDefined = true;
840 // FIXME. Is this attribute correct in all cases?
841 Setr = "\nextern \"C\" __declspec(dllimport) "
842 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
843 }
844
845 RewriteObjCMethodDecl(OID->getContainingInterface(),
846 PD->getSetterMethodDecl(), Setr);
847 Setr += "{ ";
848 // Synthesize an explicit cast to initialize the ivar.
849 // See objc-act.c:objc_synthesize_new_setter() for details.
850 if (GenSetProperty) {
851 Setr += "objc_setProperty (self, _cmd, ";
852 RewriteIvarOffsetComputation(OID, Setr);
853 Setr += ", (id)";
854 Setr += PD->getName();
855 Setr += ", ";
856 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
857 Setr += "0, ";
858 else
859 Setr += "1, ";
860 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
861 Setr += "1)";
862 else
863 Setr += "0)";
864 }
865 else {
866 Setr += getIvarAccessString(OID) + " = ";
867 Setr += PD->getName();
868 }
869 Setr += "; }";
870 InsertText(onePastSemiLoc, Setr);
871}
872
873static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
874 std::string &typedefString) {
875 typedefString += "#ifndef _REWRITER_typedef_";
876 typedefString += ForwardDecl->getNameAsString();
877 typedefString += "\n";
878 typedefString += "#define _REWRITER_typedef_";
879 typedefString += ForwardDecl->getNameAsString();
880 typedefString += "\n";
881 typedefString += "typedef struct objc_object ";
882 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +0000883 // typedef struct { } _objc_exc_Classname;
884 typedefString += ";\ntypedef struct {} _objc_exc_";
885 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000886 typedefString += ";\n#endif\n";
887}
888
889void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
890 const std::string &typedefString) {
891 SourceLocation startLoc = ClassDecl->getLocStart();
892 const char *startBuf = SM->getCharacterData(startLoc);
893 const char *semiPtr = strchr(startBuf, ';');
894 // Replace the @class with typedefs corresponding to the classes.
895 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
896}
897
898void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
899 std::string typedefString;
900 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
901 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
902 if (I == D.begin()) {
903 // Translate to typedef's that forward reference structs with the same name
904 // as the class. As a convenience, we include the original declaration
905 // as a comment.
906 typedefString += "// @class ";
907 typedefString += ForwardDecl->getNameAsString();
908 typedefString += ";\n";
909 }
910 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
911 }
912 DeclGroupRef::iterator I = D.begin();
913 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
914}
915
916void RewriteModernObjC::RewriteForwardClassDecl(
917 const llvm::SmallVector<Decl*, 8> &D) {
918 std::string typedefString;
919 for (unsigned i = 0; i < D.size(); i++) {
920 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
921 if (i == 0) {
922 typedefString += "// @class ";
923 typedefString += ForwardDecl->getNameAsString();
924 typedefString += ";\n";
925 }
926 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
927 }
928 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
929}
930
931void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
932 // When method is a synthesized one, such as a getter/setter there is
933 // nothing to rewrite.
934 if (Method->isImplicit())
935 return;
936 SourceLocation LocStart = Method->getLocStart();
937 SourceLocation LocEnd = Method->getLocEnd();
938
939 if (SM->getExpansionLineNumber(LocEnd) >
940 SM->getExpansionLineNumber(LocStart)) {
941 InsertText(LocStart, "#if 0\n");
942 ReplaceText(LocEnd, 1, ";\n#endif\n");
943 } else {
944 InsertText(LocStart, "// ");
945 }
946}
947
948void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
949 SourceLocation Loc = prop->getAtLoc();
950
951 ReplaceText(Loc, 0, "// ");
952 // FIXME: handle properties that are declared across multiple lines.
953}
954
955void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
956 SourceLocation LocStart = CatDecl->getLocStart();
957
958 // FIXME: handle category headers that are declared across multiple lines.
959 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000960 if (CatDecl->getIvarLBraceLoc().isValid())
961 InsertText(CatDecl->getIvarLBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +0000962 for (ObjCCategoryDecl::ivar_iterator
963 I = CatDecl->ivar_begin(), E = CatDecl->ivar_end(); I != E; ++I) {
964 ObjCIvarDecl *Ivar = (*I);
965 SourceLocation LocStart = Ivar->getLocStart();
966 ReplaceText(LocStart, 0, "// ");
967 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +0000968 if (CatDecl->getIvarRBraceLoc().isValid())
969 InsertText(CatDecl->getIvarRBraceLoc(), "// ");
970
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000971 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
972 E = CatDecl->prop_end(); I != E; ++I)
973 RewriteProperty(*I);
974
975 for (ObjCCategoryDecl::instmeth_iterator
976 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
977 I != E; ++I)
978 RewriteMethodDeclaration(*I);
979 for (ObjCCategoryDecl::classmeth_iterator
980 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
981 I != E; ++I)
982 RewriteMethodDeclaration(*I);
983
984 // Lastly, comment out the @end.
985 ReplaceText(CatDecl->getAtEndRange().getBegin(),
986 strlen("@end"), "/* @end */");
987}
988
989void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
990 SourceLocation LocStart = PDecl->getLocStart();
991 assert(PDecl->isThisDeclarationADefinition());
992
993 // FIXME: handle protocol headers that are declared across multiple lines.
994 ReplaceText(LocStart, 0, "// ");
995
996 for (ObjCProtocolDecl::instmeth_iterator
997 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
998 I != E; ++I)
999 RewriteMethodDeclaration(*I);
1000 for (ObjCProtocolDecl::classmeth_iterator
1001 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1002 I != E; ++I)
1003 RewriteMethodDeclaration(*I);
1004
1005 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1006 E = PDecl->prop_end(); I != E; ++I)
1007 RewriteProperty(*I);
1008
1009 // Lastly, comment out the @end.
1010 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1011 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1012
1013 // Must comment out @optional/@required
1014 const char *startBuf = SM->getCharacterData(LocStart);
1015 const char *endBuf = SM->getCharacterData(LocEnd);
1016 for (const char *p = startBuf; p < endBuf; p++) {
1017 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1018 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1019 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1020
1021 }
1022 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1023 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1024 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1025
1026 }
1027 }
1028}
1029
1030void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1031 SourceLocation LocStart = (*D.begin())->getLocStart();
1032 if (LocStart.isInvalid())
1033 llvm_unreachable("Invalid SourceLocation");
1034 // FIXME: handle forward protocol that are declared across multiple lines.
1035 ReplaceText(LocStart, 0, "// ");
1036}
1037
1038void
1039RewriteModernObjC::RewriteForwardProtocolDecl(const llvm::SmallVector<Decl*, 8> &DG) {
1040 SourceLocation LocStart = DG[0]->getLocStart();
1041 if (LocStart.isInvalid())
1042 llvm_unreachable("Invalid SourceLocation");
1043 // FIXME: handle forward protocol that are declared across multiple lines.
1044 ReplaceText(LocStart, 0, "// ");
1045}
1046
1047void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1048 const FunctionType *&FPRetType) {
1049 if (T->isObjCQualifiedIdType())
1050 ResultStr += "id";
1051 else if (T->isFunctionPointerType() ||
1052 T->isBlockPointerType()) {
1053 // needs special handling, since pointer-to-functions have special
1054 // syntax (where a decaration models use).
1055 QualType retType = T;
1056 QualType PointeeTy;
1057 if (const PointerType* PT = retType->getAs<PointerType>())
1058 PointeeTy = PT->getPointeeType();
1059 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1060 PointeeTy = BPT->getPointeeType();
1061 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1062 ResultStr += FPRetType->getResultType().getAsString(
1063 Context->getPrintingPolicy());
1064 ResultStr += "(*";
1065 }
1066 } else
1067 ResultStr += T.getAsString(Context->getPrintingPolicy());
1068}
1069
1070void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1071 ObjCMethodDecl *OMD,
1072 std::string &ResultStr) {
1073 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1074 const FunctionType *FPRetType = 0;
1075 ResultStr += "\nstatic ";
1076 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1077 ResultStr += " ";
1078
1079 // Unique method name
1080 std::string NameStr;
1081
1082 if (OMD->isInstanceMethod())
1083 NameStr += "_I_";
1084 else
1085 NameStr += "_C_";
1086
1087 NameStr += IDecl->getNameAsString();
1088 NameStr += "_";
1089
1090 if (ObjCCategoryImplDecl *CID =
1091 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1092 NameStr += CID->getNameAsString();
1093 NameStr += "_";
1094 }
1095 // Append selector names, replacing ':' with '_'
1096 {
1097 std::string selString = OMD->getSelector().getAsString();
1098 int len = selString.size();
1099 for (int i = 0; i < len; i++)
1100 if (selString[i] == ':')
1101 selString[i] = '_';
1102 NameStr += selString;
1103 }
1104 // Remember this name for metadata emission
1105 MethodInternalNames[OMD] = NameStr;
1106 ResultStr += NameStr;
1107
1108 // Rewrite arguments
1109 ResultStr += "(";
1110
1111 // invisible arguments
1112 if (OMD->isInstanceMethod()) {
1113 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1114 selfTy = Context->getPointerType(selfTy);
1115 if (!LangOpts.MicrosoftExt) {
1116 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1117 ResultStr += "struct ";
1118 }
1119 // When rewriting for Microsoft, explicitly omit the structure name.
1120 ResultStr += IDecl->getNameAsString();
1121 ResultStr += " *";
1122 }
1123 else
1124 ResultStr += Context->getObjCClassType().getAsString(
1125 Context->getPrintingPolicy());
1126
1127 ResultStr += " self, ";
1128 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1129 ResultStr += " _cmd";
1130
1131 // Method arguments.
1132 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1133 E = OMD->param_end(); PI != E; ++PI) {
1134 ParmVarDecl *PDecl = *PI;
1135 ResultStr += ", ";
1136 if (PDecl->getType()->isObjCQualifiedIdType()) {
1137 ResultStr += "id ";
1138 ResultStr += PDecl->getNameAsString();
1139 } else {
1140 std::string Name = PDecl->getNameAsString();
1141 QualType QT = PDecl->getType();
1142 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1143 if (convertBlockPointerToFunctionPointer(QT))
1144 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1145 else
1146 PDecl->getType().getAsStringInternal(Name, Context->getPrintingPolicy());
1147 ResultStr += Name;
1148 }
1149 }
1150 if (OMD->isVariadic())
1151 ResultStr += ", ...";
1152 ResultStr += ") ";
1153
1154 if (FPRetType) {
1155 ResultStr += ")"; // close the precedence "scope" for "*".
1156
1157 // Now, emit the argument types (if any).
1158 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1159 ResultStr += "(";
1160 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1161 if (i) ResultStr += ", ";
1162 std::string ParamStr = FT->getArgType(i).getAsString(
1163 Context->getPrintingPolicy());
1164 ResultStr += ParamStr;
1165 }
1166 if (FT->isVariadic()) {
1167 if (FT->getNumArgs()) ResultStr += ", ";
1168 ResultStr += "...";
1169 }
1170 ResultStr += ")";
1171 } else {
1172 ResultStr += "()";
1173 }
1174 }
1175}
1176void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1177 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1178 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1179
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001180 if (IMD) {
1181 InsertText(IMD->getLocStart(), "// ");
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001182 if (IMD->getIvarLBraceLoc().isValid())
1183 InsertText(IMD->getIvarLBraceLoc(), "// ");
1184 for (ObjCImplementationDecl::ivar_iterator
1185 I = IMD->ivar_begin(), E = IMD->ivar_end(); I != E; ++I) {
1186 ObjCIvarDecl *Ivar = (*I);
1187 SourceLocation LocStart = Ivar->getLocStart();
1188 ReplaceText(LocStart, 0, "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001189 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001190 if (IMD->getIvarRBraceLoc().isValid())
1191 InsertText(IMD->getIvarRBraceLoc(), "// ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001192 }
1193 else
1194 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001195
1196 for (ObjCCategoryImplDecl::instmeth_iterator
1197 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1198 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1199 I != E; ++I) {
1200 std::string ResultStr;
1201 ObjCMethodDecl *OMD = *I;
1202 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1203 SourceLocation LocStart = OMD->getLocStart();
1204 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1205
1206 const char *startBuf = SM->getCharacterData(LocStart);
1207 const char *endBuf = SM->getCharacterData(LocEnd);
1208 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1209 }
1210
1211 for (ObjCCategoryImplDecl::classmeth_iterator
1212 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1213 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1214 I != E; ++I) {
1215 std::string ResultStr;
1216 ObjCMethodDecl *OMD = *I;
1217 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1218 SourceLocation LocStart = OMD->getLocStart();
1219 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1220
1221 const char *startBuf = SM->getCharacterData(LocStart);
1222 const char *endBuf = SM->getCharacterData(LocEnd);
1223 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1224 }
1225 for (ObjCCategoryImplDecl::propimpl_iterator
1226 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1227 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1228 I != E; ++I) {
1229 RewritePropertyImplDecl(*I, IMD, CID);
1230 }
1231
1232 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1233}
1234
1235void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001236 // Do not synthesize more than once.
1237 if (ObjCSynthesizedStructs.count(ClassDecl))
1238 return;
1239 // Make sure super class's are written before current class is written.
1240 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1241 while (SuperClass) {
1242 RewriteInterfaceDecl(SuperClass);
1243 SuperClass = SuperClass->getSuperClass();
1244 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001245 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001246 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001247 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001248 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001249 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1250
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001251 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001252 // Mark this typedef as having been written into its c++ equivalent.
1253 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001254
1255 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001256 E = ClassDecl->prop_end(); I != E; ++I)
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001257 RewriteProperty(*I);
1258 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001259 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001260 I != E; ++I)
1261 RewriteMethodDeclaration(*I);
1262 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001263 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001264 I != E; ++I)
1265 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001266
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001267 // Lastly, comment out the @end.
1268 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1269 "/* @end */");
1270 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001271}
1272
1273Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1274 SourceRange OldRange = PseudoOp->getSourceRange();
1275
1276 // We just magically know some things about the structure of this
1277 // expression.
1278 ObjCMessageExpr *OldMsg =
1279 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1280 PseudoOp->getNumSemanticExprs() - 1));
1281
1282 // Because the rewriter doesn't allow us to rewrite rewritten code,
1283 // we need to suppress rewriting the sub-statements.
1284 Expr *Base, *RHS;
1285 {
1286 DisableReplaceStmtScope S(*this);
1287
1288 // Rebuild the base expression if we have one.
1289 Base = 0;
1290 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1291 Base = OldMsg->getInstanceReceiver();
1292 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1293 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1294 }
1295
1296 // Rebuild the RHS.
1297 RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1298 RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1299 RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1300 }
1301
1302 // TODO: avoid this copy.
1303 SmallVector<SourceLocation, 1> SelLocs;
1304 OldMsg->getSelectorLocs(SelLocs);
1305
1306 ObjCMessageExpr *NewMsg = 0;
1307 switch (OldMsg->getReceiverKind()) {
1308 case ObjCMessageExpr::Class:
1309 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1310 OldMsg->getValueKind(),
1311 OldMsg->getLeftLoc(),
1312 OldMsg->getClassReceiverTypeInfo(),
1313 OldMsg->getSelector(),
1314 SelLocs,
1315 OldMsg->getMethodDecl(),
1316 RHS,
1317 OldMsg->getRightLoc(),
1318 OldMsg->isImplicit());
1319 break;
1320
1321 case ObjCMessageExpr::Instance:
1322 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1323 OldMsg->getValueKind(),
1324 OldMsg->getLeftLoc(),
1325 Base,
1326 OldMsg->getSelector(),
1327 SelLocs,
1328 OldMsg->getMethodDecl(),
1329 RHS,
1330 OldMsg->getRightLoc(),
1331 OldMsg->isImplicit());
1332 break;
1333
1334 case ObjCMessageExpr::SuperClass:
1335 case ObjCMessageExpr::SuperInstance:
1336 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1337 OldMsg->getValueKind(),
1338 OldMsg->getLeftLoc(),
1339 OldMsg->getSuperLoc(),
1340 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1341 OldMsg->getSuperType(),
1342 OldMsg->getSelector(),
1343 SelLocs,
1344 OldMsg->getMethodDecl(),
1345 RHS,
1346 OldMsg->getRightLoc(),
1347 OldMsg->isImplicit());
1348 break;
1349 }
1350
1351 Stmt *Replacement = SynthMessageExpr(NewMsg);
1352 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1353 return Replacement;
1354}
1355
1356Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1357 SourceRange OldRange = PseudoOp->getSourceRange();
1358
1359 // We just magically know some things about the structure of this
1360 // expression.
1361 ObjCMessageExpr *OldMsg =
1362 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1363
1364 // Because the rewriter doesn't allow us to rewrite rewritten code,
1365 // we need to suppress rewriting the sub-statements.
1366 Expr *Base = 0;
1367 {
1368 DisableReplaceStmtScope S(*this);
1369
1370 // Rebuild the base expression if we have one.
1371 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1372 Base = OldMsg->getInstanceReceiver();
1373 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1374 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1375 }
1376 }
1377
1378 // Intentionally empty.
1379 SmallVector<SourceLocation, 1> SelLocs;
1380 SmallVector<Expr*, 1> Args;
1381
1382 ObjCMessageExpr *NewMsg = 0;
1383 switch (OldMsg->getReceiverKind()) {
1384 case ObjCMessageExpr::Class:
1385 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1386 OldMsg->getValueKind(),
1387 OldMsg->getLeftLoc(),
1388 OldMsg->getClassReceiverTypeInfo(),
1389 OldMsg->getSelector(),
1390 SelLocs,
1391 OldMsg->getMethodDecl(),
1392 Args,
1393 OldMsg->getRightLoc(),
1394 OldMsg->isImplicit());
1395 break;
1396
1397 case ObjCMessageExpr::Instance:
1398 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1399 OldMsg->getValueKind(),
1400 OldMsg->getLeftLoc(),
1401 Base,
1402 OldMsg->getSelector(),
1403 SelLocs,
1404 OldMsg->getMethodDecl(),
1405 Args,
1406 OldMsg->getRightLoc(),
1407 OldMsg->isImplicit());
1408 break;
1409
1410 case ObjCMessageExpr::SuperClass:
1411 case ObjCMessageExpr::SuperInstance:
1412 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1413 OldMsg->getValueKind(),
1414 OldMsg->getLeftLoc(),
1415 OldMsg->getSuperLoc(),
1416 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1417 OldMsg->getSuperType(),
1418 OldMsg->getSelector(),
1419 SelLocs,
1420 OldMsg->getMethodDecl(),
1421 Args,
1422 OldMsg->getRightLoc(),
1423 OldMsg->isImplicit());
1424 break;
1425 }
1426
1427 Stmt *Replacement = SynthMessageExpr(NewMsg);
1428 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1429 return Replacement;
1430}
1431
1432/// SynthCountByEnumWithState - To print:
1433/// ((unsigned int (*)
1434/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1435/// (void *)objc_msgSend)((id)l_collection,
1436/// sel_registerName(
1437/// "countByEnumeratingWithState:objects:count:"),
1438/// &enumState,
1439/// (id *)__rw_items, (unsigned int)16)
1440///
1441void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1442 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1443 "id *, unsigned int))(void *)objc_msgSend)";
1444 buf += "\n\t\t";
1445 buf += "((id)l_collection,\n\t\t";
1446 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1447 buf += "\n\t\t";
1448 buf += "&enumState, "
1449 "(id *)__rw_items, (unsigned int)16)";
1450}
1451
1452/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1453/// statement to exit to its outer synthesized loop.
1454///
1455Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1456 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1457 return S;
1458 // replace break with goto __break_label
1459 std::string buf;
1460
1461 SourceLocation startLoc = S->getLocStart();
1462 buf = "goto __break_label_";
1463 buf += utostr(ObjCBcLabelNo.back());
1464 ReplaceText(startLoc, strlen("break"), buf);
1465
1466 return 0;
1467}
1468
1469/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1470/// statement to continue with its inner synthesized loop.
1471///
1472Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1473 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1474 return S;
1475 // replace continue with goto __continue_label
1476 std::string buf;
1477
1478 SourceLocation startLoc = S->getLocStart();
1479 buf = "goto __continue_label_";
1480 buf += utostr(ObjCBcLabelNo.back());
1481 ReplaceText(startLoc, strlen("continue"), buf);
1482
1483 return 0;
1484}
1485
1486/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1487/// It rewrites:
1488/// for ( type elem in collection) { stmts; }
1489
1490/// Into:
1491/// {
1492/// type elem;
1493/// struct __objcFastEnumerationState enumState = { 0 };
1494/// id __rw_items[16];
1495/// id l_collection = (id)collection;
1496/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1497/// objects:__rw_items count:16];
1498/// if (limit) {
1499/// unsigned long startMutations = *enumState.mutationsPtr;
1500/// do {
1501/// unsigned long counter = 0;
1502/// do {
1503/// if (startMutations != *enumState.mutationsPtr)
1504/// objc_enumerationMutation(l_collection);
1505/// elem = (type)enumState.itemsPtr[counter++];
1506/// stmts;
1507/// __continue_label: ;
1508/// } while (counter < limit);
1509/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1510/// objects:__rw_items count:16]);
1511/// elem = nil;
1512/// __break_label: ;
1513/// }
1514/// else
1515/// elem = nil;
1516/// }
1517///
1518Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1519 SourceLocation OrigEnd) {
1520 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1521 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1522 "ObjCForCollectionStmt Statement stack mismatch");
1523 assert(!ObjCBcLabelNo.empty() &&
1524 "ObjCForCollectionStmt - Label No stack empty");
1525
1526 SourceLocation startLoc = S->getLocStart();
1527 const char *startBuf = SM->getCharacterData(startLoc);
1528 StringRef elementName;
1529 std::string elementTypeAsString;
1530 std::string buf;
1531 buf = "\n{\n\t";
1532 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1533 // type elem;
1534 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1535 QualType ElementType = cast<ValueDecl>(D)->getType();
1536 if (ElementType->isObjCQualifiedIdType() ||
1537 ElementType->isObjCQualifiedInterfaceType())
1538 // Simply use 'id' for all qualified types.
1539 elementTypeAsString = "id";
1540 else
1541 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1542 buf += elementTypeAsString;
1543 buf += " ";
1544 elementName = D->getName();
1545 buf += elementName;
1546 buf += ";\n\t";
1547 }
1548 else {
1549 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1550 elementName = DR->getDecl()->getName();
1551 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1552 if (VD->getType()->isObjCQualifiedIdType() ||
1553 VD->getType()->isObjCQualifiedInterfaceType())
1554 // Simply use 'id' for all qualified types.
1555 elementTypeAsString = "id";
1556 else
1557 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1558 }
1559
1560 // struct __objcFastEnumerationState enumState = { 0 };
1561 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1562 // id __rw_items[16];
1563 buf += "id __rw_items[16];\n\t";
1564 // id l_collection = (id)
1565 buf += "id l_collection = (id)";
1566 // Find start location of 'collection' the hard way!
1567 const char *startCollectionBuf = startBuf;
1568 startCollectionBuf += 3; // skip 'for'
1569 startCollectionBuf = strchr(startCollectionBuf, '(');
1570 startCollectionBuf++; // skip '('
1571 // find 'in' and skip it.
1572 while (*startCollectionBuf != ' ' ||
1573 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1574 (*(startCollectionBuf+3) != ' ' &&
1575 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1576 startCollectionBuf++;
1577 startCollectionBuf += 3;
1578
1579 // Replace: "for (type element in" with string constructed thus far.
1580 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1581 // Replace ')' in for '(' type elem in collection ')' with ';'
1582 SourceLocation rightParenLoc = S->getRParenLoc();
1583 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1584 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1585 buf = ";\n\t";
1586
1587 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1588 // objects:__rw_items count:16];
1589 // which is synthesized into:
1590 // unsigned int limit =
1591 // ((unsigned int (*)
1592 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1593 // (void *)objc_msgSend)((id)l_collection,
1594 // sel_registerName(
1595 // "countByEnumeratingWithState:objects:count:"),
1596 // (struct __objcFastEnumerationState *)&state,
1597 // (id *)__rw_items, (unsigned int)16);
1598 buf += "unsigned long limit =\n\t\t";
1599 SynthCountByEnumWithState(buf);
1600 buf += ";\n\t";
1601 /// if (limit) {
1602 /// unsigned long startMutations = *enumState.mutationsPtr;
1603 /// do {
1604 /// unsigned long counter = 0;
1605 /// do {
1606 /// if (startMutations != *enumState.mutationsPtr)
1607 /// objc_enumerationMutation(l_collection);
1608 /// elem = (type)enumState.itemsPtr[counter++];
1609 buf += "if (limit) {\n\t";
1610 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1611 buf += "do {\n\t\t";
1612 buf += "unsigned long counter = 0;\n\t\t";
1613 buf += "do {\n\t\t\t";
1614 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1615 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1616 buf += elementName;
1617 buf += " = (";
1618 buf += elementTypeAsString;
1619 buf += ")enumState.itemsPtr[counter++];";
1620 // Replace ')' in for '(' type elem in collection ')' with all of these.
1621 ReplaceText(lparenLoc, 1, buf);
1622
1623 /// __continue_label: ;
1624 /// } while (counter < limit);
1625 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1626 /// objects:__rw_items count:16]);
1627 /// elem = nil;
1628 /// __break_label: ;
1629 /// }
1630 /// else
1631 /// elem = nil;
1632 /// }
1633 ///
1634 buf = ";\n\t";
1635 buf += "__continue_label_";
1636 buf += utostr(ObjCBcLabelNo.back());
1637 buf += ": ;";
1638 buf += "\n\t\t";
1639 buf += "} while (counter < limit);\n\t";
1640 buf += "} while (limit = ";
1641 SynthCountByEnumWithState(buf);
1642 buf += ");\n\t";
1643 buf += elementName;
1644 buf += " = ((";
1645 buf += elementTypeAsString;
1646 buf += ")0);\n\t";
1647 buf += "__break_label_";
1648 buf += utostr(ObjCBcLabelNo.back());
1649 buf += ": ;\n\t";
1650 buf += "}\n\t";
1651 buf += "else\n\t\t";
1652 buf += elementName;
1653 buf += " = ((";
1654 buf += elementTypeAsString;
1655 buf += ")0);\n\t";
1656 buf += "}\n";
1657
1658 // Insert all these *after* the statement body.
1659 // FIXME: If this should support Obj-C++, support CXXTryStmt
1660 if (isa<CompoundStmt>(S->getBody())) {
1661 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1662 InsertText(endBodyLoc, buf);
1663 } else {
1664 /* Need to treat single statements specially. For example:
1665 *
1666 * for (A *a in b) if (stuff()) break;
1667 * for (A *a in b) xxxyy;
1668 *
1669 * The following code simply scans ahead to the semi to find the actual end.
1670 */
1671 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1672 const char *semiBuf = strchr(stmtBuf, ';');
1673 assert(semiBuf && "Can't find ';'");
1674 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1675 InsertText(endBodyLoc, buf);
1676 }
1677 Stmts.pop_back();
1678 ObjCBcLabelNo.pop_back();
1679 return 0;
1680}
1681
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001682static void Write_RethrowObject(std::string &buf) {
1683 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1684 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1685 buf += "\tid rethrow;\n";
1686 buf += "\t} _fin_force_rethow(_rethrow);";
1687}
1688
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001689/// RewriteObjCSynchronizedStmt -
1690/// This routine rewrites @synchronized(expr) stmt;
1691/// into:
1692/// objc_sync_enter(expr);
1693/// @try stmt @finally { objc_sync_exit(expr); }
1694///
1695Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1696 // Get the start location and compute the semi location.
1697 SourceLocation startLoc = S->getLocStart();
1698 const char *startBuf = SM->getCharacterData(startLoc);
1699
1700 assert((*startBuf == '@') && "bogus @synchronized location");
1701
1702 std::string buf;
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001703 buf = "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001704
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001705 const char *lparenBuf = startBuf;
1706 while (*lparenBuf != '(') lparenBuf++;
1707 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001708
1709 buf = "; objc_sync_enter(_sync_obj);\n";
1710 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1711 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1712 buf += "\n\tid sync_exit;";
1713 buf += "\n\t} _sync_exit(_sync_obj);\n";
1714
1715 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1716 // the sync expression is typically a message expression that's already
1717 // been rewritten! (which implies the SourceLocation's are invalid).
1718 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1719 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1720 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1721 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1722
1723 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1724 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1725 assert (*LBraceLocBuf == '{');
1726 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001727
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001728 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001729 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1730 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001731
1732 buf = "} catch (id e) {_rethrow = e;}\n";
1733 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001734 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001735 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001736
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001737 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001739 return 0;
1740}
1741
1742void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1743{
1744 // Perform a bottom up traversal of all children.
1745 for (Stmt::child_range CI = S->children(); CI; ++CI)
1746 if (*CI)
1747 WarnAboutReturnGotoStmts(*CI);
1748
1749 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1750 Diags.Report(Context->getFullLoc(S->getLocStart()),
1751 TryFinallyContainsReturnDiag);
1752 }
1753 return;
1754}
1755
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001756Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001757 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001758 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001759 std::string buf;
1760
1761 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001762 if (noCatch)
1763 buf = "{ id volatile _rethrow = 0;\n";
1764 else {
1765 buf = "{ id volatile _rethrow = 0;\ntry {\n";
1766 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001767 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001768 // Get the start location and compute the semi location.
1769 SourceLocation startLoc = S->getLocStart();
1770 const char *startBuf = SM->getCharacterData(startLoc);
1771
1772 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001773 if (finalStmt)
1774 ReplaceText(startLoc, 1, buf);
1775 else
1776 // @try -> try
1777 ReplaceText(startLoc, 1, "");
1778
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001779 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1780 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001781 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001782
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001783 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001784 bool AtRemoved = false;
1785 if (catchDecl) {
1786 QualType t = catchDecl->getType();
1787 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1788 // Should be a pointer to a class.
1789 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1790 if (IDecl) {
1791 std::string Result;
1792 startBuf = SM->getCharacterData(startLoc);
1793 assert((*startBuf == '@') && "bogus @catch location");
1794 SourceLocation rParenLoc = Catch->getRParenLoc();
1795 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1796
1797 // _objc_exc_Foo *_e as argument to catch.
1798 Result = "catch (_objc_exc_"; Result += IDecl->getNameAsString();
1799 Result += " *_"; Result += catchDecl->getNameAsString();
1800 Result += ")";
1801 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
1802 // Foo *e = (Foo *)_e;
1803 Result.clear();
1804 Result = "{ ";
1805 Result += IDecl->getNameAsString();
1806 Result += " *"; Result += catchDecl->getNameAsString();
1807 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
1808 Result += "_"; Result += catchDecl->getNameAsString();
1809
1810 Result += "; ";
1811 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
1812 ReplaceText(lBraceLoc, 1, Result);
1813 AtRemoved = true;
1814 }
1815 }
1816 }
1817 if (!AtRemoved)
1818 // @catch -> catch
1819 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001820
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001821 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001822 if (finalStmt) {
1823 buf.clear();
1824 if (noCatch)
1825 buf = "catch (id e) {_rethrow = e;}\n";
1826 else
1827 buf = "}\ncatch (id e) {_rethrow = e;}\n";
1828
1829 SourceLocation startFinalLoc = finalStmt->getLocStart();
1830 ReplaceText(startFinalLoc, 8, buf);
1831 Stmt *body = finalStmt->getFinallyBody();
1832 SourceLocation startFinalBodyLoc = body->getLocStart();
1833 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001834 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001835 ReplaceText(startFinalBodyLoc, 1, buf);
1836
1837 SourceLocation endFinalBodyLoc = body->getLocEnd();
1838 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001839 // Now check for any return/continue/go statements within the @try.
1840 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001841 }
1842
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001843 return 0;
1844}
1845
1846// This can't be done with ReplaceStmt(S, ThrowExpr), since
1847// the throw expression is typically a message expression that's already
1848// been rewritten! (which implies the SourceLocation's are invalid).
1849Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1850 // Get the start location and compute the semi location.
1851 SourceLocation startLoc = S->getLocStart();
1852 const char *startBuf = SM->getCharacterData(startLoc);
1853
1854 assert((*startBuf == '@') && "bogus @throw location");
1855
1856 std::string buf;
1857 /* void objc_exception_throw(id) __attribute__((noreturn)); */
1858 if (S->getThrowExpr())
1859 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00001860 else
1861 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001862
1863 // handle "@ throw" correctly.
1864 const char *wBuf = strchr(startBuf, 'w');
1865 assert((*wBuf == 'w') && "@throw: can't find 'w'");
1866 ReplaceText(startLoc, wBuf-startBuf+1, buf);
1867
1868 const char *semiBuf = strchr(startBuf, ';');
1869 assert((*semiBuf == ';') && "@throw: can't find ';'");
1870 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00001871 if (S->getThrowExpr())
1872 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001873 return 0;
1874}
1875
1876Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1877 // Create a new string expression.
1878 QualType StrType = Context->getPointerType(Context->CharTy);
1879 std::string StrEncoding;
1880 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1881 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
1882 StringLiteral::Ascii, false,
1883 StrType, SourceLocation());
1884 ReplaceStmt(Exp, Replacement);
1885
1886 // Replace this subexpr in the parent.
1887 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1888 return Replacement;
1889}
1890
1891Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1892 if (!SelGetUidFunctionDecl)
1893 SynthSelGetUidFunctionDecl();
1894 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1895 // Create a call to sel_registerName("selName").
1896 SmallVector<Expr*, 8> SelExprs;
1897 QualType argType = Context->getPointerType(Context->CharTy);
1898 SelExprs.push_back(StringLiteral::Create(*Context,
1899 Exp->getSelector().getAsString(),
1900 StringLiteral::Ascii, false,
1901 argType, SourceLocation()));
1902 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
1903 &SelExprs[0], SelExprs.size());
1904 ReplaceStmt(Exp, SelExp);
1905 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1906 return SelExp;
1907}
1908
1909CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
1910 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
1911 SourceLocation EndLoc) {
1912 // Get the type, we will need to reference it in a couple spots.
1913 QualType msgSendType = FD->getType();
1914
1915 // Create a reference to the objc_msgSend() declaration.
1916 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00001917 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001918
1919 // Now, we cast the reference to a pointer to the objc_msgSend type.
1920 QualType pToFunc = Context->getPointerType(msgSendType);
1921 ImplicitCastExpr *ICE =
1922 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
1923 DRE, 0, VK_RValue);
1924
1925 const FunctionType *FT = msgSendType->getAs<FunctionType>();
1926
1927 CallExpr *Exp =
1928 new (Context) CallExpr(*Context, ICE, args, nargs,
1929 FT->getCallResultType(*Context),
1930 VK_RValue, EndLoc);
1931 return Exp;
1932}
1933
1934static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
1935 const char *&startRef, const char *&endRef) {
1936 while (startBuf < endBuf) {
1937 if (*startBuf == '<')
1938 startRef = startBuf; // mark the start.
1939 if (*startBuf == '>') {
1940 if (startRef && *startRef == '<') {
1941 endRef = startBuf; // mark the end.
1942 return true;
1943 }
1944 return false;
1945 }
1946 startBuf++;
1947 }
1948 return false;
1949}
1950
1951static void scanToNextArgument(const char *&argRef) {
1952 int angle = 0;
1953 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
1954 if (*argRef == '<')
1955 angle++;
1956 else if (*argRef == '>')
1957 angle--;
1958 argRef++;
1959 }
1960 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
1961}
1962
1963bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
1964 if (T->isObjCQualifiedIdType())
1965 return true;
1966 if (const PointerType *PT = T->getAs<PointerType>()) {
1967 if (PT->getPointeeType()->isObjCQualifiedIdType())
1968 return true;
1969 }
1970 if (T->isObjCObjectPointerType()) {
1971 T = T->getPointeeType();
1972 return T->isObjCQualifiedInterfaceType();
1973 }
1974 if (T->isArrayType()) {
1975 QualType ElemTy = Context->getBaseElementType(T);
1976 return needToScanForQualifiers(ElemTy);
1977 }
1978 return false;
1979}
1980
1981void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
1982 QualType Type = E->getType();
1983 if (needToScanForQualifiers(Type)) {
1984 SourceLocation Loc, EndLoc;
1985
1986 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
1987 Loc = ECE->getLParenLoc();
1988 EndLoc = ECE->getRParenLoc();
1989 } else {
1990 Loc = E->getLocStart();
1991 EndLoc = E->getLocEnd();
1992 }
1993 // This will defend against trying to rewrite synthesized expressions.
1994 if (Loc.isInvalid() || EndLoc.isInvalid())
1995 return;
1996
1997 const char *startBuf = SM->getCharacterData(Loc);
1998 const char *endBuf = SM->getCharacterData(EndLoc);
1999 const char *startRef = 0, *endRef = 0;
2000 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2001 // Get the locations of the startRef, endRef.
2002 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2003 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2004 // Comment out the protocol references.
2005 InsertText(LessLoc, "/*");
2006 InsertText(GreaterLoc, "*/");
2007 }
2008 }
2009}
2010
2011void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2012 SourceLocation Loc;
2013 QualType Type;
2014 const FunctionProtoType *proto = 0;
2015 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2016 Loc = VD->getLocation();
2017 Type = VD->getType();
2018 }
2019 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2020 Loc = FD->getLocation();
2021 // Check for ObjC 'id' and class types that have been adorned with protocol
2022 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2023 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2024 assert(funcType && "missing function type");
2025 proto = dyn_cast<FunctionProtoType>(funcType);
2026 if (!proto)
2027 return;
2028 Type = proto->getResultType();
2029 }
2030 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2031 Loc = FD->getLocation();
2032 Type = FD->getType();
2033 }
2034 else
2035 return;
2036
2037 if (needToScanForQualifiers(Type)) {
2038 // Since types are unique, we need to scan the buffer.
2039
2040 const char *endBuf = SM->getCharacterData(Loc);
2041 const char *startBuf = endBuf;
2042 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2043 startBuf--; // scan backward (from the decl location) for return type.
2044 const char *startRef = 0, *endRef = 0;
2045 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2046 // Get the locations of the startRef, endRef.
2047 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2048 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2049 // Comment out the protocol references.
2050 InsertText(LessLoc, "/*");
2051 InsertText(GreaterLoc, "*/");
2052 }
2053 }
2054 if (!proto)
2055 return; // most likely, was a variable
2056 // Now check arguments.
2057 const char *startBuf = SM->getCharacterData(Loc);
2058 const char *startFuncBuf = startBuf;
2059 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2060 if (needToScanForQualifiers(proto->getArgType(i))) {
2061 // Since types are unique, we need to scan the buffer.
2062
2063 const char *endBuf = startBuf;
2064 // scan forward (from the decl location) for argument types.
2065 scanToNextArgument(endBuf);
2066 const char *startRef = 0, *endRef = 0;
2067 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2068 // Get the locations of the startRef, endRef.
2069 SourceLocation LessLoc =
2070 Loc.getLocWithOffset(startRef-startFuncBuf);
2071 SourceLocation GreaterLoc =
2072 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2073 // Comment out the protocol references.
2074 InsertText(LessLoc, "/*");
2075 InsertText(GreaterLoc, "*/");
2076 }
2077 startBuf = ++endBuf;
2078 }
2079 else {
2080 // If the function name is derived from a macro expansion, then the
2081 // argument buffer will not follow the name. Need to speak with Chris.
2082 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2083 startBuf++; // scan forward (from the decl location) for argument types.
2084 startBuf++;
2085 }
2086 }
2087}
2088
2089void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2090 QualType QT = ND->getType();
2091 const Type* TypePtr = QT->getAs<Type>();
2092 if (!isa<TypeOfExprType>(TypePtr))
2093 return;
2094 while (isa<TypeOfExprType>(TypePtr)) {
2095 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2096 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2097 TypePtr = QT->getAs<Type>();
2098 }
2099 // FIXME. This will not work for multiple declarators; as in:
2100 // __typeof__(a) b,c,d;
2101 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2102 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2103 const char *startBuf = SM->getCharacterData(DeclLoc);
2104 if (ND->getInit()) {
2105 std::string Name(ND->getNameAsString());
2106 TypeAsString += " " + Name + " = ";
2107 Expr *E = ND->getInit();
2108 SourceLocation startLoc;
2109 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2110 startLoc = ECE->getLParenLoc();
2111 else
2112 startLoc = E->getLocStart();
2113 startLoc = SM->getExpansionLoc(startLoc);
2114 const char *endBuf = SM->getCharacterData(startLoc);
2115 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2116 }
2117 else {
2118 SourceLocation X = ND->getLocEnd();
2119 X = SM->getExpansionLoc(X);
2120 const char *endBuf = SM->getCharacterData(X);
2121 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2122 }
2123}
2124
2125// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2126void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2127 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2128 SmallVector<QualType, 16> ArgTys;
2129 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2130 QualType getFuncType =
2131 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2132 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2133 SourceLocation(),
2134 SourceLocation(),
2135 SelGetUidIdent, getFuncType, 0,
2136 SC_Extern,
2137 SC_None, false);
2138}
2139
2140void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2141 // declared in <objc/objc.h>
2142 if (FD->getIdentifier() &&
2143 FD->getName() == "sel_registerName") {
2144 SelGetUidFunctionDecl = FD;
2145 return;
2146 }
2147 RewriteObjCQualifiedInterfaceTypes(FD);
2148}
2149
2150void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2151 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2152 const char *argPtr = TypeString.c_str();
2153 if (!strchr(argPtr, '^')) {
2154 Str += TypeString;
2155 return;
2156 }
2157 while (*argPtr) {
2158 Str += (*argPtr == '^' ? '*' : *argPtr);
2159 argPtr++;
2160 }
2161}
2162
2163// FIXME. Consolidate this routine with RewriteBlockPointerType.
2164void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2165 ValueDecl *VD) {
2166 QualType Type = VD->getType();
2167 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2168 const char *argPtr = TypeString.c_str();
2169 int paren = 0;
2170 while (*argPtr) {
2171 switch (*argPtr) {
2172 case '(':
2173 Str += *argPtr;
2174 paren++;
2175 break;
2176 case ')':
2177 Str += *argPtr;
2178 paren--;
2179 break;
2180 case '^':
2181 Str += '*';
2182 if (paren == 1)
2183 Str += VD->getNameAsString();
2184 break;
2185 default:
2186 Str += *argPtr;
2187 break;
2188 }
2189 argPtr++;
2190 }
2191}
2192
2193
2194void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2195 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2196 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2197 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2198 if (!proto)
2199 return;
2200 QualType Type = proto->getResultType();
2201 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2202 FdStr += " ";
2203 FdStr += FD->getName();
2204 FdStr += "(";
2205 unsigned numArgs = proto->getNumArgs();
2206 for (unsigned i = 0; i < numArgs; i++) {
2207 QualType ArgType = proto->getArgType(i);
2208 RewriteBlockPointerType(FdStr, ArgType);
2209 if (i+1 < numArgs)
2210 FdStr += ", ";
2211 }
2212 FdStr += ");\n";
2213 InsertText(FunLocStart, FdStr);
2214 CurFunctionDeclToDeclareForBlock = 0;
2215}
2216
2217// SynthSuperContructorFunctionDecl - id objc_super(id obj, id super);
2218void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2219 if (SuperContructorFunctionDecl)
2220 return;
2221 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2222 SmallVector<QualType, 16> ArgTys;
2223 QualType argT = Context->getObjCIdType();
2224 assert(!argT.isNull() && "Can't find 'id' type");
2225 ArgTys.push_back(argT);
2226 ArgTys.push_back(argT);
2227 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2228 &ArgTys[0], ArgTys.size());
2229 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2230 SourceLocation(),
2231 SourceLocation(),
2232 msgSendIdent, msgSendType, 0,
2233 SC_Extern,
2234 SC_None, false);
2235}
2236
2237// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2238void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2239 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2240 SmallVector<QualType, 16> ArgTys;
2241 QualType argT = Context->getObjCIdType();
2242 assert(!argT.isNull() && "Can't find 'id' type");
2243 ArgTys.push_back(argT);
2244 argT = Context->getObjCSelType();
2245 assert(!argT.isNull() && "Can't find 'SEL' type");
2246 ArgTys.push_back(argT);
2247 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2248 &ArgTys[0], ArgTys.size(),
2249 true /*isVariadic*/);
2250 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2251 SourceLocation(),
2252 SourceLocation(),
2253 msgSendIdent, msgSendType, 0,
2254 SC_Extern,
2255 SC_None, false);
2256}
2257
2258// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2259void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2260 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2261 SmallVector<QualType, 16> ArgTys;
2262 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2263 SourceLocation(), SourceLocation(),
2264 &Context->Idents.get("objc_super"));
2265 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2266 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2267 ArgTys.push_back(argT);
2268 argT = Context->getObjCSelType();
2269 assert(!argT.isNull() && "Can't find 'SEL' type");
2270 ArgTys.push_back(argT);
2271 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2272 &ArgTys[0], ArgTys.size(),
2273 true /*isVariadic*/);
2274 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2275 SourceLocation(),
2276 SourceLocation(),
2277 msgSendIdent, msgSendType, 0,
2278 SC_Extern,
2279 SC_None, false);
2280}
2281
2282// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2283void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2284 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2285 SmallVector<QualType, 16> ArgTys;
2286 QualType argT = Context->getObjCIdType();
2287 assert(!argT.isNull() && "Can't find 'id' type");
2288 ArgTys.push_back(argT);
2289 argT = Context->getObjCSelType();
2290 assert(!argT.isNull() && "Can't find 'SEL' type");
2291 ArgTys.push_back(argT);
2292 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2293 &ArgTys[0], ArgTys.size(),
2294 true /*isVariadic*/);
2295 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2296 SourceLocation(),
2297 SourceLocation(),
2298 msgSendIdent, msgSendType, 0,
2299 SC_Extern,
2300 SC_None, false);
2301}
2302
2303// SynthMsgSendSuperStretFunctionDecl -
2304// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2305void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2306 IdentifierInfo *msgSendIdent =
2307 &Context->Idents.get("objc_msgSendSuper_stret");
2308 SmallVector<QualType, 16> ArgTys;
2309 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2310 SourceLocation(), SourceLocation(),
2311 &Context->Idents.get("objc_super"));
2312 QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2313 assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2314 ArgTys.push_back(argT);
2315 argT = Context->getObjCSelType();
2316 assert(!argT.isNull() && "Can't find 'SEL' type");
2317 ArgTys.push_back(argT);
2318 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2319 &ArgTys[0], ArgTys.size(),
2320 true /*isVariadic*/);
2321 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2322 SourceLocation(),
2323 SourceLocation(),
2324 msgSendIdent, msgSendType, 0,
2325 SC_Extern,
2326 SC_None, false);
2327}
2328
2329// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2330void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2331 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2332 SmallVector<QualType, 16> ArgTys;
2333 QualType argT = Context->getObjCIdType();
2334 assert(!argT.isNull() && "Can't find 'id' type");
2335 ArgTys.push_back(argT);
2336 argT = Context->getObjCSelType();
2337 assert(!argT.isNull() && "Can't find 'SEL' type");
2338 ArgTys.push_back(argT);
2339 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2340 &ArgTys[0], ArgTys.size(),
2341 true /*isVariadic*/);
2342 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2343 SourceLocation(),
2344 SourceLocation(),
2345 msgSendIdent, msgSendType, 0,
2346 SC_Extern,
2347 SC_None, false);
2348}
2349
2350// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2351void RewriteModernObjC::SynthGetClassFunctionDecl() {
2352 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2353 SmallVector<QualType, 16> ArgTys;
2354 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2355 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2356 &ArgTys[0], ArgTys.size());
2357 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2358 SourceLocation(),
2359 SourceLocation(),
2360 getClassIdent, getClassType, 0,
2361 SC_Extern,
2362 SC_None, false);
2363}
2364
2365// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2366void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2367 IdentifierInfo *getSuperClassIdent =
2368 &Context->Idents.get("class_getSuperclass");
2369 SmallVector<QualType, 16> ArgTys;
2370 ArgTys.push_back(Context->getObjCClassType());
2371 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2372 &ArgTys[0], ArgTys.size());
2373 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2374 SourceLocation(),
2375 SourceLocation(),
2376 getSuperClassIdent,
2377 getClassType, 0,
2378 SC_Extern,
2379 SC_None,
2380 false);
2381}
2382
2383// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2384void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2385 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2386 SmallVector<QualType, 16> ArgTys;
2387 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2388 QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2389 &ArgTys[0], ArgTys.size());
2390 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2391 SourceLocation(),
2392 SourceLocation(),
2393 getClassIdent, getClassType, 0,
2394 SC_Extern,
2395 SC_None, false);
2396}
2397
2398Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2399 QualType strType = getConstantStringStructType();
2400
2401 std::string S = "__NSConstantStringImpl_";
2402
2403 std::string tmpName = InFileName;
2404 unsigned i;
2405 for (i=0; i < tmpName.length(); i++) {
2406 char c = tmpName.at(i);
2407 // replace any non alphanumeric characters with '_'.
2408 if (!isalpha(c) && (c < '0' || c > '9'))
2409 tmpName[i] = '_';
2410 }
2411 S += tmpName;
2412 S += "_";
2413 S += utostr(NumObjCStringLiterals++);
2414
2415 Preamble += "static __NSConstantStringImpl " + S;
2416 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2417 Preamble += "0x000007c8,"; // utf8_str
2418 // The pretty printer for StringLiteral handles escape characters properly.
2419 std::string prettyBufS;
2420 llvm::raw_string_ostream prettyBuf(prettyBufS);
2421 Exp->getString()->printPretty(prettyBuf, *Context, 0,
2422 PrintingPolicy(LangOpts));
2423 Preamble += prettyBuf.str();
2424 Preamble += ",";
2425 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2426
2427 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2428 SourceLocation(), &Context->Idents.get(S),
2429 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002430 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002431 SourceLocation());
2432 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2433 Context->getPointerType(DRE->getType()),
2434 VK_RValue, OK_Ordinary,
2435 SourceLocation());
2436 // cast to NSConstantString *
2437 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2438 CK_CPointerToObjCPointerCast, Unop);
2439 ReplaceStmt(Exp, cast);
2440 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2441 return cast;
2442}
2443
2444// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2445QualType RewriteModernObjC::getSuperStructType() {
2446 if (!SuperStructDecl) {
2447 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2448 SourceLocation(), SourceLocation(),
2449 &Context->Idents.get("objc_super"));
2450 QualType FieldTypes[2];
2451
2452 // struct objc_object *receiver;
2453 FieldTypes[0] = Context->getObjCIdType();
2454 // struct objc_class *super;
2455 FieldTypes[1] = Context->getObjCClassType();
2456
2457 // Create fields
2458 for (unsigned i = 0; i < 2; ++i) {
2459 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2460 SourceLocation(),
2461 SourceLocation(), 0,
2462 FieldTypes[i], 0,
2463 /*BitWidth=*/0,
2464 /*Mutable=*/false,
2465 /*HasInit=*/false));
2466 }
2467
2468 SuperStructDecl->completeDefinition();
2469 }
2470 return Context->getTagDeclType(SuperStructDecl);
2471}
2472
2473QualType RewriteModernObjC::getConstantStringStructType() {
2474 if (!ConstantStringDecl) {
2475 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2476 SourceLocation(), SourceLocation(),
2477 &Context->Idents.get("__NSConstantStringImpl"));
2478 QualType FieldTypes[4];
2479
2480 // struct objc_object *receiver;
2481 FieldTypes[0] = Context->getObjCIdType();
2482 // int flags;
2483 FieldTypes[1] = Context->IntTy;
2484 // char *str;
2485 FieldTypes[2] = Context->getPointerType(Context->CharTy);
2486 // long length;
2487 FieldTypes[3] = Context->LongTy;
2488
2489 // Create fields
2490 for (unsigned i = 0; i < 4; ++i) {
2491 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2492 ConstantStringDecl,
2493 SourceLocation(),
2494 SourceLocation(), 0,
2495 FieldTypes[i], 0,
2496 /*BitWidth=*/0,
2497 /*Mutable=*/true,
2498 /*HasInit=*/false));
2499 }
2500
2501 ConstantStringDecl->completeDefinition();
2502 }
2503 return Context->getTagDeclType(ConstantStringDecl);
2504}
2505
2506Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2507 SourceLocation StartLoc,
2508 SourceLocation EndLoc) {
2509 if (!SelGetUidFunctionDecl)
2510 SynthSelGetUidFunctionDecl();
2511 if (!MsgSendFunctionDecl)
2512 SynthMsgSendFunctionDecl();
2513 if (!MsgSendSuperFunctionDecl)
2514 SynthMsgSendSuperFunctionDecl();
2515 if (!MsgSendStretFunctionDecl)
2516 SynthMsgSendStretFunctionDecl();
2517 if (!MsgSendSuperStretFunctionDecl)
2518 SynthMsgSendSuperStretFunctionDecl();
2519 if (!MsgSendFpretFunctionDecl)
2520 SynthMsgSendFpretFunctionDecl();
2521 if (!GetClassFunctionDecl)
2522 SynthGetClassFunctionDecl();
2523 if (!GetSuperClassFunctionDecl)
2524 SynthGetSuperClassFunctionDecl();
2525 if (!GetMetaClassFunctionDecl)
2526 SynthGetMetaClassFunctionDecl();
2527
2528 // default to objc_msgSend().
2529 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2530 // May need to use objc_msgSend_stret() as well.
2531 FunctionDecl *MsgSendStretFlavor = 0;
2532 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2533 QualType resultType = mDecl->getResultType();
2534 if (resultType->isRecordType())
2535 MsgSendStretFlavor = MsgSendStretFunctionDecl;
2536 else if (resultType->isRealFloatingType())
2537 MsgSendFlavor = MsgSendFpretFunctionDecl;
2538 }
2539
2540 // Synthesize a call to objc_msgSend().
2541 SmallVector<Expr*, 8> MsgExprs;
2542 switch (Exp->getReceiverKind()) {
2543 case ObjCMessageExpr::SuperClass: {
2544 MsgSendFlavor = MsgSendSuperFunctionDecl;
2545 if (MsgSendStretFlavor)
2546 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2547 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2548
2549 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2550
2551 SmallVector<Expr*, 4> InitExprs;
2552
2553 // set the receiver to self, the first argument to all methods.
2554 InitExprs.push_back(
2555 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2556 CK_BitCast,
2557 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002558 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002559 Context->getObjCIdType(),
2560 VK_RValue,
2561 SourceLocation()))
2562 ); // set the 'receiver'.
2563
2564 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2565 SmallVector<Expr*, 8> ClsExprs;
2566 QualType argType = Context->getPointerType(Context->CharTy);
2567 ClsExprs.push_back(StringLiteral::Create(*Context,
2568 ClassDecl->getIdentifier()->getName(),
2569 StringLiteral::Ascii, false,
2570 argType, SourceLocation()));
2571 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2572 &ClsExprs[0],
2573 ClsExprs.size(),
2574 StartLoc,
2575 EndLoc);
2576 // (Class)objc_getClass("CurrentClass")
2577 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2578 Context->getObjCClassType(),
2579 CK_BitCast, Cls);
2580 ClsExprs.clear();
2581 ClsExprs.push_back(ArgExpr);
2582 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2583 &ClsExprs[0], ClsExprs.size(),
2584 StartLoc, EndLoc);
2585
2586 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2587 // To turn off a warning, type-cast to 'id'
2588 InitExprs.push_back( // set 'super class', using class_getSuperclass().
2589 NoTypeInfoCStyleCastExpr(Context,
2590 Context->getObjCIdType(),
2591 CK_BitCast, Cls));
2592 // struct objc_super
2593 QualType superType = getSuperStructType();
2594 Expr *SuperRep;
2595
2596 if (LangOpts.MicrosoftExt) {
2597 SynthSuperContructorFunctionDecl();
2598 // Simulate a contructor call...
2599 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002600 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002601 SourceLocation());
2602 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2603 InitExprs.size(),
2604 superType, VK_LValue,
2605 SourceLocation());
2606 // The code for super is a little tricky to prevent collision with
2607 // the structure definition in the header. The rewriter has it's own
2608 // internal definition (__rw_objc_super) that is uses. This is why
2609 // we need the cast below. For example:
2610 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2611 //
2612 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2613 Context->getPointerType(SuperRep->getType()),
2614 VK_RValue, OK_Ordinary,
2615 SourceLocation());
2616 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2617 Context->getPointerType(superType),
2618 CK_BitCast, SuperRep);
2619 } else {
2620 // (struct objc_super) { <exprs from above> }
2621 InitListExpr *ILE =
2622 new (Context) InitListExpr(*Context, SourceLocation(),
2623 &InitExprs[0], InitExprs.size(),
2624 SourceLocation());
2625 TypeSourceInfo *superTInfo
2626 = Context->getTrivialTypeSourceInfo(superType);
2627 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2628 superType, VK_LValue,
2629 ILE, false);
2630 // struct objc_super *
2631 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2632 Context->getPointerType(SuperRep->getType()),
2633 VK_RValue, OK_Ordinary,
2634 SourceLocation());
2635 }
2636 MsgExprs.push_back(SuperRep);
2637 break;
2638 }
2639
2640 case ObjCMessageExpr::Class: {
2641 SmallVector<Expr*, 8> ClsExprs;
2642 QualType argType = Context->getPointerType(Context->CharTy);
2643 ObjCInterfaceDecl *Class
2644 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
2645 IdentifierInfo *clsName = Class->getIdentifier();
2646 ClsExprs.push_back(StringLiteral::Create(*Context,
2647 clsName->getName(),
2648 StringLiteral::Ascii, false,
2649 argType, SourceLocation()));
2650 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2651 &ClsExprs[0],
2652 ClsExprs.size(),
2653 StartLoc, EndLoc);
2654 MsgExprs.push_back(Cls);
2655 break;
2656 }
2657
2658 case ObjCMessageExpr::SuperInstance:{
2659 MsgSendFlavor = MsgSendSuperFunctionDecl;
2660 if (MsgSendStretFlavor)
2661 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2662 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2663 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2664 SmallVector<Expr*, 4> InitExprs;
2665
2666 InitExprs.push_back(
2667 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2668 CK_BitCast,
2669 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00002670 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002671 Context->getObjCIdType(),
2672 VK_RValue, SourceLocation()))
2673 ); // set the 'receiver'.
2674
2675 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2676 SmallVector<Expr*, 8> ClsExprs;
2677 QualType argType = Context->getPointerType(Context->CharTy);
2678 ClsExprs.push_back(StringLiteral::Create(*Context,
2679 ClassDecl->getIdentifier()->getName(),
2680 StringLiteral::Ascii, false, argType,
2681 SourceLocation()));
2682 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2683 &ClsExprs[0],
2684 ClsExprs.size(),
2685 StartLoc, EndLoc);
2686 // (Class)objc_getClass("CurrentClass")
2687 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2688 Context->getObjCClassType(),
2689 CK_BitCast, Cls);
2690 ClsExprs.clear();
2691 ClsExprs.push_back(ArgExpr);
2692 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
2693 &ClsExprs[0], ClsExprs.size(),
2694 StartLoc, EndLoc);
2695
2696 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2697 // To turn off a warning, type-cast to 'id'
2698 InitExprs.push_back(
2699 // set 'super class', using class_getSuperclass().
2700 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2701 CK_BitCast, Cls));
2702 // struct objc_super
2703 QualType superType = getSuperStructType();
2704 Expr *SuperRep;
2705
2706 if (LangOpts.MicrosoftExt) {
2707 SynthSuperContructorFunctionDecl();
2708 // Simulate a contructor call...
2709 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00002710 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002711 SourceLocation());
2712 SuperRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0],
2713 InitExprs.size(),
2714 superType, VK_LValue, SourceLocation());
2715 // The code for super is a little tricky to prevent collision with
2716 // the structure definition in the header. The rewriter has it's own
2717 // internal definition (__rw_objc_super) that is uses. This is why
2718 // we need the cast below. For example:
2719 // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2720 //
2721 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2722 Context->getPointerType(SuperRep->getType()),
2723 VK_RValue, OK_Ordinary,
2724 SourceLocation());
2725 SuperRep = NoTypeInfoCStyleCastExpr(Context,
2726 Context->getPointerType(superType),
2727 CK_BitCast, SuperRep);
2728 } else {
2729 // (struct objc_super) { <exprs from above> }
2730 InitListExpr *ILE =
2731 new (Context) InitListExpr(*Context, SourceLocation(),
2732 &InitExprs[0], InitExprs.size(),
2733 SourceLocation());
2734 TypeSourceInfo *superTInfo
2735 = Context->getTrivialTypeSourceInfo(superType);
2736 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2737 superType, VK_RValue, ILE,
2738 false);
2739 }
2740 MsgExprs.push_back(SuperRep);
2741 break;
2742 }
2743
2744 case ObjCMessageExpr::Instance: {
2745 // Remove all type-casts because it may contain objc-style types; e.g.
2746 // Foo<Proto> *.
2747 Expr *recExpr = Exp->getInstanceReceiver();
2748 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2749 recExpr = CE->getSubExpr();
2750 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2751 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2752 ? CK_BlockPointerToObjCPointerCast
2753 : CK_CPointerToObjCPointerCast;
2754
2755 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2756 CK, recExpr);
2757 MsgExprs.push_back(recExpr);
2758 break;
2759 }
2760 }
2761
2762 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2763 SmallVector<Expr*, 8> SelExprs;
2764 QualType argType = Context->getPointerType(Context->CharTy);
2765 SelExprs.push_back(StringLiteral::Create(*Context,
2766 Exp->getSelector().getAsString(),
2767 StringLiteral::Ascii, false,
2768 argType, SourceLocation()));
2769 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2770 &SelExprs[0], SelExprs.size(),
2771 StartLoc,
2772 EndLoc);
2773 MsgExprs.push_back(SelExp);
2774
2775 // Now push any user supplied arguments.
2776 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
2777 Expr *userExpr = Exp->getArg(i);
2778 // Make all implicit casts explicit...ICE comes in handy:-)
2779 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2780 // Reuse the ICE type, it is exactly what the doctor ordered.
2781 QualType type = ICE->getType();
2782 if (needToScanForQualifiers(type))
2783 type = Context->getObjCIdType();
2784 // Make sure we convert "type (^)(...)" to "type (*)(...)".
2785 (void)convertBlockPointerToFunctionPointer(type);
2786 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2787 CastKind CK;
2788 if (SubExpr->getType()->isIntegralType(*Context) &&
2789 type->isBooleanType()) {
2790 CK = CK_IntegralToBoolean;
2791 } else if (type->isObjCObjectPointerType()) {
2792 if (SubExpr->getType()->isBlockPointerType()) {
2793 CK = CK_BlockPointerToObjCPointerCast;
2794 } else if (SubExpr->getType()->isPointerType()) {
2795 CK = CK_CPointerToObjCPointerCast;
2796 } else {
2797 CK = CK_BitCast;
2798 }
2799 } else {
2800 CK = CK_BitCast;
2801 }
2802
2803 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2804 }
2805 // Make id<P...> cast into an 'id' cast.
2806 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2807 if (CE->getType()->isObjCQualifiedIdType()) {
2808 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2809 userExpr = CE->getSubExpr();
2810 CastKind CK;
2811 if (userExpr->getType()->isIntegralType(*Context)) {
2812 CK = CK_IntegralToPointer;
2813 } else if (userExpr->getType()->isBlockPointerType()) {
2814 CK = CK_BlockPointerToObjCPointerCast;
2815 } else if (userExpr->getType()->isPointerType()) {
2816 CK = CK_CPointerToObjCPointerCast;
2817 } else {
2818 CK = CK_BitCast;
2819 }
2820 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2821 CK, userExpr);
2822 }
2823 }
2824 MsgExprs.push_back(userExpr);
2825 // We've transferred the ownership to MsgExprs. For now, we *don't* null
2826 // out the argument in the original expression (since we aren't deleting
2827 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2828 //Exp->setArg(i, 0);
2829 }
2830 // Generate the funky cast.
2831 CastExpr *cast;
2832 SmallVector<QualType, 8> ArgTypes;
2833 QualType returnType;
2834
2835 // Push 'id' and 'SEL', the 2 implicit arguments.
2836 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2837 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2838 else
2839 ArgTypes.push_back(Context->getObjCIdType());
2840 ArgTypes.push_back(Context->getObjCSelType());
2841 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2842 // Push any user argument types.
2843 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
2844 E = OMD->param_end(); PI != E; ++PI) {
2845 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
2846 ? Context->getObjCIdType()
2847 : (*PI)->getType();
2848 // Make sure we convert "t (^)(...)" to "t (*)(...)".
2849 (void)convertBlockPointerToFunctionPointer(t);
2850 ArgTypes.push_back(t);
2851 }
2852 returnType = Exp->getType();
2853 convertToUnqualifiedObjCType(returnType);
2854 (void)convertBlockPointerToFunctionPointer(returnType);
2855 } else {
2856 returnType = Context->getObjCIdType();
2857 }
2858 // Get the type, we will need to reference it in a couple spots.
2859 QualType msgSendType = MsgSendFlavor->getType();
2860
2861 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002862 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002863 VK_LValue, SourceLocation());
2864
2865 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2866 // If we don't do this cast, we get the following bizarre warning/note:
2867 // xx.m:13: warning: function called through a non-compatible type
2868 // xx.m:13: note: if this code is reached, the program will abort
2869 cast = NoTypeInfoCStyleCastExpr(Context,
2870 Context->getPointerType(Context->VoidTy),
2871 CK_BitCast, DRE);
2872
2873 // Now do the "normal" pointer to function cast.
2874 QualType castType =
2875 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2876 // If we don't have a method decl, force a variadic cast.
2877 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
2878 castType = Context->getPointerType(castType);
2879 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2880 cast);
2881
2882 // Don't forget the parens to enforce the proper binding.
2883 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2884
2885 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2886 CallExpr *CE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2887 MsgExprs.size(),
2888 FT->getResultType(), VK_RValue,
2889 EndLoc);
2890 Stmt *ReplacingStmt = CE;
2891 if (MsgSendStretFlavor) {
2892 // We have the method which returns a struct/union. Must also generate
2893 // call to objc_msgSend_stret and hang both varieties on a conditional
2894 // expression which dictate which one to envoke depending on size of
2895 // method's return type.
2896
2897 // Create a reference to the objc_msgSend_stret() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00002898 DeclRefExpr *STDRE = new (Context) DeclRefExpr(MsgSendStretFlavor,
2899 false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002900 VK_LValue, SourceLocation());
2901 // Need to cast objc_msgSend_stret to "void *" (see above comment).
2902 cast = NoTypeInfoCStyleCastExpr(Context,
2903 Context->getPointerType(Context->VoidTy),
2904 CK_BitCast, STDRE);
2905 // Now do the "normal" pointer to function cast.
2906 castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2907 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : false);
2908 castType = Context->getPointerType(castType);
2909 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2910 cast);
2911
2912 // Don't forget the parens to enforce the proper binding.
2913 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2914
2915 FT = msgSendType->getAs<FunctionType>();
2916 CallExpr *STCE = new (Context) CallExpr(*Context, PE, &MsgExprs[0],
2917 MsgExprs.size(),
2918 FT->getResultType(), VK_RValue,
2919 SourceLocation());
2920
2921 // Build sizeof(returnType)
2922 UnaryExprOrTypeTraitExpr *sizeofExpr =
2923 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2924 Context->getTrivialTypeSourceInfo(returnType),
2925 Context->getSizeType(), SourceLocation(),
2926 SourceLocation());
2927 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2928 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2929 // For X86 it is more complicated and some kind of target specific routine
2930 // is needed to decide what to do.
2931 unsigned IntSize =
2932 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2933 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2934 llvm::APInt(IntSize, 8),
2935 Context->IntTy,
2936 SourceLocation());
2937 BinaryOperator *lessThanExpr =
2938 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
2939 VK_RValue, OK_Ordinary, SourceLocation());
2940 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2941 ConditionalOperator *CondExpr =
2942 new (Context) ConditionalOperator(lessThanExpr,
2943 SourceLocation(), CE,
2944 SourceLocation(), STCE,
2945 returnType, VK_RValue, OK_Ordinary);
2946 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
2947 CondExpr);
2948 }
2949 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2950 return ReplacingStmt;
2951}
2952
2953Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
2954 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
2955 Exp->getLocEnd());
2956
2957 // Now do the actual rewrite.
2958 ReplaceStmt(Exp, ReplacingStmt);
2959
2960 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2961 return ReplacingStmt;
2962}
2963
2964// typedef struct objc_object Protocol;
2965QualType RewriteModernObjC::getProtocolType() {
2966 if (!ProtocolTypeDecl) {
2967 TypeSourceInfo *TInfo
2968 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
2969 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
2970 SourceLocation(), SourceLocation(),
2971 &Context->Idents.get("Protocol"),
2972 TInfo);
2973 }
2974 return Context->getTypeDeclType(ProtocolTypeDecl);
2975}
2976
2977/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
2978/// a synthesized/forward data reference (to the protocol's metadata).
2979/// The forward references (and metadata) are generated in
2980/// RewriteModernObjC::HandleTranslationUnit().
2981Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00002982 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
2983 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002984 IdentifierInfo *ID = &Context->Idents.get(Name);
2985 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2986 SourceLocation(), ID, getProtocolType(), 0,
2987 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002988 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
2989 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002990 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
2991 Context->getPointerType(DRE->getType()),
2992 VK_RValue, OK_Ordinary, SourceLocation());
2993 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
2994 CK_BitCast,
2995 DerefExpr);
2996 ReplaceStmt(Exp, castExpr);
2997 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
2998 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2999 return castExpr;
3000
3001}
3002
3003bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3004 const char *endBuf) {
3005 while (startBuf < endBuf) {
3006 if (*startBuf == '#') {
3007 // Skip whitespace.
3008 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3009 ;
3010 if (!strncmp(startBuf, "if", strlen("if")) ||
3011 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3012 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3013 !strncmp(startBuf, "define", strlen("define")) ||
3014 !strncmp(startBuf, "undef", strlen("undef")) ||
3015 !strncmp(startBuf, "else", strlen("else")) ||
3016 !strncmp(startBuf, "elif", strlen("elif")) ||
3017 !strncmp(startBuf, "endif", strlen("endif")) ||
3018 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3019 !strncmp(startBuf, "include", strlen("include")) ||
3020 !strncmp(startBuf, "import", strlen("import")) ||
3021 !strncmp(startBuf, "include_next", strlen("include_next")))
3022 return true;
3023 }
3024 startBuf++;
3025 }
3026 return false;
3027}
3028
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003029/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003030/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003031bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3032 std::string &Result) {
3033 if (Type->isArrayType()) {
3034 QualType ElemTy = Context->getBaseElementType(Type);
3035 return RewriteObjCFieldDeclType(ElemTy, Result);
3036 }
3037 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003038 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3039 if (RD->isCompleteDefinition()) {
3040 if (RD->isStruct())
3041 Result += "\n\tstruct ";
3042 else if (RD->isUnion())
3043 Result += "\n\tunion ";
3044 else
3045 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003046
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003047 Result += RD->getName();
3048 if (TagsDefinedInIvarDecls.count(RD)) {
3049 // This struct is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003050 Result += " ";
3051 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003052 }
3053 TagsDefinedInIvarDecls.insert(RD);
3054 Result += " {\n";
3055 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003056 e = RD->field_end(); i != e; ++i) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003057 FieldDecl *FD = *i;
3058 RewriteObjCFieldDecl(FD, Result);
3059 }
3060 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003061 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003062 }
3063 }
3064 else if (Type->isEnumeralType()) {
3065 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3066 if (ED->isCompleteDefinition()) {
3067 Result += "\n\tenum ";
3068 Result += ED->getName();
3069 if (TagsDefinedInIvarDecls.count(ED)) {
3070 // This enum is already defined. Do not write its definition again.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003071 Result += " ";
3072 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003073 }
3074 TagsDefinedInIvarDecls.insert(ED);
3075
3076 Result += " {\n";
3077 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3078 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3079 Result += "\t"; Result += EC->getName(); Result += " = ";
3080 llvm::APSInt Val = EC->getInitVal();
3081 Result += Val.toString(10);
3082 Result += ",\n";
3083 }
3084 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003085 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003086 }
3087 }
3088
3089 Result += "\t";
3090 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003091 return false;
3092}
3093
3094
3095/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3096/// It handles elaborated types, as well as enum types in the process.
3097void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3098 std::string &Result) {
3099 QualType Type = fieldDecl->getType();
3100 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003101
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003102 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3103 if (!EleboratedType)
3104 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003105 Result += Name;
3106 if (fieldDecl->isBitField()) {
3107 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3108 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003109 else if (EleboratedType && Type->isArrayType()) {
3110 CanQualType CType = Context->getCanonicalType(Type);
3111 while (isa<ArrayType>(CType)) {
3112 if (const ConstantArrayType *CAT = Context->getAsConstantArrayType(CType)) {
3113 Result += "[";
3114 llvm::APInt Dim = CAT->getSize();
3115 Result += utostr(Dim.getZExtValue());
3116 Result += "]";
3117 }
3118 CType = CType->getAs<ArrayType>()->getElementType();
3119 }
3120 }
3121
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003122 Result += ";\n";
3123}
3124
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003125/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3126/// an objective-c class with ivars.
3127void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3128 std::string &Result) {
3129 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3130 assert(CDecl->getName() != "" &&
3131 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003132 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003133 SmallVector<ObjCIvarDecl *, 8> IVars;
3134 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003135 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003136 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00003137
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003138 SourceLocation LocStart = CDecl->getLocStart();
3139 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003140
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003141 const char *startBuf = SM->getCharacterData(LocStart);
3142 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003143
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003144 // If no ivars and no root or if its root, directly or indirectly,
3145 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003146 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003147 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3148 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3149 ReplaceText(LocStart, endBuf-startBuf, Result);
3150 return;
3151 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003152
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003153 Result += "\nstruct ";
3154 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003155 Result += "_IMPL {\n";
3156
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003157 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003158 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3159 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3160 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003161 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003162 TagsDefinedInIvarDecls.clear();
3163 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3164 RewriteObjCFieldDecl(IVars[i], Result);
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00003165
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00003166 Result += "};\n";
3167 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3168 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00003169 // Mark this struct as having been generated.
3170 if (!ObjCSynthesizedStructs.insert(CDecl))
3171 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003172}
3173
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003174/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
3175/// have been referenced in an ivar access expression.
3176void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
3177 std::string &Result) {
3178 // write out ivar offset symbols which have been referenced in an ivar
3179 // access expression.
3180 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
3181 if (Ivars.empty())
3182 return;
3183 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
3184 e = Ivars.end(); i != e; i++) {
3185 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00003186 Result += "\n";
3187 if (LangOpts.MicrosoftExt)
3188 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
3189 if (LangOpts.MicrosoftExt &&
3190 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
3191 IvarDecl->getAccessControl() != ObjCIvarDecl::Package) {
3192 const ObjCInterfaceDecl *CDecl = IvarDecl->getContainingInterface();
3193 if (CDecl->getImplementation())
3194 Result += "__declspec(dllexport) ";
3195 }
3196 Result += "extern unsigned long OBJC_IVAR_$_";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00003197 Result += CDecl->getName(); Result += "_";
3198 Result += IvarDecl->getName(); Result += ";";
3199 }
3200}
3201
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003202//===----------------------------------------------------------------------===//
3203// Meta Data Emission
3204//===----------------------------------------------------------------------===//
3205
3206
3207/// RewriteImplementations - This routine rewrites all method implementations
3208/// and emits meta-data.
3209
3210void RewriteModernObjC::RewriteImplementations() {
3211 int ClsDefCount = ClassImplementation.size();
3212 int CatDefCount = CategoryImplementation.size();
3213
3214 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003215 for (int i = 0; i < ClsDefCount; i++) {
3216 ObjCImplementationDecl *OIMP = ClassImplementation[i];
3217 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
3218 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00003219 assert(false &&
3220 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00003221 RewriteImplementationDecl(OIMP);
3222 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003223
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003224 for (int i = 0; i < CatDefCount; i++) {
3225 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
3226 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
3227 if (CDecl->isImplicitInterfaceDecl())
3228 assert(false &&
3229 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00003230 RewriteImplementationDecl(CIMP);
3231 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003232}
3233
3234void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
3235 const std::string &Name,
3236 ValueDecl *VD, bool def) {
3237 assert(BlockByRefDeclNo.count(VD) &&
3238 "RewriteByRefString: ByRef decl missing");
3239 if (def)
3240 ResultStr += "struct ";
3241 ResultStr += "__Block_byref_" + Name +
3242 "_" + utostr(BlockByRefDeclNo[VD]) ;
3243}
3244
3245static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3246 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3247 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
3248 return false;
3249}
3250
3251std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3252 StringRef funcName,
3253 std::string Tag) {
3254 const FunctionType *AFT = CE->getFunctionType();
3255 QualType RT = AFT->getResultType();
3256 std::string StructRef = "struct " + Tag;
3257 std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3258 funcName.str() + "_" + "block_func_" + utostr(i);
3259
3260 BlockDecl *BD = CE->getBlockDecl();
3261
3262 if (isa<FunctionNoProtoType>(AFT)) {
3263 // No user-supplied arguments. Still need to pass in a pointer to the
3264 // block (to reference imported block decl refs).
3265 S += "(" + StructRef + " *__cself)";
3266 } else if (BD->param_empty()) {
3267 S += "(" + StructRef + " *__cself)";
3268 } else {
3269 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3270 assert(FT && "SynthesizeBlockFunc: No function proto");
3271 S += '(';
3272 // first add the implicit argument.
3273 S += StructRef + " *__cself, ";
3274 std::string ParamStr;
3275 for (BlockDecl::param_iterator AI = BD->param_begin(),
3276 E = BD->param_end(); AI != E; ++AI) {
3277 if (AI != BD->param_begin()) S += ", ";
3278 ParamStr = (*AI)->getNameAsString();
3279 QualType QT = (*AI)->getType();
3280 if (convertBlockPointerToFunctionPointer(QT))
3281 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3282 else
3283 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3284 S += ParamStr;
3285 }
3286 if (FT->isVariadic()) {
3287 if (!BD->param_empty()) S += ", ";
3288 S += "...";
3289 }
3290 S += ')';
3291 }
3292 S += " {\n";
3293
3294 // Create local declarations to avoid rewriting all closure decl ref exprs.
3295 // First, emit a declaration for all "by ref" decls.
3296 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3297 E = BlockByRefDecls.end(); I != E; ++I) {
3298 S += " ";
3299 std::string Name = (*I)->getNameAsString();
3300 std::string TypeString;
3301 RewriteByRefString(TypeString, Name, (*I));
3302 TypeString += " *";
3303 Name = TypeString + Name;
3304 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3305 }
3306 // Next, emit a declaration for all "by copy" declarations.
3307 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3308 E = BlockByCopyDecls.end(); I != E; ++I) {
3309 S += " ";
3310 // Handle nested closure invocation. For example:
3311 //
3312 // void (^myImportedClosure)(void);
3313 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
3314 //
3315 // void (^anotherClosure)(void);
3316 // anotherClosure = ^(void) {
3317 // myImportedClosure(); // import and invoke the closure
3318 // };
3319 //
3320 if (isTopLevelBlockPointerType((*I)->getType())) {
3321 RewriteBlockPointerTypeVariable(S, (*I));
3322 S += " = (";
3323 RewriteBlockPointerType(S, (*I)->getType());
3324 S += ")";
3325 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3326 }
3327 else {
3328 std::string Name = (*I)->getNameAsString();
3329 QualType QT = (*I)->getType();
3330 if (HasLocalVariableExternalStorage(*I))
3331 QT = Context->getPointerType(QT);
3332 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3333 S += Name + " = __cself->" +
3334 (*I)->getNameAsString() + "; // bound by copy\n";
3335 }
3336 }
3337 std::string RewrittenStr = RewrittenBlockExprs[CE];
3338 const char *cstr = RewrittenStr.c_str();
3339 while (*cstr++ != '{') ;
3340 S += cstr;
3341 S += "\n";
3342 return S;
3343}
3344
3345std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3346 StringRef funcName,
3347 std::string Tag) {
3348 std::string StructRef = "struct " + Tag;
3349 std::string S = "static void __";
3350
3351 S += funcName;
3352 S += "_block_copy_" + utostr(i);
3353 S += "(" + StructRef;
3354 S += "*dst, " + StructRef;
3355 S += "*src) {";
3356 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3357 E = ImportedBlockDecls.end(); I != E; ++I) {
3358 ValueDecl *VD = (*I);
3359 S += "_Block_object_assign((void*)&dst->";
3360 S += (*I)->getNameAsString();
3361 S += ", (void*)src->";
3362 S += (*I)->getNameAsString();
3363 if (BlockByRefDeclsPtrSet.count((*I)))
3364 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3365 else if (VD->getType()->isBlockPointerType())
3366 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3367 else
3368 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3369 }
3370 S += "}\n";
3371
3372 S += "\nstatic void __";
3373 S += funcName;
3374 S += "_block_dispose_" + utostr(i);
3375 S += "(" + StructRef;
3376 S += "*src) {";
3377 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
3378 E = ImportedBlockDecls.end(); I != E; ++I) {
3379 ValueDecl *VD = (*I);
3380 S += "_Block_object_dispose((void*)src->";
3381 S += (*I)->getNameAsString();
3382 if (BlockByRefDeclsPtrSet.count((*I)))
3383 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3384 else if (VD->getType()->isBlockPointerType())
3385 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3386 else
3387 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3388 }
3389 S += "}\n";
3390 return S;
3391}
3392
3393std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3394 std::string Desc) {
3395 std::string S = "\nstruct " + Tag;
3396 std::string Constructor = " " + Tag;
3397
3398 S += " {\n struct __block_impl impl;\n";
3399 S += " struct " + Desc;
3400 S += "* Desc;\n";
3401
3402 Constructor += "(void *fp, "; // Invoke function pointer.
3403 Constructor += "struct " + Desc; // Descriptor pointer.
3404 Constructor += " *desc";
3405
3406 if (BlockDeclRefs.size()) {
3407 // Output all "by copy" declarations.
3408 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3409 E = BlockByCopyDecls.end(); I != E; ++I) {
3410 S += " ";
3411 std::string FieldName = (*I)->getNameAsString();
3412 std::string ArgName = "_" + FieldName;
3413 // Handle nested closure invocation. For example:
3414 //
3415 // void (^myImportedBlock)(void);
3416 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
3417 //
3418 // void (^anotherBlock)(void);
3419 // anotherBlock = ^(void) {
3420 // myImportedBlock(); // import and invoke the closure
3421 // };
3422 //
3423 if (isTopLevelBlockPointerType((*I)->getType())) {
3424 S += "struct __block_impl *";
3425 Constructor += ", void *" + ArgName;
3426 } else {
3427 QualType QT = (*I)->getType();
3428 if (HasLocalVariableExternalStorage(*I))
3429 QT = Context->getPointerType(QT);
3430 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3431 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3432 Constructor += ", " + ArgName;
3433 }
3434 S += FieldName + ";\n";
3435 }
3436 // Output all "by ref" declarations.
3437 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3438 E = BlockByRefDecls.end(); I != E; ++I) {
3439 S += " ";
3440 std::string FieldName = (*I)->getNameAsString();
3441 std::string ArgName = "_" + FieldName;
3442 {
3443 std::string TypeString;
3444 RewriteByRefString(TypeString, FieldName, (*I));
3445 TypeString += " *";
3446 FieldName = TypeString + FieldName;
3447 ArgName = TypeString + ArgName;
3448 Constructor += ", " + ArgName;
3449 }
3450 S += FieldName + "; // by ref\n";
3451 }
3452 // Finish writing the constructor.
3453 Constructor += ", int flags=0)";
3454 // Initialize all "by copy" arguments.
3455 bool firsTime = true;
3456 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
3457 E = BlockByCopyDecls.end(); I != E; ++I) {
3458 std::string Name = (*I)->getNameAsString();
3459 if (firsTime) {
3460 Constructor += " : ";
3461 firsTime = false;
3462 }
3463 else
3464 Constructor += ", ";
3465 if (isTopLevelBlockPointerType((*I)->getType()))
3466 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3467 else
3468 Constructor += Name + "(_" + Name + ")";
3469 }
3470 // Initialize all "by ref" arguments.
3471 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
3472 E = BlockByRefDecls.end(); I != E; ++I) {
3473 std::string Name = (*I)->getNameAsString();
3474 if (firsTime) {
3475 Constructor += " : ";
3476 firsTime = false;
3477 }
3478 else
3479 Constructor += ", ";
3480 Constructor += Name + "(_" + Name + "->__forwarding)";
3481 }
3482
3483 Constructor += " {\n";
3484 if (GlobalVarDecl)
3485 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3486 else
3487 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3488 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3489
3490 Constructor += " Desc = desc;\n";
3491 } else {
3492 // Finish writing the constructor.
3493 Constructor += ", int flags=0) {\n";
3494 if (GlobalVarDecl)
3495 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
3496 else
3497 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
3498 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
3499 Constructor += " Desc = desc;\n";
3500 }
3501 Constructor += " ";
3502 Constructor += "}\n";
3503 S += Constructor;
3504 S += "};\n";
3505 return S;
3506}
3507
3508std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
3509 std::string ImplTag, int i,
3510 StringRef FunName,
3511 unsigned hasCopy) {
3512 std::string S = "\nstatic struct " + DescTag;
3513
3514 S += " {\n unsigned long reserved;\n";
3515 S += " unsigned long Block_size;\n";
3516 if (hasCopy) {
3517 S += " void (*copy)(struct ";
3518 S += ImplTag; S += "*, struct ";
3519 S += ImplTag; S += "*);\n";
3520
3521 S += " void (*dispose)(struct ";
3522 S += ImplTag; S += "*);\n";
3523 }
3524 S += "} ";
3525
3526 S += DescTag + "_DATA = { 0, sizeof(struct ";
3527 S += ImplTag + ")";
3528 if (hasCopy) {
3529 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3530 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3531 }
3532 S += "};\n";
3533 return S;
3534}
3535
3536void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3537 StringRef FunName) {
3538 // Insert declaration for the function in which block literal is used.
3539 if (CurFunctionDeclToDeclareForBlock && !Blocks.empty())
3540 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3541 bool RewriteSC = (GlobalVarDecl &&
3542 !Blocks.empty() &&
3543 GlobalVarDecl->getStorageClass() == SC_Static &&
3544 GlobalVarDecl->getType().getCVRQualifiers());
3545 if (RewriteSC) {
3546 std::string SC(" void __");
3547 SC += GlobalVarDecl->getNameAsString();
3548 SC += "() {}";
3549 InsertText(FunLocStart, SC);
3550 }
3551
3552 // Insert closures that were part of the function.
3553 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
3554 CollectBlockDeclRefInfo(Blocks[i]);
3555 // Need to copy-in the inner copied-in variables not actually used in this
3556 // block.
3557 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00003558 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003559 ValueDecl *VD = Exp->getDecl();
3560 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00003561 if (!VD->hasAttr<BlocksAttr>()) {
3562 if (!BlockByCopyDeclsPtrSet.count(VD)) {
3563 BlockByCopyDeclsPtrSet.insert(VD);
3564 BlockByCopyDecls.push_back(VD);
3565 }
3566 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003567 }
John McCallf4b88a42012-03-10 09:33:50 +00003568
3569 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003570 BlockByRefDeclsPtrSet.insert(VD);
3571 BlockByRefDecls.push_back(VD);
3572 }
John McCallf4b88a42012-03-10 09:33:50 +00003573
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003574 // imported objects in the inner blocks not used in the outer
3575 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00003576 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003577 VD->getType()->isBlockPointerType())
3578 ImportedBlockDecls.insert(VD);
3579 }
3580
3581 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3582 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3583
3584 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3585
3586 InsertText(FunLocStart, CI);
3587
3588 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3589
3590 InsertText(FunLocStart, CF);
3591
3592 if (ImportedBlockDecls.size()) {
3593 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3594 InsertText(FunLocStart, HF);
3595 }
3596 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3597 ImportedBlockDecls.size() > 0);
3598 InsertText(FunLocStart, BD);
3599
3600 BlockDeclRefs.clear();
3601 BlockByRefDecls.clear();
3602 BlockByRefDeclsPtrSet.clear();
3603 BlockByCopyDecls.clear();
3604 BlockByCopyDeclsPtrSet.clear();
3605 ImportedBlockDecls.clear();
3606 }
3607 if (RewriteSC) {
3608 // Must insert any 'const/volatile/static here. Since it has been
3609 // removed as result of rewriting of block literals.
3610 std::string SC;
3611 if (GlobalVarDecl->getStorageClass() == SC_Static)
3612 SC = "static ";
3613 if (GlobalVarDecl->getType().isConstQualified())
3614 SC += "const ";
3615 if (GlobalVarDecl->getType().isVolatileQualified())
3616 SC += "volatile ";
3617 if (GlobalVarDecl->getType().isRestrictQualified())
3618 SC += "restrict ";
3619 InsertText(FunLocStart, SC);
3620 }
3621
3622 Blocks.clear();
3623 InnerDeclRefsCount.clear();
3624 InnerDeclRefs.clear();
3625 RewrittenBlockExprs.clear();
3626}
3627
3628void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3629 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3630 StringRef FuncName = FD->getName();
3631
3632 SynthesizeBlockLiterals(FunLocStart, FuncName);
3633}
3634
3635static void BuildUniqueMethodName(std::string &Name,
3636 ObjCMethodDecl *MD) {
3637 ObjCInterfaceDecl *IFace = MD->getClassInterface();
3638 Name = IFace->getName();
3639 Name += "__" + MD->getSelector().getAsString();
3640 // Convert colons to underscores.
3641 std::string::size_type loc = 0;
3642 while ((loc = Name.find(":", loc)) != std::string::npos)
3643 Name.replace(loc, 1, "_");
3644}
3645
3646void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3647 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3648 //SourceLocation FunLocStart = MD->getLocStart();
3649 SourceLocation FunLocStart = MD->getLocStart();
3650 std::string FuncName;
3651 BuildUniqueMethodName(FuncName, MD);
3652 SynthesizeBlockLiterals(FunLocStart, FuncName);
3653}
3654
3655void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
3656 for (Stmt::child_range CI = S->children(); CI; ++CI)
3657 if (*CI) {
3658 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
3659 GetBlockDeclRefExprs(CBE->getBody());
3660 else
3661 GetBlockDeclRefExprs(*CI);
3662 }
3663 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003664 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3665 if (DRE->refersToEnclosingLocal() &&
3666 HasLocalVariableExternalStorage(DRE->getDecl())) {
3667 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003668 }
3669
3670 return;
3671}
3672
3673void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00003674 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003675 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
3676 for (Stmt::child_range CI = S->children(); CI; ++CI)
3677 if (*CI) {
3678 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
3679 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3680 GetInnerBlockDeclRefExprs(CBE->getBody(),
3681 InnerBlockDeclRefs,
3682 InnerContexts);
3683 }
3684 else
3685 GetInnerBlockDeclRefExprs(*CI,
3686 InnerBlockDeclRefs,
3687 InnerContexts);
3688
3689 }
3690 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00003691 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3692 if (DRE->refersToEnclosingLocal()) {
3693 if (!isa<FunctionDecl>(DRE->getDecl()) &&
3694 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
3695 InnerBlockDeclRefs.push_back(DRE);
3696 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
3697 if (Var->isFunctionOrMethodVarDecl())
3698 ImportedLocalExternalDecls.insert(Var);
3699 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003700 }
3701
3702 return;
3703}
3704
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003705/// convertObjCTypeToCStyleType - This routine converts such objc types
3706/// as qualified objects, and blocks to their closest c/c++ types that
3707/// it can. It returns true if input type was modified.
3708bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
3709 QualType oldT = T;
3710 convertBlockPointerToFunctionPointer(T);
3711 if (T->isFunctionPointerType()) {
3712 QualType PointeeTy;
3713 if (const PointerType* PT = T->getAs<PointerType>()) {
3714 PointeeTy = PT->getPointeeType();
3715 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
3716 T = convertFunctionTypeOfBlocks(FT);
3717 T = Context->getPointerType(T);
3718 }
3719 }
3720 }
3721
3722 convertToUnqualifiedObjCType(T);
3723 return T != oldT;
3724}
3725
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003726/// convertFunctionTypeOfBlocks - This routine converts a function type
3727/// whose result type may be a block pointer or whose argument type(s)
3728/// might be block pointers to an equivalent function type replacing
3729/// all block pointers to function pointers.
3730QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3731 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3732 // FTP will be null for closures that don't take arguments.
3733 // Generate a funky cast.
3734 SmallVector<QualType, 8> ArgTypes;
3735 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003736 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003737
3738 if (FTP) {
3739 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3740 E = FTP->arg_type_end(); I && (I != E); ++I) {
3741 QualType t = *I;
3742 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003743 if (convertObjCTypeToCStyleType(t))
3744 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003745 ArgTypes.push_back(t);
3746 }
3747 }
3748 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00003749 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003750 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
3751 else FuncType = QualType(FT, 0);
3752 return FuncType;
3753}
3754
3755Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3756 // Navigate to relevant type information.
3757 const BlockPointerType *CPT = 0;
3758
3759 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3760 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003761 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3762 CPT = MExpr->getType()->getAs<BlockPointerType>();
3763 }
3764 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3765 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3766 }
3767 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3768 CPT = IEXPR->getType()->getAs<BlockPointerType>();
3769 else if (const ConditionalOperator *CEXPR =
3770 dyn_cast<ConditionalOperator>(BlockExp)) {
3771 Expr *LHSExp = CEXPR->getLHS();
3772 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3773 Expr *RHSExp = CEXPR->getRHS();
3774 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3775 Expr *CONDExp = CEXPR->getCond();
3776 ConditionalOperator *CondExpr =
3777 new (Context) ConditionalOperator(CONDExp,
3778 SourceLocation(), cast<Expr>(LHSStmt),
3779 SourceLocation(), cast<Expr>(RHSStmt),
3780 Exp->getType(), VK_RValue, OK_Ordinary);
3781 return CondExpr;
3782 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3783 CPT = IRE->getType()->getAs<BlockPointerType>();
3784 } else if (const PseudoObjectExpr *POE
3785 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3786 CPT = POE->getType()->castAs<BlockPointerType>();
3787 } else {
3788 assert(1 && "RewriteBlockClass: Bad type");
3789 }
3790 assert(CPT && "RewriteBlockClass: Bad type");
3791 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3792 assert(FT && "RewriteBlockClass: Bad type");
3793 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3794 // FTP will be null for closures that don't take arguments.
3795
3796 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3797 SourceLocation(), SourceLocation(),
3798 &Context->Idents.get("__block_impl"));
3799 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3800
3801 // Generate a funky cast.
3802 SmallVector<QualType, 8> ArgTypes;
3803
3804 // Push the block argument type.
3805 ArgTypes.push_back(PtrBlock);
3806 if (FTP) {
3807 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
3808 E = FTP->arg_type_end(); I && (I != E); ++I) {
3809 QualType t = *I;
3810 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3811 if (!convertBlockPointerToFunctionPointer(t))
3812 convertToUnqualifiedObjCType(t);
3813 ArgTypes.push_back(t);
3814 }
3815 }
3816 // Now do the pointer to function cast.
3817 QualType PtrToFuncCastType
3818 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
3819
3820 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3821
3822 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3823 CK_BitCast,
3824 const_cast<Expr*>(BlockExp));
3825 // Don't forget the parens to enforce the proper binding.
3826 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3827 BlkCast);
3828 //PE->dump();
3829
3830 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3831 SourceLocation(),
3832 &Context->Idents.get("FuncPtr"),
3833 Context->VoidPtrTy, 0,
3834 /*BitWidth=*/0, /*Mutable=*/true,
3835 /*HasInit=*/false);
3836 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
3837 FD->getType(), VK_LValue,
3838 OK_Ordinary);
3839
3840
3841 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3842 CK_BitCast, ME);
3843 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3844
3845 SmallVector<Expr*, 8> BlkExprs;
3846 // Add the implicit argument.
3847 BlkExprs.push_back(BlkCast);
3848 // Add the user arguments.
3849 for (CallExpr::arg_iterator I = Exp->arg_begin(),
3850 E = Exp->arg_end(); I != E; ++I) {
3851 BlkExprs.push_back(*I);
3852 }
3853 CallExpr *CE = new (Context) CallExpr(*Context, PE, &BlkExprs[0],
3854 BlkExprs.size(),
3855 Exp->getType(), VK_RValue,
3856 SourceLocation());
3857 return CE;
3858}
3859
3860// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00003861// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003862// For example:
3863//
3864// int main() {
3865// __block Foo *f;
3866// __block int i;
3867//
3868// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00003869// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003870// i = 77;
3871// };
3872//}
John McCallf4b88a42012-03-10 09:33:50 +00003873Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003874 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3875 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00003876 ValueDecl *VD = DeclRefExp->getDecl();
3877 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003878
3879 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
3880 SourceLocation(),
3881 &Context->Idents.get("__forwarding"),
3882 Context->VoidPtrTy, 0,
3883 /*BitWidth=*/0, /*Mutable=*/true,
3884 /*HasInit=*/false);
3885 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
3886 FD, SourceLocation(),
3887 FD->getType(), VK_LValue,
3888 OK_Ordinary);
3889
3890 StringRef Name = VD->getName();
3891 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
3892 &Context->Idents.get(Name),
3893 Context->VoidPtrTy, 0,
3894 /*BitWidth=*/0, /*Mutable=*/true,
3895 /*HasInit=*/false);
3896 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
3897 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
3898
3899
3900
3901 // Need parens to enforce precedence.
3902 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3903 DeclRefExp->getExprLoc(),
3904 ME);
3905 ReplaceStmt(DeclRefExp, PE);
3906 return PE;
3907}
3908
3909// Rewrites the imported local variable V with external storage
3910// (static, extern, etc.) as *V
3911//
3912Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3913 ValueDecl *VD = DRE->getDecl();
3914 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3915 if (!ImportedLocalExternalDecls.count(Var))
3916 return DRE;
3917 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3918 VK_LValue, OK_Ordinary,
3919 DRE->getLocation());
3920 // Need parens to enforce precedence.
3921 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3922 Exp);
3923 ReplaceStmt(DRE, PE);
3924 return PE;
3925}
3926
3927void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3928 SourceLocation LocStart = CE->getLParenLoc();
3929 SourceLocation LocEnd = CE->getRParenLoc();
3930
3931 // Need to avoid trying to rewrite synthesized casts.
3932 if (LocStart.isInvalid())
3933 return;
3934 // Need to avoid trying to rewrite casts contained in macros.
3935 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3936 return;
3937
3938 const char *startBuf = SM->getCharacterData(LocStart);
3939 const char *endBuf = SM->getCharacterData(LocEnd);
3940 QualType QT = CE->getType();
3941 const Type* TypePtr = QT->getAs<Type>();
3942 if (isa<TypeOfExprType>(TypePtr)) {
3943 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3944 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3945 std::string TypeAsString = "(";
3946 RewriteBlockPointerType(TypeAsString, QT);
3947 TypeAsString += ")";
3948 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3949 return;
3950 }
3951 // advance the location to startArgList.
3952 const char *argPtr = startBuf;
3953
3954 while (*argPtr++ && (argPtr < endBuf)) {
3955 switch (*argPtr) {
3956 case '^':
3957 // Replace the '^' with '*'.
3958 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3959 ReplaceText(LocStart, 1, "*");
3960 break;
3961 }
3962 }
3963 return;
3964}
3965
3966void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3967 SourceLocation DeclLoc = FD->getLocation();
3968 unsigned parenCount = 0;
3969
3970 // We have 1 or more arguments that have closure pointers.
3971 const char *startBuf = SM->getCharacterData(DeclLoc);
3972 const char *startArgList = strchr(startBuf, '(');
3973
3974 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3975
3976 parenCount++;
3977 // advance the location to startArgList.
3978 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3979 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3980
3981 const char *argPtr = startArgList;
3982
3983 while (*argPtr++ && parenCount) {
3984 switch (*argPtr) {
3985 case '^':
3986 // Replace the '^' with '*'.
3987 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3988 ReplaceText(DeclLoc, 1, "*");
3989 break;
3990 case '(':
3991 parenCount++;
3992 break;
3993 case ')':
3994 parenCount--;
3995 break;
3996 }
3997 }
3998 return;
3999}
4000
4001bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4002 const FunctionProtoType *FTP;
4003 const PointerType *PT = QT->getAs<PointerType>();
4004 if (PT) {
4005 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4006 } else {
4007 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4008 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4009 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4010 }
4011 if (FTP) {
4012 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4013 E = FTP->arg_type_end(); I != E; ++I)
4014 if (isTopLevelBlockPointerType(*I))
4015 return true;
4016 }
4017 return false;
4018}
4019
4020bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4021 const FunctionProtoType *FTP;
4022 const PointerType *PT = QT->getAs<PointerType>();
4023 if (PT) {
4024 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4025 } else {
4026 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4027 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4028 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4029 }
4030 if (FTP) {
4031 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4032 E = FTP->arg_type_end(); I != E; ++I) {
4033 if ((*I)->isObjCQualifiedIdType())
4034 return true;
4035 if ((*I)->isObjCObjectPointerType() &&
4036 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4037 return true;
4038 }
4039
4040 }
4041 return false;
4042}
4043
4044void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4045 const char *&RParen) {
4046 const char *argPtr = strchr(Name, '(');
4047 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4048
4049 LParen = argPtr; // output the start.
4050 argPtr++; // skip past the left paren.
4051 unsigned parenCount = 1;
4052
4053 while (*argPtr && parenCount) {
4054 switch (*argPtr) {
4055 case '(': parenCount++; break;
4056 case ')': parenCount--; break;
4057 default: break;
4058 }
4059 if (parenCount) argPtr++;
4060 }
4061 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4062 RParen = argPtr; // output the end
4063}
4064
4065void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4066 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4067 RewriteBlockPointerFunctionArgs(FD);
4068 return;
4069 }
4070 // Handle Variables and Typedefs.
4071 SourceLocation DeclLoc = ND->getLocation();
4072 QualType DeclT;
4073 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4074 DeclT = VD->getType();
4075 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4076 DeclT = TDD->getUnderlyingType();
4077 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4078 DeclT = FD->getType();
4079 else
4080 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4081
4082 const char *startBuf = SM->getCharacterData(DeclLoc);
4083 const char *endBuf = startBuf;
4084 // scan backward (from the decl location) for the end of the previous decl.
4085 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4086 startBuf--;
4087 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4088 std::string buf;
4089 unsigned OrigLength=0;
4090 // *startBuf != '^' if we are dealing with a pointer to function that
4091 // may take block argument types (which will be handled below).
4092 if (*startBuf == '^') {
4093 // Replace the '^' with '*', computing a negative offset.
4094 buf = '*';
4095 startBuf++;
4096 OrigLength++;
4097 }
4098 while (*startBuf != ')') {
4099 buf += *startBuf;
4100 startBuf++;
4101 OrigLength++;
4102 }
4103 buf += ')';
4104 OrigLength++;
4105
4106 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4107 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4108 // Replace the '^' with '*' for arguments.
4109 // Replace id<P> with id/*<>*/
4110 DeclLoc = ND->getLocation();
4111 startBuf = SM->getCharacterData(DeclLoc);
4112 const char *argListBegin, *argListEnd;
4113 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4114 while (argListBegin < argListEnd) {
4115 if (*argListBegin == '^')
4116 buf += '*';
4117 else if (*argListBegin == '<') {
4118 buf += "/*";
4119 buf += *argListBegin++;
4120 OrigLength++;;
4121 while (*argListBegin != '>') {
4122 buf += *argListBegin++;
4123 OrigLength++;
4124 }
4125 buf += *argListBegin;
4126 buf += "*/";
4127 }
4128 else
4129 buf += *argListBegin;
4130 argListBegin++;
4131 OrigLength++;
4132 }
4133 buf += ')';
4134 OrigLength++;
4135 }
4136 ReplaceText(Start, OrigLength, buf);
4137
4138 return;
4139}
4140
4141
4142/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4143/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4144/// struct Block_byref_id_object *src) {
4145/// _Block_object_assign (&_dest->object, _src->object,
4146/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4147/// [|BLOCK_FIELD_IS_WEAK]) // object
4148/// _Block_object_assign(&_dest->object, _src->object,
4149/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4150/// [|BLOCK_FIELD_IS_WEAK]) // block
4151/// }
4152/// And:
4153/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4154/// _Block_object_dispose(_src->object,
4155/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4156/// [|BLOCK_FIELD_IS_WEAK]) // object
4157/// _Block_object_dispose(_src->object,
4158/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4159/// [|BLOCK_FIELD_IS_WEAK]) // block
4160/// }
4161
4162std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4163 int flag) {
4164 std::string S;
4165 if (CopyDestroyCache.count(flag))
4166 return S;
4167 CopyDestroyCache.insert(flag);
4168 S = "static void __Block_byref_id_object_copy_";
4169 S += utostr(flag);
4170 S += "(void *dst, void *src) {\n";
4171
4172 // offset into the object pointer is computed as:
4173 // void * + void* + int + int + void* + void *
4174 unsigned IntSize =
4175 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4176 unsigned VoidPtrSize =
4177 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4178
4179 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4180 S += " _Block_object_assign((char*)dst + ";
4181 S += utostr(offset);
4182 S += ", *(void * *) ((char*)src + ";
4183 S += utostr(offset);
4184 S += "), ";
4185 S += utostr(flag);
4186 S += ");\n}\n";
4187
4188 S += "static void __Block_byref_id_object_dispose_";
4189 S += utostr(flag);
4190 S += "(void *src) {\n";
4191 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4192 S += utostr(offset);
4193 S += "), ";
4194 S += utostr(flag);
4195 S += ");\n}\n";
4196 return S;
4197}
4198
4199/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4200/// the declaration into:
4201/// struct __Block_byref_ND {
4202/// void *__isa; // NULL for everything except __weak pointers
4203/// struct __Block_byref_ND *__forwarding;
4204/// int32_t __flags;
4205/// int32_t __size;
4206/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4207/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4208/// typex ND;
4209/// };
4210///
4211/// It then replaces declaration of ND variable with:
4212/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4213/// __size=sizeof(struct __Block_byref_ND),
4214/// ND=initializer-if-any};
4215///
4216///
4217void RewriteModernObjC::RewriteByRefVar(VarDecl *ND) {
4218 // Insert declaration for the function in which block literal is
4219 // used.
4220 if (CurFunctionDeclToDeclareForBlock)
4221 RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4222 int flag = 0;
4223 int isa = 0;
4224 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4225 if (DeclLoc.isInvalid())
4226 // If type location is missing, it is because of missing type (a warning).
4227 // Use variable's location which is good for this case.
4228 DeclLoc = ND->getLocation();
4229 const char *startBuf = SM->getCharacterData(DeclLoc);
4230 SourceLocation X = ND->getLocEnd();
4231 X = SM->getExpansionLoc(X);
4232 const char *endBuf = SM->getCharacterData(X);
4233 std::string Name(ND->getNameAsString());
4234 std::string ByrefType;
4235 RewriteByRefString(ByrefType, Name, ND, true);
4236 ByrefType += " {\n";
4237 ByrefType += " void *__isa;\n";
4238 RewriteByRefString(ByrefType, Name, ND);
4239 ByrefType += " *__forwarding;\n";
4240 ByrefType += " int __flags;\n";
4241 ByrefType += " int __size;\n";
4242 // Add void *__Block_byref_id_object_copy;
4243 // void *__Block_byref_id_object_dispose; if needed.
4244 QualType Ty = ND->getType();
4245 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty);
4246 if (HasCopyAndDispose) {
4247 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4248 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4249 }
4250
4251 QualType T = Ty;
4252 (void)convertBlockPointerToFunctionPointer(T);
4253 T.getAsStringInternal(Name, Context->getPrintingPolicy());
4254
4255 ByrefType += " " + Name + ";\n";
4256 ByrefType += "};\n";
4257 // Insert this type in global scope. It is needed by helper function.
4258 SourceLocation FunLocStart;
4259 if (CurFunctionDef)
4260 FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4261 else {
4262 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4263 FunLocStart = CurMethodDef->getLocStart();
4264 }
4265 InsertText(FunLocStart, ByrefType);
4266 if (Ty.isObjCGCWeak()) {
4267 flag |= BLOCK_FIELD_IS_WEAK;
4268 isa = 1;
4269 }
4270
4271 if (HasCopyAndDispose) {
4272 flag = BLOCK_BYREF_CALLER;
4273 QualType Ty = ND->getType();
4274 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4275 if (Ty->isBlockPointerType())
4276 flag |= BLOCK_FIELD_IS_BLOCK;
4277 else
4278 flag |= BLOCK_FIELD_IS_OBJECT;
4279 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4280 if (!HF.empty())
4281 InsertText(FunLocStart, HF);
4282 }
4283
4284 // struct __Block_byref_ND ND =
4285 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4286 // initializer-if-any};
4287 bool hasInit = (ND->getInit() != 0);
4288 unsigned flags = 0;
4289 if (HasCopyAndDispose)
4290 flags |= BLOCK_HAS_COPY_DISPOSE;
4291 Name = ND->getNameAsString();
4292 ByrefType.clear();
4293 RewriteByRefString(ByrefType, Name, ND);
4294 std::string ForwardingCastType("(");
4295 ForwardingCastType += ByrefType + " *)";
4296 if (!hasInit) {
4297 ByrefType += " " + Name + " = {(void*)";
4298 ByrefType += utostr(isa);
4299 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4300 ByrefType += utostr(flags);
4301 ByrefType += ", ";
4302 ByrefType += "sizeof(";
4303 RewriteByRefString(ByrefType, Name, ND);
4304 ByrefType += ")";
4305 if (HasCopyAndDispose) {
4306 ByrefType += ", __Block_byref_id_object_copy_";
4307 ByrefType += utostr(flag);
4308 ByrefType += ", __Block_byref_id_object_dispose_";
4309 ByrefType += utostr(flag);
4310 }
4311 ByrefType += "};\n";
4312 unsigned nameSize = Name.size();
4313 // for block or function pointer declaration. Name is aleady
4314 // part of the declaration.
4315 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
4316 nameSize = 1;
4317 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4318 }
4319 else {
4320 SourceLocation startLoc;
4321 Expr *E = ND->getInit();
4322 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4323 startLoc = ECE->getLParenLoc();
4324 else
4325 startLoc = E->getLocStart();
4326 startLoc = SM->getExpansionLoc(startLoc);
4327 endBuf = SM->getCharacterData(startLoc);
4328 ByrefType += " " + Name;
4329 ByrefType += " = {(void*)";
4330 ByrefType += utostr(isa);
4331 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
4332 ByrefType += utostr(flags);
4333 ByrefType += ", ";
4334 ByrefType += "sizeof(";
4335 RewriteByRefString(ByrefType, Name, ND);
4336 ByrefType += "), ";
4337 if (HasCopyAndDispose) {
4338 ByrefType += "__Block_byref_id_object_copy_";
4339 ByrefType += utostr(flag);
4340 ByrefType += ", __Block_byref_id_object_dispose_";
4341 ByrefType += utostr(flag);
4342 ByrefType += ", ";
4343 }
4344 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4345
4346 // Complete the newly synthesized compound expression by inserting a right
4347 // curly brace before the end of the declaration.
4348 // FIXME: This approach avoids rewriting the initializer expression. It
4349 // also assumes there is only one declarator. For example, the following
4350 // isn't currently supported by this routine (in general):
4351 //
4352 // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4353 //
4354 const char *startInitializerBuf = SM->getCharacterData(startLoc);
4355 const char *semiBuf = strchr(startInitializerBuf, ';');
4356 assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4357 SourceLocation semiLoc =
4358 startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4359
4360 InsertText(semiLoc, "}");
4361 }
4362 return;
4363}
4364
4365void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4366 // Add initializers for any closure decl refs.
4367 GetBlockDeclRefExprs(Exp->getBody());
4368 if (BlockDeclRefs.size()) {
4369 // Unique all "by copy" declarations.
4370 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004371 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004372 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4373 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4374 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4375 }
4376 }
4377 // Unique all "by ref" declarations.
4378 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004379 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004380 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4381 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4382 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4383 }
4384 }
4385 // Find any imported blocks...they will need special attention.
4386 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004387 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004388 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4389 BlockDeclRefs[i]->getType()->isBlockPointerType())
4390 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4391 }
4392}
4393
4394FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
4395 IdentifierInfo *ID = &Context->Idents.get(name);
4396 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4397 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4398 SourceLocation(), ID, FType, 0, SC_Extern,
4399 SC_None, false, false);
4400}
4401
4402Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00004403 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004404 const BlockDecl *block = Exp->getBlockDecl();
4405 Blocks.push_back(Exp);
4406
4407 CollectBlockDeclRefInfo(Exp);
4408
4409 // Add inner imported variables now used in current block.
4410 int countOfInnerDecls = 0;
4411 if (!InnerBlockDeclRefs.empty()) {
4412 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00004413 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004414 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00004415 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004416 // We need to save the copied-in variables in nested
4417 // blocks because it is needed at the end for some of the API generations.
4418 // See SynthesizeBlockLiterals routine.
4419 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4420 BlockDeclRefs.push_back(Exp);
4421 BlockByCopyDeclsPtrSet.insert(VD);
4422 BlockByCopyDecls.push_back(VD);
4423 }
John McCallf4b88a42012-03-10 09:33:50 +00004424 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004425 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4426 BlockDeclRefs.push_back(Exp);
4427 BlockByRefDeclsPtrSet.insert(VD);
4428 BlockByRefDecls.push_back(VD);
4429 }
4430 }
4431 // Find any imported blocks...they will need special attention.
4432 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00004433 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004434 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
4435 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
4436 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4437 }
4438 InnerDeclRefsCount.push_back(countOfInnerDecls);
4439
4440 std::string FuncName;
4441
4442 if (CurFunctionDef)
4443 FuncName = CurFunctionDef->getNameAsString();
4444 else if (CurMethodDef)
4445 BuildUniqueMethodName(FuncName, CurMethodDef);
4446 else if (GlobalVarDecl)
4447 FuncName = std::string(GlobalVarDecl->getNameAsString());
4448
4449 std::string BlockNumber = utostr(Blocks.size()-1);
4450
4451 std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4452 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4453
4454 // Get a pointer to the function type so we can cast appropriately.
4455 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4456 QualType FType = Context->getPointerType(BFT);
4457
4458 FunctionDecl *FD;
4459 Expr *NewRep;
4460
4461 // Simulate a contructor call...
4462 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00004463 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004464 SourceLocation());
4465
4466 SmallVector<Expr*, 4> InitExprs;
4467
4468 // Initialize the block function.
4469 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00004470 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4471 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004472 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4473 CK_BitCast, Arg);
4474 InitExprs.push_back(castExpr);
4475
4476 // Initialize the block descriptor.
4477 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4478
4479 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
4480 SourceLocation(), SourceLocation(),
4481 &Context->Idents.get(DescData.c_str()),
4482 Context->VoidPtrTy, 0,
4483 SC_Static, SC_None);
4484 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00004485 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004486 Context->VoidPtrTy,
4487 VK_LValue,
4488 SourceLocation()),
4489 UO_AddrOf,
4490 Context->getPointerType(Context->VoidPtrTy),
4491 VK_RValue, OK_Ordinary,
4492 SourceLocation());
4493 InitExprs.push_back(DescRefExpr);
4494
4495 // Add initializers for any closure decl refs.
4496 if (BlockDeclRefs.size()) {
4497 Expr *Exp;
4498 // Output all "by copy" declarations.
4499 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4500 E = BlockByCopyDecls.end(); I != E; ++I) {
4501 if (isObjCType((*I)->getType())) {
4502 // FIXME: Conform to ABI ([[obj retain] autorelease]).
4503 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004504 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4505 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004506 if (HasLocalVariableExternalStorage(*I)) {
4507 QualType QT = (*I)->getType();
4508 QT = Context->getPointerType(QT);
4509 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4510 OK_Ordinary, SourceLocation());
4511 }
4512 } else if (isTopLevelBlockPointerType((*I)->getType())) {
4513 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004514 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
4515 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004516 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
4517 CK_BitCast, Arg);
4518 } else {
4519 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004520 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
4521 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004522 if (HasLocalVariableExternalStorage(*I)) {
4523 QualType QT = (*I)->getType();
4524 QT = Context->getPointerType(QT);
4525 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4526 OK_Ordinary, SourceLocation());
4527 }
4528
4529 }
4530 InitExprs.push_back(Exp);
4531 }
4532 // Output all "by ref" declarations.
4533 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4534 E = BlockByRefDecls.end(); I != E; ++I) {
4535 ValueDecl *ND = (*I);
4536 std::string Name(ND->getNameAsString());
4537 std::string RecName;
4538 RewriteByRefString(RecName, Name, ND, true);
4539 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4540 + sizeof("struct"));
4541 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4542 SourceLocation(), SourceLocation(),
4543 II);
4544 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4545 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4546
4547 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00004548 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004549 SourceLocation());
4550 bool isNestedCapturedVar = false;
4551 if (block)
4552 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
4553 ce = block->capture_end(); ci != ce; ++ci) {
4554 const VarDecl *variable = ci->getVariable();
4555 if (variable == ND && ci->isNested()) {
4556 assert (ci->isByRef() &&
4557 "SynthBlockInitExpr - captured block variable is not byref");
4558 isNestedCapturedVar = true;
4559 break;
4560 }
4561 }
4562 // captured nested byref variable has its address passed. Do not take
4563 // its address again.
4564 if (!isNestedCapturedVar)
4565 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
4566 Context->getPointerType(Exp->getType()),
4567 VK_RValue, OK_Ordinary, SourceLocation());
4568 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4569 InitExprs.push_back(Exp);
4570 }
4571 }
4572 if (ImportedBlockDecls.size()) {
4573 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4574 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4575 unsigned IntSize =
4576 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4577 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4578 Context->IntTy, SourceLocation());
4579 InitExprs.push_back(FlagExp);
4580 }
4581 NewRep = new (Context) CallExpr(*Context, DRE, &InitExprs[0], InitExprs.size(),
4582 FType, VK_LValue, SourceLocation());
4583 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
4584 Context->getPointerType(NewRep->getType()),
4585 VK_RValue, OK_Ordinary, SourceLocation());
4586 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4587 NewRep);
4588 BlockDeclRefs.clear();
4589 BlockByRefDecls.clear();
4590 BlockByRefDeclsPtrSet.clear();
4591 BlockByCopyDecls.clear();
4592 BlockByCopyDeclsPtrSet.clear();
4593 ImportedBlockDecls.clear();
4594 return NewRep;
4595}
4596
4597bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4598 if (const ObjCForCollectionStmt * CS =
4599 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4600 return CS->getElement() == DS;
4601 return false;
4602}
4603
4604//===----------------------------------------------------------------------===//
4605// Function Body / Expression rewriting
4606//===----------------------------------------------------------------------===//
4607
4608Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4609 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4610 isa<DoStmt>(S) || isa<ForStmt>(S))
4611 Stmts.push_back(S);
4612 else if (isa<ObjCForCollectionStmt>(S)) {
4613 Stmts.push_back(S);
4614 ObjCBcLabelNo.push_back(++BcLabelCount);
4615 }
4616
4617 // Pseudo-object operations and ivar references need special
4618 // treatment because we're going to recursively rewrite them.
4619 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4620 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4621 return RewritePropertyOrImplicitSetter(PseudoOp);
4622 } else {
4623 return RewritePropertyOrImplicitGetter(PseudoOp);
4624 }
4625 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4626 return RewriteObjCIvarRefExpr(IvarRefExpr);
4627 }
4628
4629 SourceRange OrigStmtRange = S->getSourceRange();
4630
4631 // Perform a bottom up rewrite of all children.
4632 for (Stmt::child_range CI = S->children(); CI; ++CI)
4633 if (*CI) {
4634 Stmt *childStmt = (*CI);
4635 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4636 if (newStmt) {
4637 *CI = newStmt;
4638 }
4639 }
4640
4641 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00004642 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004643 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4644 InnerContexts.insert(BE->getBlockDecl());
4645 ImportedLocalExternalDecls.clear();
4646 GetInnerBlockDeclRefExprs(BE->getBody(),
4647 InnerBlockDeclRefs, InnerContexts);
4648 // Rewrite the block body in place.
4649 Stmt *SaveCurrentBody = CurrentBody;
4650 CurrentBody = BE->getBody();
4651 PropParentMap = 0;
4652 // block literal on rhs of a property-dot-sytax assignment
4653 // must be replaced by its synthesize ast so getRewrittenText
4654 // works as expected. In this case, what actually ends up on RHS
4655 // is the blockTranscribed which is the helper function for the
4656 // block literal; as in: self.c = ^() {[ace ARR];};
4657 bool saveDisableReplaceStmt = DisableReplaceStmt;
4658 DisableReplaceStmt = false;
4659 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4660 DisableReplaceStmt = saveDisableReplaceStmt;
4661 CurrentBody = SaveCurrentBody;
4662 PropParentMap = 0;
4663 ImportedLocalExternalDecls.clear();
4664 // Now we snarf the rewritten text and stash it away for later use.
4665 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4666 RewrittenBlockExprs[BE] = Str;
4667
4668 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4669
4670 //blockTranscribed->dump();
4671 ReplaceStmt(S, blockTranscribed);
4672 return blockTranscribed;
4673 }
4674 // Handle specific things.
4675 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4676 return RewriteAtEncode(AtEncode);
4677
4678 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4679 return RewriteAtSelector(AtSelector);
4680
4681 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4682 return RewriteObjCStringLiteral(AtString);
4683
4684 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4685#if 0
4686 // Before we rewrite it, put the original message expression in a comment.
4687 SourceLocation startLoc = MessExpr->getLocStart();
4688 SourceLocation endLoc = MessExpr->getLocEnd();
4689
4690 const char *startBuf = SM->getCharacterData(startLoc);
4691 const char *endBuf = SM->getCharacterData(endLoc);
4692
4693 std::string messString;
4694 messString += "// ";
4695 messString.append(startBuf, endBuf-startBuf+1);
4696 messString += "\n";
4697
4698 // FIXME: Missing definition of
4699 // InsertText(clang::SourceLocation, char const*, unsigned int).
4700 // InsertText(startLoc, messString.c_str(), messString.size());
4701 // Tried this, but it didn't work either...
4702 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4703#endif
4704 return RewriteMessageExpr(MessExpr);
4705 }
4706
4707 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4708 return RewriteObjCTryStmt(StmtTry);
4709
4710 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4711 return RewriteObjCSynchronizedStmt(StmtTry);
4712
4713 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4714 return RewriteObjCThrowStmt(StmtThrow);
4715
4716 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4717 return RewriteObjCProtocolExpr(ProtocolExp);
4718
4719 if (ObjCForCollectionStmt *StmtForCollection =
4720 dyn_cast<ObjCForCollectionStmt>(S))
4721 return RewriteObjCForCollectionStmt(StmtForCollection,
4722 OrigStmtRange.getEnd());
4723 if (BreakStmt *StmtBreakStmt =
4724 dyn_cast<BreakStmt>(S))
4725 return RewriteBreakStmt(StmtBreakStmt);
4726 if (ContinueStmt *StmtContinueStmt =
4727 dyn_cast<ContinueStmt>(S))
4728 return RewriteContinueStmt(StmtContinueStmt);
4729
4730 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4731 // and cast exprs.
4732 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4733 // FIXME: What we're doing here is modifying the type-specifier that
4734 // precedes the first Decl. In the future the DeclGroup should have
4735 // a separate type-specifier that we can rewrite.
4736 // NOTE: We need to avoid rewriting the DeclStmt if it is within
4737 // the context of an ObjCForCollectionStmt. For example:
4738 // NSArray *someArray;
4739 // for (id <FooProtocol> index in someArray) ;
4740 // This is because RewriteObjCForCollectionStmt() does textual rewriting
4741 // and it depends on the original text locations/positions.
4742 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
4743 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4744
4745 // Blocks rewrite rules.
4746 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
4747 DI != DE; ++DI) {
4748 Decl *SD = *DI;
4749 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4750 if (isTopLevelBlockPointerType(ND->getType()))
4751 RewriteBlockPointerDecl(ND);
4752 else if (ND->getType()->isFunctionPointerType())
4753 CheckFunctionPointerDecl(ND->getType(), ND);
4754 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4755 if (VD->hasAttr<BlocksAttr>()) {
4756 static unsigned uniqueByrefDeclCount = 0;
4757 assert(!BlockByRefDeclNo.count(ND) &&
4758 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4759 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4760 RewriteByRefVar(VD);
4761 }
4762 else
4763 RewriteTypeOfDecl(VD);
4764 }
4765 }
4766 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4767 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4768 RewriteBlockPointerDecl(TD);
4769 else if (TD->getUnderlyingType()->isFunctionPointerType())
4770 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4771 }
4772 }
4773 }
4774
4775 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4776 RewriteObjCQualifiedInterfaceTypes(CE);
4777
4778 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4779 isa<DoStmt>(S) || isa<ForStmt>(S)) {
4780 assert(!Stmts.empty() && "Statement stack is empty");
4781 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4782 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4783 && "Statement stack mismatch");
4784 Stmts.pop_back();
4785 }
4786 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004787 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4788 ValueDecl *VD = DRE->getDecl();
4789 if (VD->hasAttr<BlocksAttr>())
4790 return RewriteBlockDeclRefExpr(DRE);
4791 if (HasLocalVariableExternalStorage(VD))
4792 return RewriteLocalVariableExternalStorage(DRE);
4793 }
4794
4795 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4796 if (CE->getCallee()->getType()->isBlockPointerType()) {
4797 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4798 ReplaceStmt(S, BlockCall);
4799 return BlockCall;
4800 }
4801 }
4802 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4803 RewriteCastExpr(CE);
4804 }
4805#if 0
4806 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4807 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4808 ICE->getSubExpr(),
4809 SourceLocation());
4810 // Get the new text.
4811 std::string SStr;
4812 llvm::raw_string_ostream Buf(SStr);
4813 Replacement->printPretty(Buf, *Context);
4814 const std::string &Str = Buf.str();
4815
4816 printf("CAST = %s\n", &Str[0]);
4817 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
4818 delete S;
4819 return Replacement;
4820 }
4821#endif
4822 // Return this stmt unmodified.
4823 return S;
4824}
4825
4826void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
4827 for (RecordDecl::field_iterator i = RD->field_begin(),
4828 e = RD->field_end(); i != e; ++i) {
4829 FieldDecl *FD = *i;
4830 if (isTopLevelBlockPointerType(FD->getType()))
4831 RewriteBlockPointerDecl(FD);
4832 if (FD->getType()->isObjCQualifiedIdType() ||
4833 FD->getType()->isObjCQualifiedInterfaceType())
4834 RewriteObjCQualifiedInterfaceTypes(FD);
4835 }
4836}
4837
4838/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4839/// main file of the input.
4840void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
4841 switch (D->getKind()) {
4842 case Decl::Function: {
4843 FunctionDecl *FD = cast<FunctionDecl>(D);
4844 if (FD->isOverloadedOperator())
4845 return;
4846
4847 // Since function prototypes don't have ParmDecl's, we check the function
4848 // prototype. This enables us to rewrite function declarations and
4849 // definitions using the same code.
4850 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4851
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00004852 if (!FD->isThisDeclarationADefinition())
4853 break;
4854
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004855 // FIXME: If this should support Obj-C++, support CXXTryStmt
4856 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4857 CurFunctionDef = FD;
4858 CurFunctionDeclToDeclareForBlock = FD;
4859 CurrentBody = Body;
4860 Body =
4861 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4862 FD->setBody(Body);
4863 CurrentBody = 0;
4864 if (PropParentMap) {
4865 delete PropParentMap;
4866 PropParentMap = 0;
4867 }
4868 // This synthesizes and inserts the block "impl" struct, invoke function,
4869 // and any copy/dispose helper functions.
4870 InsertBlockLiteralsWithinFunction(FD);
4871 CurFunctionDef = 0;
4872 CurFunctionDeclToDeclareForBlock = 0;
4873 }
4874 break;
4875 }
4876 case Decl::ObjCMethod: {
4877 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4878 if (CompoundStmt *Body = MD->getCompoundBody()) {
4879 CurMethodDef = MD;
4880 CurrentBody = Body;
4881 Body =
4882 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4883 MD->setBody(Body);
4884 CurrentBody = 0;
4885 if (PropParentMap) {
4886 delete PropParentMap;
4887 PropParentMap = 0;
4888 }
4889 InsertBlockLiteralsWithinMethod(MD);
4890 CurMethodDef = 0;
4891 }
4892 break;
4893 }
4894 case Decl::ObjCImplementation: {
4895 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4896 ClassImplementation.push_back(CI);
4897 break;
4898 }
4899 case Decl::ObjCCategoryImpl: {
4900 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4901 CategoryImplementation.push_back(CI);
4902 break;
4903 }
4904 case Decl::Var: {
4905 VarDecl *VD = cast<VarDecl>(D);
4906 RewriteObjCQualifiedInterfaceTypes(VD);
4907 if (isTopLevelBlockPointerType(VD->getType()))
4908 RewriteBlockPointerDecl(VD);
4909 else if (VD->getType()->isFunctionPointerType()) {
4910 CheckFunctionPointerDecl(VD->getType(), VD);
4911 if (VD->getInit()) {
4912 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4913 RewriteCastExpr(CE);
4914 }
4915 }
4916 } else if (VD->getType()->isRecordType()) {
4917 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
4918 if (RD->isCompleteDefinition())
4919 RewriteRecordBody(RD);
4920 }
4921 if (VD->getInit()) {
4922 GlobalVarDecl = VD;
4923 CurrentBody = VD->getInit();
4924 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4925 CurrentBody = 0;
4926 if (PropParentMap) {
4927 delete PropParentMap;
4928 PropParentMap = 0;
4929 }
4930 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4931 GlobalVarDecl = 0;
4932
4933 // This is needed for blocks.
4934 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4935 RewriteCastExpr(CE);
4936 }
4937 }
4938 break;
4939 }
4940 case Decl::TypeAlias:
4941 case Decl::Typedef: {
4942 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4943 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4944 RewriteBlockPointerDecl(TD);
4945 else if (TD->getUnderlyingType()->isFunctionPointerType())
4946 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4947 }
4948 break;
4949 }
4950 case Decl::CXXRecord:
4951 case Decl::Record: {
4952 RecordDecl *RD = cast<RecordDecl>(D);
4953 if (RD->isCompleteDefinition())
4954 RewriteRecordBody(RD);
4955 break;
4956 }
4957 default:
4958 break;
4959 }
4960 // Nothing yet.
4961}
4962
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00004963/// Write_ProtocolExprReferencedMetadata - This routine writer out the
4964/// protocol reference symbols in the for of:
4965/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
4966static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
4967 ObjCProtocolDecl *PDecl,
4968 std::string &Result) {
4969 // Also output .objc_protorefs$B section and its meta-data.
4970 if (Context->getLangOpts().MicrosoftExt)
4971 Result += "__declspec(allocate(\".objc_protorefs$B\")) ";
4972 Result += "struct _protocol_t *";
4973 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
4974 Result += PDecl->getNameAsString();
4975 Result += " = &";
4976 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
4977 Result += ";\n";
4978}
4979
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004980void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
4981 if (Diags.hasErrorOccurred())
4982 return;
4983
4984 RewriteInclude();
4985
4986 // Here's a great place to add any extra declarations that may be needed.
4987 // Write out meta data for each @protocol(<expr>).
4988 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00004989 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00004990 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00004991 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
4992 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004993
4994 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian57317782012-02-21 23:58:41 +00004995 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
4996 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
4997 // Write struct declaration for the class matching its ivar declarations.
4998 // Note that for modern abi, this is postponed until the end of TU
4999 // because class extensions and the implementation might declare their own
5000 // private ivars.
5001 RewriteInterfaceDecl(CDecl);
5002 }
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00005003
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005004 if (ClassImplementation.size() || CategoryImplementation.size())
5005 RewriteImplementations();
5006
5007 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5008 // we are done.
5009 if (const RewriteBuffer *RewriteBuf =
5010 Rewrite.getRewriteBufferFor(MainFileID)) {
5011 //printf("Changed:\n");
5012 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5013 } else {
5014 llvm::errs() << "No changes\n";
5015 }
5016
5017 if (ClassImplementation.size() || CategoryImplementation.size() ||
5018 ProtocolExprDecls.size()) {
5019 // Rewrite Objective-c meta data*
5020 std::string ResultStr;
5021 RewriteMetaDataIntoBuffer(ResultStr);
5022 // Emit metadata.
5023 *OutFile << ResultStr;
5024 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005025 // Emit ImageInfo;
5026 {
5027 std::string ResultStr;
5028 WriteImageInfo(ResultStr);
5029 *OutFile << ResultStr;
5030 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005031 OutFile->flush();
5032}
5033
5034void RewriteModernObjC::Initialize(ASTContext &context) {
5035 InitializeCommon(context);
5036
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00005037 Preamble += "#ifndef __OBJC2__\n";
5038 Preamble += "#define __OBJC2__\n";
5039 Preamble += "#endif\n";
5040
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005041 // declaring objc_selector outside the parameter list removes a silly
5042 // scope related warning...
5043 if (IsHeader)
5044 Preamble = "#pragma once\n";
5045 Preamble += "struct objc_selector; struct objc_class;\n";
5046 Preamble += "struct __rw_objc_super { struct objc_object *object; ";
5047 Preamble += "struct objc_object *superClass; ";
5048 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005049 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005050 // These are currently generated.
5051 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005052 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005053 Preamble += "#pragma section(\".objc_protolist$B\", long, read, write)\n";
5054 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005055 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
5056 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005057 Preamble += "#pragma section(\".objc_protorefs$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005058 // These are generated but not necessary for functionality.
5059 Preamble += "#pragma section(\".datacoal_nt$B\", long, read, write)\n";
5060 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005061 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
5062 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005063 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005064
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005065 // These need be generated for performance. Currently they are not,
5066 // using API calls instead.
5067 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
5068 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
5069 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
5070
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005071 // Add a constructor for creating temporary objects.
5072 Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
5073 ": ";
5074 Preamble += "object(o), superClass(s) {} ";
5075 }
5076 Preamble += "};\n";
5077 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
5078 Preamble += "typedef struct objc_object Protocol;\n";
5079 Preamble += "#define _REWRITER_typedef_Protocol\n";
5080 Preamble += "#endif\n";
5081 if (LangOpts.MicrosoftExt) {
5082 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
5083 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
5084 } else
5085 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
5086 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
5087 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5088 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
5089 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5090 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
5091 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5092 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
5093 Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
5094 Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
5095 Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
5096 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
5097 Preamble += "(const char *);\n";
5098 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
5099 Preamble += "(struct objc_class *);\n";
5100 Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
5101 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005102 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005103 // @synchronized hooks.
Fariborz Jahanian55261af2012-03-19 18:11:32 +00005104 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_enter( struct objc_object *);\n";
5105 Preamble += "__OBJC_RW_DLLIMPORT void objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005106 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
5107 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
5108 Preamble += "struct __objcFastEnumerationState {\n\t";
5109 Preamble += "unsigned long state;\n\t";
5110 Preamble += "void **itemsPtr;\n\t";
5111 Preamble += "unsigned long *mutationsPtr;\n\t";
5112 Preamble += "unsigned long extra[5];\n};\n";
5113 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5114 Preamble += "#define __FASTENUMERATIONSTATE\n";
5115 Preamble += "#endif\n";
5116 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5117 Preamble += "struct __NSConstantStringImpl {\n";
5118 Preamble += " int *isa;\n";
5119 Preamble += " int flags;\n";
5120 Preamble += " char *str;\n";
5121 Preamble += " long length;\n";
5122 Preamble += "};\n";
5123 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5124 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5125 Preamble += "#else\n";
5126 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5127 Preamble += "#endif\n";
5128 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5129 Preamble += "#endif\n";
5130 // Blocks preamble.
5131 Preamble += "#ifndef BLOCK_IMPL\n";
5132 Preamble += "#define BLOCK_IMPL\n";
5133 Preamble += "struct __block_impl {\n";
5134 Preamble += " void *isa;\n";
5135 Preamble += " int Flags;\n";
5136 Preamble += " int Reserved;\n";
5137 Preamble += " void *FuncPtr;\n";
5138 Preamble += "};\n";
5139 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5140 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5141 Preamble += "extern \"C\" __declspec(dllexport) "
5142 "void _Block_object_assign(void *, const void *, const int);\n";
5143 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5144 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5145 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5146 Preamble += "#else\n";
5147 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5148 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5149 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5150 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5151 Preamble += "#endif\n";
5152 Preamble += "#endif\n";
5153 if (LangOpts.MicrosoftExt) {
5154 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5155 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5156 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
5157 Preamble += "#define __attribute__(X)\n";
5158 Preamble += "#endif\n";
5159 Preamble += "#define __weak\n";
5160 }
5161 else {
5162 Preamble += "#define __block\n";
5163 Preamble += "#define __weak\n";
5164 }
5165 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5166 // as this avoids warning in any 64bit/32bit compilation model.
5167 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5168}
5169
5170/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
5171/// ivar offset.
5172void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
5173 std::string &Result) {
5174 if (ivar->isBitField()) {
5175 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5176 // place all bitfields at offset 0.
5177 Result += "0";
5178 } else {
5179 Result += "__OFFSETOFIVAR__(struct ";
5180 Result += ivar->getContainingInterface()->getNameAsString();
5181 if (LangOpts.MicrosoftExt)
5182 Result += "_IMPL";
5183 Result += ", ";
5184 Result += ivar->getNameAsString();
5185 Result += ")";
5186 }
5187}
5188
5189/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
5190/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005191/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005192/// char *attributes;
5193/// }
5194
5195/// struct _prop_list_t {
5196/// uint32_t entsize; // sizeof(struct _prop_t)
5197/// uint32_t count_of_properties;
5198/// struct _prop_t prop_list[count_of_properties];
5199/// }
5200
5201/// struct _protocol_t;
5202
5203/// struct _protocol_list_t {
5204/// long protocol_count; // Note, this is 32/64 bit
5205/// struct _protocol_t * protocol_list[protocol_count];
5206/// }
5207
5208/// struct _objc_method {
5209/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005210/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005211/// char *_imp;
5212/// }
5213
5214/// struct _method_list_t {
5215/// uint32_t entsize; // sizeof(struct _objc_method)
5216/// uint32_t method_count;
5217/// struct _objc_method method_list[method_count];
5218/// }
5219
5220/// struct _protocol_t {
5221/// id isa; // NULL
5222/// const char * const protocol_name;
5223/// const struct _protocol_list_t * protocol_list; // super protocols
5224/// const struct method_list_t * const instance_methods;
5225/// const struct method_list_t * const class_methods;
5226/// const struct method_list_t *optionalInstanceMethods;
5227/// const struct method_list_t *optionalClassMethods;
5228/// const struct _prop_list_t * properties;
5229/// const uint32_t size; // sizeof(struct _protocol_t)
5230/// const uint32_t flags; // = 0
5231/// const char ** extendedMethodTypes;
5232/// }
5233
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005234/// struct _ivar_t {
5235/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00005236/// const char *name;
5237/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005238/// uint32_t alignment;
5239/// uint32_t size;
5240/// }
5241
5242/// struct _ivar_list_t {
5243/// uint32 entsize; // sizeof(struct _ivar_t)
5244/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00005245/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005246/// }
5247
5248/// struct _class_ro_t {
5249/// uint32_t const flags;
5250/// uint32_t const instanceStart;
5251/// uint32_t const instanceSize;
5252/// uint32_t const reserved; // only when building for 64bit targets
5253/// const uint8_t * const ivarLayout;
5254/// const char *const name;
5255/// const struct _method_list_t * const baseMethods;
Fariborz Jahanian0a525342012-02-14 19:31:35 +00005256/// const struct _protocol_list_t *const baseProtocols;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005257/// const struct _ivar_list_t *const ivars;
5258/// const uint8_t * const weakIvarLayout;
5259/// const struct _prop_list_t * const properties;
5260/// }
5261
5262/// struct _class_t {
5263/// struct _class_t *isa;
5264/// struct _class_t * const superclass;
5265/// void *cache;
5266/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005267/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005268/// }
5269
5270/// struct _category_t {
5271/// const char * const name;
5272/// struct _class_t *const cls;
5273/// const struct _method_list_t * const instance_methods;
5274/// const struct _method_list_t * const class_methods;
5275/// const struct _protocol_list_t * const protocols;
5276/// const struct _prop_list_t * const properties;
5277/// }
5278
5279/// MessageRefTy - LLVM for:
5280/// struct _message_ref_t {
5281/// IMP messenger;
5282/// SEL name;
5283/// };
5284
5285/// SuperMessageRefTy - LLVM for:
5286/// struct _super_message_ref_t {
5287/// SUPER_IMP messenger;
5288/// SEL name;
5289/// };
5290
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005291static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005292 static bool meta_data_declared = false;
5293 if (meta_data_declared)
5294 return;
5295
5296 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005297 Result += "\tconst char *name;\n";
5298 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005299 Result += "};\n";
5300
5301 Result += "\nstruct _protocol_t;\n";
5302
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005303 Result += "\nstruct _objc_method {\n";
5304 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005305 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005306 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005307 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005308
5309 Result += "\nstruct _protocol_t {\n";
5310 Result += "\tvoid * isa; // NULL\n";
5311 Result += "\tconst char * const protocol_name;\n";
5312 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
5313 Result += "\tconst struct method_list_t * const instance_methods;\n";
5314 Result += "\tconst struct method_list_t * const class_methods;\n";
5315 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
5316 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
5317 Result += "\tconst struct _prop_list_t * properties;\n";
5318 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
5319 Result += "\tconst unsigned int flags; // = 0\n";
5320 Result += "\tconst char ** extendedMethodTypes;\n";
5321 Result += "};\n";
5322
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005323 Result += "\nstruct _ivar_t {\n";
5324 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005325 Result += "\tconst char *name;\n";
5326 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005327 Result += "\tunsigned int alignment;\n";
5328 Result += "\tunsigned int size;\n";
5329 Result += "};\n";
5330
5331 Result += "\nstruct _class_ro_t {\n";
5332 Result += "\tunsigned int const flags;\n";
5333 Result += "\tunsigned int instanceStart;\n";
5334 Result += "\tunsigned int const instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005335 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5336 if (Triple.getArch() == llvm::Triple::x86_64)
5337 Result += "\tunsigned int const reserved;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005338 Result += "\tconst unsigned char * const ivarLayout;\n";
5339 Result += "\tconst char *const name;\n";
5340 Result += "\tconst struct _method_list_t * const baseMethods;\n";
5341 Result += "\tconst struct _objc_protocol_list *const baseProtocols;\n";
5342 Result += "\tconst struct _ivar_list_t *const ivars;\n";
5343 Result += "\tconst unsigned char *const weakIvarLayout;\n";
5344 Result += "\tconst struct _prop_list_t *const properties;\n";
5345 Result += "};\n";
5346
5347 Result += "\nstruct _class_t {\n";
5348 Result += "\tstruct _class_t *isa;\n";
5349 Result += "\tstruct _class_t *const superclass;\n";
5350 Result += "\tvoid *cache;\n";
5351 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005352 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00005353 Result += "};\n";
5354
5355 Result += "\nstruct _category_t {\n";
5356 Result += "\tconst char * const name;\n";
5357 Result += "\tstruct _class_t *const cls;\n";
5358 Result += "\tconst struct _method_list_t *const instance_methods;\n";
5359 Result += "\tconst struct _method_list_t *const class_methods;\n";
5360 Result += "\tconst struct _protocol_list_t *const protocols;\n";
5361 Result += "\tconst struct _prop_list_t *const properties;\n";
5362 Result += "};\n";
5363
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005364 Result += "extern void *_objc_empty_cache;\n";
5365 Result += "extern void *_objc_empty_vtable;\n";
5366
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005367 meta_data_declared = true;
5368}
5369
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005370static void Write_protocol_list_t_TypeDecl(std::string &Result,
5371 long super_protocol_count) {
5372 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
5373 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
5374 Result += "\tstruct _protocol_t *super_protocols[";
5375 Result += utostr(super_protocol_count); Result += "];\n";
5376 Result += "}";
5377}
5378
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005379static void Write_method_list_t_TypeDecl(std::string &Result,
5380 unsigned int method_count) {
5381 Result += "struct /*_method_list_t*/"; Result += " {\n";
5382 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
5383 Result += "\tunsigned int method_count;\n";
5384 Result += "\tstruct _objc_method method_list[";
5385 Result += utostr(method_count); Result += "];\n";
5386 Result += "}";
5387}
5388
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005389static void Write__prop_list_t_TypeDecl(std::string &Result,
5390 unsigned int property_count) {
5391 Result += "struct /*_prop_list_t*/"; Result += " {\n";
5392 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5393 Result += "\tunsigned int count_of_properties;\n";
5394 Result += "\tstruct _prop_t prop_list[";
5395 Result += utostr(property_count); Result += "];\n";
5396 Result += "}";
5397}
5398
Fariborz Jahanianae932952012-02-10 20:47:10 +00005399static void Write__ivar_list_t_TypeDecl(std::string &Result,
5400 unsigned int ivar_count) {
5401 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
5402 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
5403 Result += "\tunsigned int count;\n";
5404 Result += "\tstruct _ivar_t ivar_list[";
5405 Result += utostr(ivar_count); Result += "];\n";
5406 Result += "}";
5407}
5408
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005409static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
5410 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
5411 StringRef VarName,
5412 StringRef ProtocolName) {
5413 if (SuperProtocols.size() > 0) {
5414 Result += "\nstatic ";
5415 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
5416 Result += " "; Result += VarName;
5417 Result += ProtocolName;
5418 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5419 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
5420 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
5421 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
5422 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
5423 Result += SuperPD->getNameAsString();
5424 if (i == e-1)
5425 Result += "\n};\n";
5426 else
5427 Result += ",\n";
5428 }
5429 }
5430}
5431
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005432static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
5433 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005434 ArrayRef<ObjCMethodDecl *> Methods,
5435 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005436 StringRef TopLevelDeclName,
5437 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005438 if (Methods.size() > 0) {
5439 Result += "\nstatic ";
5440 Write_method_list_t_TypeDecl(Result, Methods.size());
5441 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005442 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005443 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5444 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
5445 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
5446 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5447 ObjCMethodDecl *MD = Methods[i];
5448 if (i == 0)
5449 Result += "\t{{(struct objc_selector *)\"";
5450 else
5451 Result += "\t{(struct objc_selector *)\"";
5452 Result += (MD)->getSelector().getAsString(); Result += "\"";
5453 Result += ", ";
5454 std::string MethodTypeString;
5455 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
5456 Result += "\""; Result += MethodTypeString; Result += "\"";
5457 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005458 if (!MethodImpl)
5459 Result += "0";
5460 else {
5461 Result += "(void *)";
5462 Result += RewriteObj.MethodInternalNames[MD];
5463 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005464 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005465 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005466 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005467 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005468 }
5469 Result += "};\n";
5470 }
5471}
5472
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005473static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005474 ASTContext *Context, std::string &Result,
5475 ArrayRef<ObjCPropertyDecl *> Properties,
5476 const Decl *Container,
5477 StringRef VarName,
5478 StringRef ProtocolName) {
5479 if (Properties.size() > 0) {
5480 Result += "\nstatic ";
5481 Write__prop_list_t_TypeDecl(Result, Properties.size());
5482 Result += " "; Result += VarName;
5483 Result += ProtocolName;
5484 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5485 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
5486 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
5487 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
5488 ObjCPropertyDecl *PropDecl = Properties[i];
5489 if (i == 0)
5490 Result += "\t{{\"";
5491 else
5492 Result += "\t{\"";
5493 Result += PropDecl->getName(); Result += "\",";
5494 std::string PropertyTypeString, QuotePropertyTypeString;
5495 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
5496 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
5497 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
5498 if (i == e-1)
5499 Result += "}}\n";
5500 else
5501 Result += "},\n";
5502 }
5503 Result += "};\n";
5504 }
5505}
5506
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005507// Metadata flags
5508enum MetaDataDlags {
5509 CLS = 0x0,
5510 CLS_META = 0x1,
5511 CLS_ROOT = 0x2,
5512 OBJC2_CLS_HIDDEN = 0x10,
5513 CLS_EXCEPTION = 0x20,
5514
5515 /// (Obsolete) ARC-specific: this class has a .release_ivars method
5516 CLS_HAS_IVAR_RELEASER = 0x40,
5517 /// class was compiled with -fobjc-arr
5518 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
5519};
5520
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005521static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
5522 unsigned int flags,
5523 const std::string &InstanceStart,
5524 const std::string &InstanceSize,
5525 ArrayRef<ObjCMethodDecl *>baseMethods,
5526 ArrayRef<ObjCProtocolDecl *>baseProtocols,
5527 ArrayRef<ObjCIvarDecl *>ivars,
5528 ArrayRef<ObjCPropertyDecl *>Properties,
5529 StringRef VarName,
5530 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005531 Result += "\nstatic struct _class_ro_t ";
5532 Result += VarName; Result += ClassName;
5533 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5534 Result += "\t";
5535 Result += llvm::utostr(flags); Result += ", ";
5536 Result += InstanceStart; Result += ", ";
5537 Result += InstanceSize; Result += ", \n";
5538 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005539 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
5540 if (Triple.getArch() == llvm::Triple::x86_64)
5541 // uint32_t const reserved; // only when building for 64bit targets
5542 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005543 // const uint8_t * const ivarLayout;
5544 Result += "0, \n\t";
5545 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005546 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005547 if (baseMethods.size() > 0) {
5548 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005549 if (metaclass)
5550 Result += "_OBJC_$_CLASS_METHODS_";
5551 else
5552 Result += "_OBJC_$_INSTANCE_METHODS_";
5553 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005554 Result += ",\n\t";
5555 }
5556 else
5557 Result += "0, \n\t";
5558
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005559 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005560 Result += "(const struct _objc_protocol_list *)&";
5561 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
5562 Result += ",\n\t";
5563 }
5564 else
5565 Result += "0, \n\t";
5566
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005567 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005568 Result += "(const struct _ivar_list_t *)&";
5569 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
5570 Result += ",\n\t";
5571 }
5572 else
5573 Result += "0, \n\t";
5574
5575 // weakIvarLayout
5576 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00005577 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005578 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00005579 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005580 Result += ",\n";
5581 }
5582 else
5583 Result += "0, \n";
5584
5585 Result += "};\n";
5586}
5587
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005588static void Write_class_t(ASTContext *Context, std::string &Result,
5589 StringRef VarName,
5590 const ObjCInterfaceDecl *CDecl, bool metadata) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005591
5592 if (metadata && !CDecl->getSuperClass()) {
5593 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005594 Result += "\n";
5595 if (CDecl->getImplementation())
5596 Result += "__declspec(dllexport) ";
5597 Result += "extern struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005598 Result += CDecl->getNameAsString();
5599 Result += ";\n";
5600 }
5601 // Also, for possibility of 'super' metadata class not having been defined yet.
5602 if (CDecl->getSuperClass()) {
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00005603 Result += "\n";
5604 if (CDecl->getSuperClass()->getImplementation())
5605 Result += "__declspec(dllexport) ";
5606 Result += "extern struct _class_t ";
5607 Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005608 Result += CDecl->getSuperClass()->getNameAsString();
5609 Result += ";\n";
5610 }
5611
Fariborz Jahaniane57303c2012-03-10 00:39:34 +00005612 Result += "\n__declspec(dllexport) struct _class_t "; Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00005613 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
5614 Result += "\t";
5615 if (metadata) {
5616 if (CDecl->getSuperClass()) {
5617 Result += "&"; Result += VarName;
5618 Result += CDecl->getSuperClass()->getNameAsString();
5619 Result += ",\n\t";
5620 Result += "&"; Result += VarName;
5621 Result += CDecl->getSuperClass()->getNameAsString();
5622 Result += ",\n\t";
5623 }
5624 else {
5625 Result += "&"; Result += VarName;
5626 Result += CDecl->getNameAsString();
5627 Result += ",\n\t";
5628 Result += "&OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
5629 Result += ",\n\t";
5630 }
5631 }
5632 else {
5633 Result += "&OBJC_METACLASS_$_";
5634 Result += CDecl->getNameAsString();
5635 Result += ",\n\t";
5636 if (CDecl->getSuperClass()) {
5637 Result += "&"; Result += VarName;
5638 Result += CDecl->getSuperClass()->getNameAsString();
5639 Result += ",\n\t";
5640 }
5641 else
5642 Result += "0,\n\t";
5643 }
5644 Result += "(void *)&_objc_empty_cache,\n\t";
5645 Result += "(void *)&_objc_empty_vtable,\n\t";
5646 if (metadata)
5647 Result += "&_OBJC_METACLASS_RO_$_";
5648 else
5649 Result += "&_OBJC_CLASS_RO_$_";
5650 Result += CDecl->getNameAsString();
5651 Result += ",\n};\n";
5652}
5653
Fariborz Jahanian61186122012-02-17 18:40:41 +00005654static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
5655 std::string &Result,
5656 StringRef CatName,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005657 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00005658 ArrayRef<ObjCMethodDecl *> InstanceMethods,
5659 ArrayRef<ObjCMethodDecl *> ClassMethods,
5660 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
5661 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005662
5663 StringRef ClassName = ClassDecl->getNameAsString();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005664 // must declare an extern class object in case this class is not implemented
5665 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00005666 Result += "\n";
5667 if (ClassDecl->getImplementation())
5668 Result += "__declspec(dllexport) ";
5669
5670 Result += "extern struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00005671 Result += "OBJC_CLASS_$_"; Result += ClassName;
5672 Result += ";\n";
5673
Fariborz Jahanian61186122012-02-17 18:40:41 +00005674 Result += "\nstatic struct _category_t ";
5675 Result += "_OBJC_$_CATEGORY_";
5676 Result += ClassName; Result += "_$_"; Result += CatName;
5677 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5678 Result += "{\n";
5679 Result += "\t\""; Result += ClassName; Result += "\",\n";
5680 Result += "\t&"; Result += "OBJC_CLASS_$_"; Result += ClassName;
5681 Result += ",\n";
5682 if (InstanceMethods.size() > 0) {
5683 Result += "\t(const struct _method_list_t *)&";
5684 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
5685 Result += ClassName; Result += "_$_"; Result += CatName;
5686 Result += ",\n";
5687 }
5688 else
5689 Result += "\t0,\n";
5690
5691 if (ClassMethods.size() > 0) {
5692 Result += "\t(const struct _method_list_t *)&";
5693 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
5694 Result += ClassName; Result += "_$_"; Result += CatName;
5695 Result += ",\n";
5696 }
5697 else
5698 Result += "\t0,\n";
5699
5700 if (RefedProtocols.size() > 0) {
5701 Result += "\t(const struct _protocol_list_t *)&";
5702 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
5703 Result += ClassName; Result += "_$_"; Result += CatName;
5704 Result += ",\n";
5705 }
5706 else
5707 Result += "\t0,\n";
5708
5709 if (ClassProperties.size() > 0) {
5710 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
5711 Result += ClassName; Result += "_$_"; Result += CatName;
5712 Result += ",\n";
5713 }
5714 else
5715 Result += "\t0,\n";
5716
5717 Result += "};\n";
5718}
5719
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005720static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
5721 ASTContext *Context, std::string &Result,
5722 ArrayRef<ObjCMethodDecl *> Methods,
5723 StringRef VarName,
5724 StringRef ProtocolName) {
5725 if (Methods.size() == 0)
5726 return;
5727
5728 Result += "\nstatic const char *";
5729 Result += VarName; Result += ProtocolName;
5730 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
5731 Result += "{\n";
5732 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
5733 ObjCMethodDecl *MD = Methods[i];
5734 std::string MethodTypeString, QuoteMethodTypeString;
5735 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
5736 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
5737 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
5738 if (i == e-1)
5739 Result += "\n};\n";
5740 else {
5741 Result += ",\n";
5742 }
5743 }
5744}
5745
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005746static void Write_IvarOffsetVar(ASTContext *Context,
5747 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005748 ArrayRef<ObjCIvarDecl *> Ivars,
5749 StringRef VarName,
5750 StringRef ClassName) {
5751 // FIXME. visibilty of offset symbols may have to be set; for Darwin
5752 // this is what happens:
5753 /**
5754 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
5755 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
5756 Class->getVisibility() == HiddenVisibility)
5757 Visibility shoud be: HiddenVisibility;
5758 else
5759 Visibility shoud be: DefaultVisibility;
5760 */
5761
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005762 Result += "\n";
5763 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5764 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005765 if (Context->getLangOpts().MicrosoftExt)
5766 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
5767
5768 if (!Context->getLangOpts().MicrosoftExt ||
5769 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00005770 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00005771 Result += "unsigned long int ";
5772 else
5773 Result += "__declspec(dllexport) unsigned long int ";
5774
5775 Result += VarName;
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005776 Result += ClassName; Result += "_";
5777 Result += IvarDecl->getName();
5778 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
5779 Result += " = ";
5780 if (IvarDecl->isBitField()) {
5781 // FIXME: The hack below doesn't work for bitfields. For now, we simply
5782 // place all bitfields at offset 0.
5783 Result += "0;\n";
5784 }
5785 else {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005786 Result += "__OFFSETOFIVAR__(struct ";
5787 Result += ClassName;
5788 Result += "_IMPL, ";
5789 Result += IvarDecl->getName(); Result += ");\n";
5790 }
5791 }
5792}
5793
Fariborz Jahanianae932952012-02-10 20:47:10 +00005794static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
5795 ASTContext *Context, std::string &Result,
5796 ArrayRef<ObjCIvarDecl *> Ivars,
5797 StringRef VarName,
5798 StringRef ClassName) {
5799 if (Ivars.size() > 0) {
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00005800 Write_IvarOffsetVar(Context, Result, Ivars, "OBJC_IVAR_$_", ClassName);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00005801
Fariborz Jahanianae932952012-02-10 20:47:10 +00005802 Result += "\nstatic ";
5803 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
5804 Result += " "; Result += VarName;
5805 Result += ClassName;
5806 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
5807 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
5808 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
5809 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
5810 ObjCIvarDecl *IvarDecl = Ivars[i];
5811 if (i == 0)
5812 Result += "\t{{";
5813 else
5814 Result += "\t {";
Fariborz Jahaniandb649232012-02-13 20:59:02 +00005815
5816 Result += "(unsigned long int *)&OBJC_IVAR_$_";
5817 Result += ClassName; Result += "_"; Result += IvarDecl->getName();
5818 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00005819
5820 Result += "\""; Result += IvarDecl->getName(); Result += "\", ";
5821 std::string IvarTypeString, QuoteIvarTypeString;
5822 Context->getObjCEncodingForType(IvarDecl->getType(), IvarTypeString,
5823 IvarDecl);
5824 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
5825 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
5826
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00005827 // FIXME. this alignment represents the host alignment and need be changed to
5828 // represent the target alignment.
5829 unsigned Align = Context->getTypeAlign(IvarDecl->getType())/8;
5830 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00005831 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00005832 CharUnits Size = Context->getTypeSizeInChars(IvarDecl->getType());
5833 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00005834 if (i == e-1)
5835 Result += "}}\n";
5836 else
5837 Result += "},\n";
5838 }
5839 Result += "};\n";
5840 }
5841}
5842
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005843/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005844void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
5845 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005846
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005847 // Do not synthesize the protocol more than once.
5848 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
5849 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00005850 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005851
5852 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
5853 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005854 // Must write out all protocol definitions in current qualifier list,
5855 // and in their nested qualifiers before writing out current definition.
5856 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5857 E = PDecl->protocol_end(); I != E; ++I)
5858 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005859
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005860 // Construct method lists.
5861 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
5862 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
5863 for (ObjCProtocolDecl::instmeth_iterator
5864 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
5865 I != E; ++I) {
5866 ObjCMethodDecl *MD = *I;
5867 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5868 OptInstanceMethods.push_back(MD);
5869 } else {
5870 InstanceMethods.push_back(MD);
5871 }
5872 }
5873
5874 for (ObjCProtocolDecl::classmeth_iterator
5875 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
5876 I != E; ++I) {
5877 ObjCMethodDecl *MD = *I;
5878 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
5879 OptClassMethods.push_back(MD);
5880 } else {
5881 ClassMethods.push_back(MD);
5882 }
5883 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005884 std::vector<ObjCMethodDecl *> AllMethods;
5885 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
5886 AllMethods.push_back(InstanceMethods[i]);
5887 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
5888 AllMethods.push_back(ClassMethods[i]);
5889 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
5890 AllMethods.push_back(OptInstanceMethods[i]);
5891 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
5892 AllMethods.push_back(OptClassMethods[i]);
5893
5894 Write__extendedMethodTypes_initializer(*this, Context, Result,
5895 AllMethods,
5896 "_OBJC_PROTOCOL_METHOD_TYPES_",
5897 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005898 // Protocol's super protocol list
5899 std::vector<ObjCProtocolDecl *> SuperProtocols;
5900 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
5901 E = PDecl->protocol_end(); I != E; ++I)
5902 SuperProtocols.push_back(*I);
5903
5904 Write_protocol_list_initializer(Context, Result, SuperProtocols,
5905 "_OBJC_PROTOCOL_REFS_",
5906 PDecl->getNameAsString());
5907
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005908 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005909 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005910 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005911
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005912 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005913 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005914 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005915
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005916 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005917 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005918 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005919
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005920 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005921 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00005922 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00005923
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005924 // Protocol's property metadata.
5925 std::vector<ObjCPropertyDecl *> ProtocolProperties;
5926 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
5927 E = PDecl->prop_end(); I != E; ++I)
5928 ProtocolProperties.push_back(*I);
5929
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00005930 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005931 /* Container */0,
5932 "_OBJC_PROTOCOL_PROPERTIES_",
5933 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00005934
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005935 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00005936 Result += "\n";
5937 if (LangOpts.MicrosoftExt)
5938 Result += "__declspec(allocate(\".datacoal_nt$B\")) ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00005939 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005940 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005941 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
5942 Result += "\t0,\n"; // id is; is null
5943 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00005944 if (SuperProtocols.size() > 0) {
5945 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
5946 Result += PDecl->getNameAsString(); Result += ",\n";
5947 }
5948 else
5949 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005950 if (InstanceMethods.size() > 0) {
5951 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
5952 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005953 }
5954 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005955 Result += "\t0,\n";
5956
5957 if (ClassMethods.size() > 0) {
5958 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
5959 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005960 }
5961 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005962 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005963
Fariborz Jahanian82848c22012-02-08 00:50:52 +00005964 if (OptInstanceMethods.size() > 0) {
5965 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
5966 Result += PDecl->getNameAsString(); Result += ",\n";
5967 }
5968 else
5969 Result += "\t0,\n";
5970
5971 if (OptClassMethods.size() > 0) {
5972 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
5973 Result += PDecl->getNameAsString(); Result += ",\n";
5974 }
5975 else
5976 Result += "\t0,\n";
5977
5978 if (ProtocolProperties.size() > 0) {
5979 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
5980 Result += PDecl->getNameAsString(); Result += ",\n";
5981 }
5982 else
5983 Result += "\t0,\n";
5984
5985 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
5986 Result += "\t0,\n";
5987
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00005988 if (AllMethods.size() > 0) {
5989 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
5990 Result += PDecl->getNameAsString();
5991 Result += "\n};\n";
5992 }
5993 else
5994 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00005995
5996 // Use this protocol meta-data to build protocol list table in section
5997 // .objc_protolist$B
5998 // Unspecified visibility means 'private extern'.
5999 if (LangOpts.MicrosoftExt)
6000 Result += "__declspec(allocate(\".objc_protolist$B\")) ";
6001 Result += "struct _protocol_t *";
6002 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
6003 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6004 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00006005
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006006 // Mark this protocol as having been generated.
6007 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
6008 llvm_unreachable("protocol already synthesized");
6009
6010}
6011
6012void RewriteModernObjC::RewriteObjCProtocolListMetaData(
6013 const ObjCList<ObjCProtocolDecl> &Protocols,
6014 StringRef prefix, StringRef ClassName,
6015 std::string &Result) {
6016 if (Protocols.empty()) return;
6017
6018 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006019 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006020
6021 // Output the top lovel protocol meta-data for the class.
6022 /* struct _objc_protocol_list {
6023 struct _objc_protocol_list *next;
6024 int protocol_count;
6025 struct _objc_protocol *class_protocols[];
6026 }
6027 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006028 Result += "\n";
6029 if (LangOpts.MicrosoftExt)
6030 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
6031 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006032 Result += "\tstruct _objc_protocol_list *next;\n";
6033 Result += "\tint protocol_count;\n";
6034 Result += "\tstruct _objc_protocol *class_protocols[";
6035 Result += utostr(Protocols.size());
6036 Result += "];\n} _OBJC_";
6037 Result += prefix;
6038 Result += "_PROTOCOLS_";
6039 Result += ClassName;
6040 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
6041 "{\n\t0, ";
6042 Result += utostr(Protocols.size());
6043 Result += "\n";
6044
6045 Result += "\t,{&_OBJC_PROTOCOL_";
6046 Result += Protocols[0]->getNameAsString();
6047 Result += " \n";
6048
6049 for (unsigned i = 1; i != Protocols.size(); i++) {
6050 Result += "\t ,&_OBJC_PROTOCOL_";
6051 Result += Protocols[i]->getNameAsString();
6052 Result += "\n";
6053 }
6054 Result += "\t }\n};\n";
6055}
6056
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006057/// hasObjCExceptionAttribute - Return true if this class or any super
6058/// class has the __objc_exception__ attribute.
6059/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
6060static bool hasObjCExceptionAttribute(ASTContext &Context,
6061 const ObjCInterfaceDecl *OID) {
6062 if (OID->hasAttr<ObjCExceptionAttr>())
6063 return true;
6064 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
6065 return hasObjCExceptionAttribute(Context, Super);
6066 return false;
6067}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006068
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006069void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
6070 std::string &Result) {
6071 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
6072
6073 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00006074 if (CDecl->isImplicitInterfaceDecl())
6075 assert(false &&
6076 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00006077
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006078 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00006079 SmallVector<ObjCIvarDecl *, 8> IVars;
6080
6081 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6082 IVD; IVD = IVD->getNextIvar()) {
6083 // Ignore unnamed bit-fields.
6084 if (!IVD->getDeclName())
6085 continue;
6086 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006087 }
6088
Fariborz Jahanianae932952012-02-10 20:47:10 +00006089 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006090 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanianae932952012-02-10 20:47:10 +00006091 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006092
6093 // Build _objc_method_list for class's instance methods if needed
6094 SmallVector<ObjCMethodDecl *, 32>
6095 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6096
6097 // If any of our property implementations have associated getters or
6098 // setters, produce metadata for them as well.
6099 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6100 PropEnd = IDecl->propimpl_end();
6101 Prop != PropEnd; ++Prop) {
6102 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6103 continue;
6104 if (!(*Prop)->getPropertyIvarDecl())
6105 continue;
6106 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6107 if (!PD)
6108 continue;
6109 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6110 if (!Getter->isDefined())
6111 InstanceMethods.push_back(Getter);
6112 if (PD->isReadOnly())
6113 continue;
6114 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6115 if (!Setter->isDefined())
6116 InstanceMethods.push_back(Setter);
6117 }
6118
6119 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6120 "_OBJC_$_INSTANCE_METHODS_",
6121 IDecl->getNameAsString(), true);
6122
6123 SmallVector<ObjCMethodDecl *, 32>
6124 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6125
6126 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6127 "_OBJC_$_CLASS_METHODS_",
6128 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00006129
6130 // Protocols referenced in class declaration?
6131 // Protocol's super protocol list
6132 std::vector<ObjCProtocolDecl *> RefedProtocols;
6133 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
6134 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
6135 E = Protocols.end();
6136 I != E; ++I) {
6137 RefedProtocols.push_back(*I);
6138 // Must write out all protocol definitions in current qualifier list,
6139 // and in their nested qualifiers before writing out current definition.
6140 RewriteObjCProtocolMetaData(*I, Result);
6141 }
6142
6143 Write_protocol_list_initializer(Context, Result,
6144 RefedProtocols,
6145 "_OBJC_CLASS_PROTOCOLS_$_",
6146 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006147
6148 // Protocol's property metadata.
6149 std::vector<ObjCPropertyDecl *> ClassProperties;
6150 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6151 E = CDecl->prop_end(); I != E; ++I)
6152 ClassProperties.push_back(*I);
6153
6154 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6155 /* Container */0,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006156 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006157 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006158
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006159
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006160 // Data for initializing _class_ro_t metaclass meta-data
6161 uint32_t flags = CLS_META;
6162 std::string InstanceSize;
6163 std::string InstanceStart;
6164
6165
6166 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
6167 if (classIsHidden)
6168 flags |= OBJC2_CLS_HIDDEN;
6169
6170 if (!CDecl->getSuperClass())
6171 // class is root
6172 flags |= CLS_ROOT;
6173 InstanceSize = "sizeof(struct _class_t)";
6174 InstanceStart = InstanceSize;
6175 Write__class_ro_t_initializer(Context, Result, flags,
6176 InstanceStart, InstanceSize,
6177 ClassMethods,
6178 0,
6179 0,
6180 0,
6181 "_OBJC_METACLASS_RO_$_",
6182 CDecl->getNameAsString());
6183
6184
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006185 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006186 flags = CLS;
6187 if (classIsHidden)
6188 flags |= OBJC2_CLS_HIDDEN;
6189
6190 if (hasObjCExceptionAttribute(*Context, CDecl))
6191 flags |= CLS_EXCEPTION;
6192
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006193 if (!CDecl->getSuperClass())
6194 // class is root
6195 flags |= CLS_ROOT;
6196
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006197 InstanceSize.clear();
6198 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006199 if (!ObjCSynthesizedStructs.count(CDecl)) {
6200 InstanceSize = "0";
6201 InstanceStart = "0";
6202 }
6203 else {
6204 InstanceSize = "sizeof(struct ";
6205 InstanceSize += CDecl->getNameAsString();
6206 InstanceSize += "_IMPL)";
6207
6208 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
6209 if (IVD) {
6210 InstanceStart += "__OFFSETOFIVAR__(struct ";
6211 InstanceStart += CDecl->getNameAsString();
6212 InstanceStart += "_IMPL, ";
6213 InstanceStart += IVD->getNameAsString();
6214 InstanceStart += ")";
6215 }
6216 else
6217 InstanceStart = InstanceSize;
6218 }
6219 Write__class_ro_t_initializer(Context, Result, flags,
6220 InstanceStart, InstanceSize,
6221 InstanceMethods,
6222 RefedProtocols,
6223 IVars,
6224 ClassProperties,
6225 "_OBJC_CLASS_RO_$_",
6226 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006227
6228 Write_class_t(Context, Result,
6229 "OBJC_METACLASS_$_",
6230 CDecl, /*metaclass*/true);
6231
6232 Write_class_t(Context, Result,
6233 "OBJC_CLASS_$_",
6234 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006235
6236 if (ImplementationIsNonLazy(IDecl))
6237 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006238
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006239}
6240
6241void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
6242 int ClsDefCount = ClassImplementation.size();
6243 int CatDefCount = CategoryImplementation.size();
6244
6245 // For each implemented class, write out all its meta data.
6246 for (int i = 0; i < ClsDefCount; i++)
6247 RewriteObjCClassMetaData(ClassImplementation[i], Result);
6248
6249 // For each implemented category, write out all its meta data.
6250 for (int i = 0; i < CatDefCount; i++)
6251 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
6252
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006253 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006254 if (LangOpts.MicrosoftExt)
6255 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006256 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
6257 Result += llvm::utostr(ClsDefCount); Result += "]";
6258 Result +=
6259 " __attribute__((used, section (\"__DATA, __objc_classlist,"
6260 "regular,no_dead_strip\")))= {\n";
6261 for (int i = 0; i < ClsDefCount; i++) {
6262 Result += "\t&OBJC_CLASS_$_";
6263 Result += ClassImplementation[i]->getNameAsString();
6264 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006265 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00006266 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006267
6268 if (!DefinedNonLazyClasses.empty()) {
6269 if (LangOpts.MicrosoftExt)
6270 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
6271 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
6272 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
6273 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
6274 Result += ",\n";
6275 }
6276 Result += "};\n";
6277 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006278 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00006279
6280 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006281 if (LangOpts.MicrosoftExt)
6282 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006283 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
6284 Result += llvm::utostr(CatDefCount); Result += "]";
6285 Result +=
6286 " __attribute__((used, section (\"__DATA, __objc_catlist,"
6287 "regular,no_dead_strip\")))= {\n";
6288 for (int i = 0; i < CatDefCount; i++) {
6289 Result += "\t&_OBJC_$_CATEGORY_";
6290 Result +=
6291 CategoryImplementation[i]->getClassInterface()->getNameAsString();
6292 Result += "_$_";
6293 Result += CategoryImplementation[i]->getNameAsString();
6294 Result += ",\n";
6295 }
6296 Result += "};\n";
6297 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006298
6299 if (!DefinedNonLazyCategories.empty()) {
6300 if (LangOpts.MicrosoftExt)
6301 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
6302 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
6303 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
6304 Result += "\t&_OBJC_$_CATEGORY_";
6305 Result +=
6306 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
6307 Result += "_$_";
6308 Result += DefinedNonLazyCategories[i]->getNameAsString();
6309 Result += ",\n";
6310 }
6311 Result += "};\n";
6312 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006313}
6314
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006315void RewriteModernObjC::WriteImageInfo(std::string &Result) {
6316 if (LangOpts.MicrosoftExt)
6317 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
6318
6319 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
6320 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006321 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006322}
6323
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006324/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
6325/// implementation.
6326void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
6327 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006328 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006329 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
6330 // Find category declaration for this implementation.
Fariborz Jahanian61186122012-02-17 18:40:41 +00006331 ObjCCategoryDecl *CDecl=0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006332 for (CDecl = ClassDecl->getCategoryList(); CDecl;
6333 CDecl = CDecl->getNextClassCategory())
6334 if (CDecl->getIdentifier() == IDecl->getIdentifier())
6335 break;
6336
6337 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00006338 FullCategoryName += "_$_";
6339 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006340
6341 // Build _objc_method_list for class's instance methods if needed
6342 SmallVector<ObjCMethodDecl *, 32>
6343 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
6344
6345 // If any of our property implementations have associated getters or
6346 // setters, produce metadata for them as well.
6347 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
6348 PropEnd = IDecl->propimpl_end();
6349 Prop != PropEnd; ++Prop) {
6350 if ((*Prop)->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
6351 continue;
6352 if (!(*Prop)->getPropertyIvarDecl())
6353 continue;
6354 ObjCPropertyDecl *PD = (*Prop)->getPropertyDecl();
6355 if (!PD)
6356 continue;
6357 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
6358 InstanceMethods.push_back(Getter);
6359 if (PD->isReadOnly())
6360 continue;
6361 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
6362 InstanceMethods.push_back(Setter);
6363 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006364
Fariborz Jahanian61186122012-02-17 18:40:41 +00006365 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6366 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
6367 FullCategoryName, true);
6368
6369 SmallVector<ObjCMethodDecl *, 32>
6370 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
6371
6372 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6373 "_OBJC_$_CATEGORY_CLASS_METHODS_",
6374 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006375
6376 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00006377 // Protocol's super protocol list
6378 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00006379 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
6380 E = CDecl->protocol_end();
6381
6382 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00006383 RefedProtocols.push_back(*I);
6384 // Must write out all protocol definitions in current qualifier list,
6385 // and in their nested qualifiers before writing out current definition.
6386 RewriteObjCProtocolMetaData(*I, Result);
6387 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006388
Fariborz Jahanian61186122012-02-17 18:40:41 +00006389 Write_protocol_list_initializer(Context, Result,
6390 RefedProtocols,
6391 "_OBJC_CATEGORY_PROTOCOLS_$_",
6392 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006393
Fariborz Jahanian61186122012-02-17 18:40:41 +00006394 // Protocol's property metadata.
6395 std::vector<ObjCPropertyDecl *> ClassProperties;
6396 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
6397 E = CDecl->prop_end(); I != E; ++I)
6398 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006399
Fariborz Jahanian61186122012-02-17 18:40:41 +00006400 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
6401 /* Container */0,
6402 "_OBJC_$_PROP_LIST_",
6403 FullCategoryName);
6404
6405 Write_category_t(*this, Context, Result,
6406 CDecl->getNameAsString(),
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006407 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006408 InstanceMethods,
6409 ClassMethods,
6410 RefedProtocols,
6411 ClassProperties);
6412
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006413 // Determine if this category is also "non-lazy".
6414 if (ImplementationIsNonLazy(IDecl))
6415 DefinedNonLazyCategories.push_back(CDecl);
6416
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006417}
6418
6419// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
6420/// class methods.
6421template<typename MethodIterator>
6422void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
6423 MethodIterator MethodEnd,
6424 bool IsInstanceMethod,
6425 StringRef prefix,
6426 StringRef ClassName,
6427 std::string &Result) {
6428 if (MethodBegin == MethodEnd) return;
6429
6430 if (!objc_impl_method) {
6431 /* struct _objc_method {
6432 SEL _cmd;
6433 char *method_types;
6434 void *_imp;
6435 }
6436 */
6437 Result += "\nstruct _objc_method {\n";
6438 Result += "\tSEL _cmd;\n";
6439 Result += "\tchar *method_types;\n";
6440 Result += "\tvoid *_imp;\n";
6441 Result += "};\n";
6442
6443 objc_impl_method = true;
6444 }
6445
6446 // Build _objc_method_list for class's methods if needed
6447
6448 /* struct {
6449 struct _objc_method_list *next_method;
6450 int method_count;
6451 struct _objc_method method_list[];
6452 }
6453 */
6454 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006455 Result += "\n";
6456 if (LangOpts.MicrosoftExt) {
6457 if (IsInstanceMethod)
6458 Result += "__declspec(allocate(\".inst_meth$B\")) ";
6459 else
6460 Result += "__declspec(allocate(\".cls_meth$B\")) ";
6461 }
6462 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006463 Result += "\tstruct _objc_method_list *next_method;\n";
6464 Result += "\tint method_count;\n";
6465 Result += "\tstruct _objc_method method_list[";
6466 Result += utostr(NumMethods);
6467 Result += "];\n} _OBJC_";
6468 Result += prefix;
6469 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
6470 Result += "_METHODS_";
6471 Result += ClassName;
6472 Result += " __attribute__ ((used, section (\"__OBJC, __";
6473 Result += IsInstanceMethod ? "inst" : "cls";
6474 Result += "_meth\")))= ";
6475 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
6476
6477 Result += "\t,{{(SEL)\"";
6478 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6479 std::string MethodTypeString;
6480 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6481 Result += "\", \"";
6482 Result += MethodTypeString;
6483 Result += "\", (void *)";
6484 Result += MethodInternalNames[*MethodBegin];
6485 Result += "}\n";
6486 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
6487 Result += "\t ,{(SEL)\"";
6488 Result += (*MethodBegin)->getSelector().getAsString().c_str();
6489 std::string MethodTypeString;
6490 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
6491 Result += "\", \"";
6492 Result += MethodTypeString;
6493 Result += "\", (void *)";
6494 Result += MethodInternalNames[*MethodBegin];
6495 Result += "}\n";
6496 }
6497 Result += "\t }\n};\n";
6498}
6499
6500Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
6501 SourceRange OldRange = IV->getSourceRange();
6502 Expr *BaseExpr = IV->getBase();
6503
6504 // Rewrite the base, but without actually doing replaces.
6505 {
6506 DisableReplaceStmtScope S(*this);
6507 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
6508 IV->setBase(BaseExpr);
6509 }
6510
6511 ObjCIvarDecl *D = IV->getDecl();
6512
6513 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006514
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006515 if (BaseExpr->getType()->isObjCObjectPointerType()) {
6516 const ObjCInterfaceType *iFaceDecl =
6517 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
6518 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
6519 // lookup which class implements the instance variable.
6520 ObjCInterfaceDecl *clsDeclared = 0;
6521 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
6522 clsDeclared);
6523 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
6524
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006525 // Build name of symbol holding ivar offset.
6526 std::string IvarOffsetName = "OBJC_IVAR_$_";
6527 IvarOffsetName += clsDeclared->getIdentifier()->getName();
6528 IvarOffsetName += "_";
6529 IvarOffsetName += D->getName();
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00006530 ReferencedIvars[clsDeclared].insert(D);
6531
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006532 // cast offset to "char *".
6533 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
6534 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006535 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006536 BaseExpr);
6537 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
6538 SourceLocation(), &Context->Idents.get(IvarOffsetName),
6539 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00006540 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
6541 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006542 SourceLocation());
6543 BinaryOperator *addExpr =
6544 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
6545 Context->getPointerType(Context->CharTy),
6546 VK_RValue, OK_Ordinary, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006547 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006548 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
6549 SourceLocation(),
6550 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006551 QualType IvarT = D->getType();
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006552 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00006553 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006554
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006555 castExpr = NoTypeInfoCStyleCastExpr(Context,
6556 castT,
6557 CK_BitCast,
6558 PE);
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00006559 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006560 VK_LValue, OK_Ordinary,
6561 SourceLocation());
6562 PE = new (Context) ParenExpr(OldRange.getBegin(),
6563 OldRange.getEnd(),
6564 Exp);
6565
6566 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006567 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006568
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00006569 ReplaceStmtWithRange(IV, Replacement, OldRange);
6570 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006571}