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