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