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