blob: bb98aab61156583e8a360ae8e8036dcfa188c3a6 [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
Ted Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000019#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000020#include "clang/Basic/IdentifierTable.h"
21#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000022#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000023#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000024#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000025#include "llvm/ADT/DenseSet.h"
26#include "llvm/ADT/OwningPtr.h"
27#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000031
32using namespace clang;
33using llvm::utostr;
34
35namespace {
36 class RewriteModernObjC : public ASTConsumer {
37 protected:
38
39 enum {
40 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
41 block, ... */
42 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
43 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
44 __block variable */
45 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
46 helpers */
47 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
48 support routines */
49 BLOCK_BYREF_CURRENT_MAX = 256
50 };
51
52 enum {
53 BLOCK_NEEDS_FREE = (1 << 24),
54 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
55 BLOCK_HAS_CXX_OBJ = (1 << 26),
56 BLOCK_IS_GC = (1 << 27),
57 BLOCK_IS_GLOBAL = (1 << 28),
58 BLOCK_HAS_DESCRIPTOR = (1 << 29)
59 };
60 static const int OBJC_ABI_VERSION = 7;
61
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
105 FunctionDecl *SuperContructorFunctionDecl;
106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000121
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
John McCallf4b88a42012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000135
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000136
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
156
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000157 // This maps an original source AST to it's rewritten form. This allows
158 // us to avoid rewriting the same node twice (which is very uncommon).
159 // This is needed to support some of the exotic property rewriting.
160 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
161
162 // Needed for header files being rewritten
163 bool IsHeader;
164 bool SilenceRewriteMacroWarning;
165 bool objc_impl_method;
166
167 bool DisableReplaceStmt;
168 class DisableReplaceStmtScope {
169 RewriteModernObjC &R;
170 bool SavedValue;
171
172 public:
173 DisableReplaceStmtScope(RewriteModernObjC &R)
174 : R(R), SavedValue(R.DisableReplaceStmt) {
175 R.DisableReplaceStmt = true;
176 }
177 ~DisableReplaceStmtScope() {
178 R.DisableReplaceStmt = SavedValue;
179 }
180 };
181 void InitializeCommon(ASTContext &context);
182
183 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000184 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000185 // Top Level Driver code.
186 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
187 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
188 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
189 if (!Class->isThisDeclarationADefinition()) {
190 RewriteForwardClassDecl(D);
191 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000192 } else {
193 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000194 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000195 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000196 }
197 }
198
199 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
200 if (!Proto->isThisDeclarationADefinition()) {
201 RewriteForwardProtocolDecl(D);
202 break;
203 }
204 }
205
206 HandleTopLevelSingleDecl(*I);
207 }
208 return true;
209 }
210 void HandleTopLevelSingleDecl(Decl *D);
211 void HandleDeclInMainFile(Decl *D);
212 RewriteModernObjC(std::string inFile, raw_ostream *OS,
213 DiagnosticsEngine &D, const LangOptions &LOpts,
214 bool silenceMacroWarn);
215
216 ~RewriteModernObjC() {}
217
218 virtual void HandleTranslationUnit(ASTContext &C);
219
220 void ReplaceStmt(Stmt *Old, Stmt *New) {
221 Stmt *ReplacingStmt = ReplacedNodes[Old];
222
223 if (ReplacingStmt)
224 return; // We can't rewrite the same node twice.
225
226 if (DisableReplaceStmt)
227 return;
228
229 // If replacement succeeded or warning disabled return with no warning.
230 if (!Rewrite.ReplaceStmt(Old, New)) {
231 ReplacedNodes[Old] = New;
232 return;
233 }
234 if (SilenceRewriteMacroWarning)
235 return;
236 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
237 << Old->getSourceRange();
238 }
239
240 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
241 if (DisableReplaceStmt)
242 return;
243
244 // Measure the old text.
245 int Size = Rewrite.getRangeSize(SrcRange);
246 if (Size == -1) {
247 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
248 << Old->getSourceRange();
249 return;
250 }
251 // Get the new text.
252 std::string SStr;
253 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000254 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000255 const std::string &Str = S.str();
256
257 // If replacement succeeded or warning disabled return with no warning.
258 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
259 ReplacedNodes[Old] = New;
260 return;
261 }
262 if (SilenceRewriteMacroWarning)
263 return;
264 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
265 << Old->getSourceRange();
266 }
267
268 void InsertText(SourceLocation Loc, StringRef Str,
269 bool InsertAfter = true) {
270 // If insertion succeeded or warning disabled return with no warning.
271 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
272 SilenceRewriteMacroWarning)
273 return;
274
275 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
276 }
277
278 void ReplaceText(SourceLocation Start, unsigned OrigLength,
279 StringRef Str) {
280 // If removal succeeded or warning disabled return with no warning.
281 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
282 SilenceRewriteMacroWarning)
283 return;
284
285 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
286 }
287
288 // Syntactic Rewriting.
289 void RewriteRecordBody(RecordDecl *RD);
290 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000291 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000292 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
293 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000294 void RewriteForwardClassDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000295 void RewriteForwardClassDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000296 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
297 const std::string &typedefString);
298 void RewriteImplementations();
299 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
300 ObjCImplementationDecl *IMD,
301 ObjCCategoryImplDecl *CID);
302 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
303 void RewriteImplementationDecl(Decl *Dcl);
304 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
305 ObjCMethodDecl *MDecl, std::string &ResultStr);
306 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
307 const FunctionType *&FPRetType);
308 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
309 ValueDecl *VD, bool def=false);
310 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
311 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
312 void RewriteForwardProtocolDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000313 void RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000314 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
315 void RewriteProperty(ObjCPropertyDecl *prop);
316 void RewriteFunctionDecl(FunctionDecl *FD);
317 void RewriteBlockPointerType(std::string& Str, QualType Type);
318 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000319 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000320 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
321 void RewriteTypeOfDecl(VarDecl *VD);
322 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000323
324 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000325
326 // Expression Rewriting.
327 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
328 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
329 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
330 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
331 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
332 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
333 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000334 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000335 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000336 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000337 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000338 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000339 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000340 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000341 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
342 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
343 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
344 SourceLocation OrigEnd);
345 Stmt *RewriteBreakStmt(BreakStmt *S);
346 Stmt *RewriteContinueStmt(ContinueStmt *S);
347 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000348 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000349 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000350
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000351 // Computes ivar bitfield group no.
352 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
353 // Names field decl. for ivar bitfield group.
354 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
355 // Names struct type for ivar bitfield group.
356 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
357 // Names symbol for ivar bitfield group field offset.
358 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
359 // Given an ivar bitfield, it builds (or finds) its group record type.
360 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
361 QualType SynthesizeBitfieldGroupStructType(
362 ObjCIvarDecl *IV,
363 SmallVectorImpl<ObjCIvarDecl *> &IVars);
364
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000365 // Block rewriting.
366 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
367
368 // Block specific rewrite rules.
369 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000370 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000371 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000372 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
373 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
374
375 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
376 std::string &Result);
377
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000378 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000379 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000380 bool &IsNamedDefinition);
381 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
382 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000383
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000384 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
385
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000386 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
387 std::string &Result);
388
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000389 virtual void Initialize(ASTContext &context);
390
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000391 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000392 // rewriting routines on the new ASTs.
393 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
394 Expr **args, unsigned nargs,
395 SourceLocation StartLoc=SourceLocation(),
396 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000397
398 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
399 QualType msgSendType,
400 QualType returnType,
401 SmallVectorImpl<QualType> &ArgTypes,
402 SmallVectorImpl<Expr*> &MsgExprs,
403 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000404
405 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
406 SourceLocation StartLoc=SourceLocation(),
407 SourceLocation EndLoc=SourceLocation());
408
409 void SynthCountByEnumWithState(std::string &buf);
410 void SynthMsgSendFunctionDecl();
411 void SynthMsgSendSuperFunctionDecl();
412 void SynthMsgSendStretFunctionDecl();
413 void SynthMsgSendFpretFunctionDecl();
414 void SynthMsgSendSuperStretFunctionDecl();
415 void SynthGetClassFunctionDecl();
416 void SynthGetMetaClassFunctionDecl();
417 void SynthGetSuperClassFunctionDecl();
418 void SynthSelGetUidFunctionDecl();
419 void SynthSuperContructorFunctionDecl();
420
421 // Rewriting metadata
422 template<typename MethodIterator>
423 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
424 MethodIterator MethodEnd,
425 bool IsInstanceMethod,
426 StringRef prefix,
427 StringRef ClassName,
428 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000429 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
430 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000431 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000432 const ObjCList<ObjCProtocolDecl> &Prots,
433 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000434 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000435 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000436 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000437
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000438 void RewriteMetaDataIntoBuffer(std::string &Result);
439 void WriteImageInfo(std::string &Result);
440 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000441 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000442 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000443
444 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000445 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000446 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000447 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000448
449
450 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
451 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
452 StringRef funcName, std::string Tag);
453 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
454 StringRef funcName, std::string Tag);
455 std::string SynthesizeBlockImpl(BlockExpr *CE,
456 std::string Tag, std::string Desc);
457 std::string SynthesizeBlockDescriptor(std::string DescTag,
458 std::string ImplTag,
459 int i, StringRef funcName,
460 unsigned hasCopy);
461 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
462 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
463 StringRef FunName);
464 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
465 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000466 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000467
468 // Misc. helper routines.
469 QualType getProtocolType();
470 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000471 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
472 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
473 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
474
475 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
476 void CollectBlockDeclRefInfo(BlockExpr *Exp);
477 void GetBlockDeclRefExprs(Stmt *S);
478 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000479 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
481
482 // We avoid calling Type::isBlockPointerType(), since it operates on the
483 // canonical type. We only care if the top-level type is a closure pointer.
484 bool isTopLevelBlockPointerType(QualType T) {
485 return isa<BlockPointerType>(T);
486 }
487
488 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
489 /// to a function pointer type and upon success, returns true; false
490 /// otherwise.
491 bool convertBlockPointerToFunctionPointer(QualType &T) {
492 if (isTopLevelBlockPointerType(T)) {
493 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
494 T = Context->getPointerType(BPT->getPointeeType());
495 return true;
496 }
497 return false;
498 }
499
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000500 bool convertObjCTypeToCStyleType(QualType &T);
501
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000502 bool needToScanForQualifiers(QualType T);
503 QualType getSuperStructType();
504 QualType getConstantStringStructType();
505 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
506 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
507
508 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000509 if (T->isObjCQualifiedIdType()) {
510 bool isConst = T.isConstQualified();
511 T = isConst ? Context->getObjCIdType().withConst()
512 : Context->getObjCIdType();
513 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000514 else if (T->isObjCQualifiedClassType())
515 T = Context->getObjCClassType();
516 else if (T->isObjCObjectPointerType() &&
517 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
518 if (const ObjCObjectPointerType * OBJPT =
519 T->getAsObjCInterfacePointerType()) {
520 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
521 T = QualType(IFaceT, 0);
522 T = Context->getPointerType(T);
523 }
524 }
525 }
526
527 // FIXME: This predicate seems like it would be useful to add to ASTContext.
528 bool isObjCType(QualType T) {
529 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
530 return false;
531
532 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
533
534 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
535 OCT == Context->getCanonicalType(Context->getObjCClassType()))
536 return true;
537
538 if (const PointerType *PT = OCT->getAs<PointerType>()) {
539 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
540 PT->getPointeeType()->isObjCQualifiedIdType())
541 return true;
542 }
543 return false;
544 }
545 bool PointerTypeTakesAnyBlockArguments(QualType QT);
546 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
547 void GetExtentOfArgList(const char *Name, const char *&LParen,
548 const char *&RParen);
549
550 void QuoteDoublequotes(std::string &From, std::string &To) {
551 for (unsigned i = 0; i < From.length(); i++) {
552 if (From[i] == '"')
553 To += "\\\"";
554 else
555 To += From[i];
556 }
557 }
558
559 QualType getSimpleFunctionType(QualType result,
560 const QualType *args,
561 unsigned numArgs,
562 bool variadic = false) {
563 if (result == Context->getObjCInstanceType())
564 result = Context->getObjCIdType();
565 FunctionProtoType::ExtProtoInfo fpi;
566 fpi.Variadic = variadic;
567 return Context->getFunctionType(result, args, numArgs, fpi);
568 }
569
570 // Helper function: create a CStyleCastExpr with trivial type source info.
571 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
572 CastKind Kind, Expr *E) {
573 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
574 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
575 SourceLocation(), SourceLocation());
576 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000577
578 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
579 IdentifierInfo* II = &Context->Idents.get("load");
580 Selector LoadSel = Context->Selectors.getSelector(0, &II);
581 return OD->getClassMethod(LoadSel) != 0;
582 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000583 };
584
585}
586
587void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
588 NamedDecl *D) {
589 if (const FunctionProtoType *fproto
590 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
591 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
592 E = fproto->arg_type_end(); I && (I != E); ++I)
593 if (isTopLevelBlockPointerType(*I)) {
594 // All the args are checked/rewritten. Don't call twice!
595 RewriteBlockPointerDecl(D);
596 break;
597 }
598 }
599}
600
601void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
602 const PointerType *PT = funcType->getAs<PointerType>();
603 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
604 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
605}
606
607static bool IsHeaderFile(const std::string &Filename) {
608 std::string::size_type DotPos = Filename.rfind('.');
609
610 if (DotPos == std::string::npos) {
611 // no file extension
612 return false;
613 }
614
615 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
616 // C header: .h
617 // C++ header: .hh or .H;
618 return Ext == "h" || Ext == "hh" || Ext == "H";
619}
620
621RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
622 DiagnosticsEngine &D, const LangOptions &LOpts,
623 bool silenceMacroWarn)
624 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
625 SilenceRewriteMacroWarning(silenceMacroWarn) {
626 IsHeader = IsHeaderFile(inFile);
627 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
628 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000629 // FIXME. This should be an error. But if block is not called, it is OK. And it
630 // may break including some headers.
631 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
632 "rewriting block literal declared in global scope is not implemented");
633
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000634 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
635 DiagnosticsEngine::Warning,
636 "rewriter doesn't support user-specified control flow semantics "
637 "for @try/@finally (code may not execute properly)");
638}
639
640ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
641 raw_ostream* OS,
642 DiagnosticsEngine &Diags,
643 const LangOptions &LOpts,
644 bool SilenceRewriteMacroWarning) {
645 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
646}
647
648void RewriteModernObjC::InitializeCommon(ASTContext &context) {
649 Context = &context;
650 SM = &Context->getSourceManager();
651 TUDecl = Context->getTranslationUnitDecl();
652 MsgSendFunctionDecl = 0;
653 MsgSendSuperFunctionDecl = 0;
654 MsgSendStretFunctionDecl = 0;
655 MsgSendSuperStretFunctionDecl = 0;
656 MsgSendFpretFunctionDecl = 0;
657 GetClassFunctionDecl = 0;
658 GetMetaClassFunctionDecl = 0;
659 GetSuperClassFunctionDecl = 0;
660 SelGetUidFunctionDecl = 0;
661 CFStringFunctionDecl = 0;
662 ConstantStringClassReference = 0;
663 NSStringRecord = 0;
664 CurMethodDef = 0;
665 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000666 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000667 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000668 SuperStructDecl = 0;
669 ProtocolTypeDecl = 0;
670 ConstantStringDecl = 0;
671 BcLabelCount = 0;
672 SuperContructorFunctionDecl = 0;
673 NumObjCStringLiterals = 0;
674 PropParentMap = 0;
675 CurrentBody = 0;
676 DisableReplaceStmt = false;
677 objc_impl_method = false;
678
679 // Get the ID and start/end of the main file.
680 MainFileID = SM->getMainFileID();
681 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
682 MainFileStart = MainBuf->getBufferStart();
683 MainFileEnd = MainBuf->getBufferEnd();
684
David Blaikie4e4d0842012-03-11 07:00:24 +0000685 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000686}
687
688//===----------------------------------------------------------------------===//
689// Top Level Driver Code
690//===----------------------------------------------------------------------===//
691
692void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
693 if (Diags.hasErrorOccurred())
694 return;
695
696 // Two cases: either the decl could be in the main file, or it could be in a
697 // #included file. If the former, rewrite it now. If the later, check to see
698 // if we rewrote the #include/#import.
699 SourceLocation Loc = D->getLocation();
700 Loc = SM->getExpansionLoc(Loc);
701
702 // If this is for a builtin, ignore it.
703 if (Loc.isInvalid()) return;
704
705 // Look for built-in declarations that we need to refer during the rewrite.
706 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
707 RewriteFunctionDecl(FD);
708 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
709 // declared in <Foundation/NSString.h>
710 if (FVD->getName() == "_NSConstantStringClassReference") {
711 ConstantStringClassReference = FVD;
712 return;
713 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000714 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
715 RewriteCategoryDecl(CD);
716 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
717 if (PD->isThisDeclarationADefinition())
718 RewriteProtocolDecl(PD);
719 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000720 // FIXME. This will not work in all situations and leaving it out
721 // is harmless.
722 // RewriteLinkageSpec(LSD);
723
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000724 // Recurse into linkage specifications
725 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
726 DIEnd = LSD->decls_end();
727 DI != DIEnd; ) {
728 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
729 if (!IFace->isThisDeclarationADefinition()) {
730 SmallVector<Decl *, 8> DG;
731 SourceLocation StartLoc = IFace->getLocStart();
732 do {
733 if (isa<ObjCInterfaceDecl>(*DI) &&
734 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
735 StartLoc == (*DI)->getLocStart())
736 DG.push_back(*DI);
737 else
738 break;
739
740 ++DI;
741 } while (DI != DIEnd);
742 RewriteForwardClassDecl(DG);
743 continue;
744 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000745 else {
746 // Keep track of all interface declarations seen.
747 ObjCInterfacesSeen.push_back(IFace);
748 ++DI;
749 continue;
750 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000751 }
752
753 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
754 if (!Proto->isThisDeclarationADefinition()) {
755 SmallVector<Decl *, 8> DG;
756 SourceLocation StartLoc = Proto->getLocStart();
757 do {
758 if (isa<ObjCProtocolDecl>(*DI) &&
759 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
760 StartLoc == (*DI)->getLocStart())
761 DG.push_back(*DI);
762 else
763 break;
764
765 ++DI;
766 } while (DI != DIEnd);
767 RewriteForwardProtocolDecl(DG);
768 continue;
769 }
770 }
771
772 HandleTopLevelSingleDecl(*DI);
773 ++DI;
774 }
775 }
776 // If we have a decl in the main file, see if we should rewrite it.
777 if (SM->isFromMainFile(Loc))
778 return HandleDeclInMainFile(D);
779}
780
781//===----------------------------------------------------------------------===//
782// Syntactic (non-AST) Rewriting Code
783//===----------------------------------------------------------------------===//
784
785void RewriteModernObjC::RewriteInclude() {
786 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
787 StringRef MainBuf = SM->getBufferData(MainFileID);
788 const char *MainBufStart = MainBuf.begin();
789 const char *MainBufEnd = MainBuf.end();
790 size_t ImportLen = strlen("import");
791
792 // Loop over the whole file, looking for includes.
793 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
794 if (*BufPtr == '#') {
795 if (++BufPtr == MainBufEnd)
796 return;
797 while (*BufPtr == ' ' || *BufPtr == '\t')
798 if (++BufPtr == MainBufEnd)
799 return;
800 if (!strncmp(BufPtr, "import", ImportLen)) {
801 // replace import with include
802 SourceLocation ImportLoc =
803 LocStart.getLocWithOffset(BufPtr-MainBufStart);
804 ReplaceText(ImportLoc, ImportLen, "include");
805 BufPtr += ImportLen;
806 }
807 }
808 }
809}
810
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000811static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
812 ObjCIvarDecl *IvarDecl, std::string &Result) {
813 Result += "OBJC_IVAR_$_";
814 Result += IDecl->getName();
815 Result += "$";
816 Result += IvarDecl->getName();
817}
818
819std::string
820RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
821 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
822
823 // Build name of symbol holding ivar offset.
824 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000825 if (D->isBitField())
826 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
827 else
828 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000829
830
831 std::string S = "(*(";
832 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000833 if (D->isBitField())
834 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000835
836 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
837 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
838 RD = RD->getDefinition();
839 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
840 // decltype(((Foo_IMPL*)0)->bar) *
841 ObjCContainerDecl *CDecl =
842 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
843 // ivar in class extensions requires special treatment.
844 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
845 CDecl = CatDecl->getClassInterface();
846 std::string RecName = CDecl->getName();
847 RecName += "_IMPL";
848 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
849 SourceLocation(), SourceLocation(),
850 &Context->Idents.get(RecName.c_str()));
851 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
852 unsigned UnsignedIntSize =
853 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
854 Expr *Zero = IntegerLiteral::Create(*Context,
855 llvm::APInt(UnsignedIntSize, 0),
856 Context->UnsignedIntTy, SourceLocation());
857 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
858 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
859 Zero);
860 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
861 SourceLocation(),
862 &Context->Idents.get(D->getNameAsString()),
863 IvarT, 0,
864 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000865 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000866 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
867 FD->getType(), VK_LValue,
868 OK_Ordinary);
869 IvarT = Context->getDecltypeType(ME, ME->getType());
870 }
871 }
872 convertObjCTypeToCStyleType(IvarT);
873 QualType castT = Context->getPointerType(IvarT);
874 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
875 S += TypeString;
876 S += ")";
877
878 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
879 S += "((char *)self + ";
880 S += IvarOffsetName;
881 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000882 if (D->isBitField()) {
883 S += ".";
884 S += D->getNameAsString();
885 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000886 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000887 return S;
888}
889
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000890/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
891/// been found in the class implementation. In this case, it must be synthesized.
892static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
893 ObjCPropertyDecl *PD,
894 bool getter) {
895 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
896 : !IMP->getInstanceMethod(PD->getSetterName());
897
898}
899
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000900void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
901 ObjCImplementationDecl *IMD,
902 ObjCCategoryImplDecl *CID) {
903 static bool objcGetPropertyDefined = false;
904 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000905 SourceLocation startGetterSetterLoc;
906
907 if (PID->getLocStart().isValid()) {
908 SourceLocation startLoc = PID->getLocStart();
909 InsertText(startLoc, "// ");
910 const char *startBuf = SM->getCharacterData(startLoc);
911 assert((*startBuf == '@') && "bogus @synthesize location");
912 const char *semiBuf = strchr(startBuf, ';');
913 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
914 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
915 }
916 else
917 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000918
919 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
920 return; // FIXME: is this correct?
921
922 // Generate the 'getter' function.
923 ObjCPropertyDecl *PD = PID->getPropertyDecl();
924 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
925
926 if (!OID)
927 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000928 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000929 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000930 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
931 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000932 ObjCPropertyDecl::OBJC_PR_copy));
933 std::string Getr;
934 if (GenGetProperty && !objcGetPropertyDefined) {
935 objcGetPropertyDefined = true;
936 // FIXME. Is this attribute correct in all cases?
937 Getr = "\nextern \"C\" __declspec(dllimport) "
938 "id objc_getProperty(id, SEL, long, bool);\n";
939 }
940 RewriteObjCMethodDecl(OID->getContainingInterface(),
941 PD->getGetterMethodDecl(), Getr);
942 Getr += "{ ";
943 // Synthesize an explicit cast to gain access to the ivar.
944 // See objc-act.c:objc_synthesize_new_getter() for details.
945 if (GenGetProperty) {
946 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
947 Getr += "typedef ";
948 const FunctionType *FPRetType = 0;
949 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
950 FPRetType);
951 Getr += " _TYPE";
952 if (FPRetType) {
953 Getr += ")"; // close the precedence "scope" for "*".
954
955 // Now, emit the argument types (if any).
956 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
957 Getr += "(";
958 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
959 if (i) Getr += ", ";
960 std::string ParamStr = FT->getArgType(i).getAsString(
961 Context->getPrintingPolicy());
962 Getr += ParamStr;
963 }
964 if (FT->isVariadic()) {
965 if (FT->getNumArgs()) Getr += ", ";
966 Getr += "...";
967 }
968 Getr += ")";
969 } else
970 Getr += "()";
971 }
972 Getr += ";\n";
973 Getr += "return (_TYPE)";
974 Getr += "objc_getProperty(self, _cmd, ";
975 RewriteIvarOffsetComputation(OID, Getr);
976 Getr += ", 1)";
977 }
978 else
979 Getr += "return " + getIvarAccessString(OID);
980 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000981 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000982 }
983
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000984 if (PD->isReadOnly() ||
985 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000986 return;
987
988 // Generate the 'setter' function.
989 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000990 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000991 ObjCPropertyDecl::OBJC_PR_copy);
992 if (GenSetProperty && !objcSetPropertyDefined) {
993 objcSetPropertyDefined = true;
994 // FIXME. Is this attribute correct in all cases?
995 Setr = "\nextern \"C\" __declspec(dllimport) "
996 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
997 }
998
999 RewriteObjCMethodDecl(OID->getContainingInterface(),
1000 PD->getSetterMethodDecl(), Setr);
1001 Setr += "{ ";
1002 // Synthesize an explicit cast to initialize the ivar.
1003 // See objc-act.c:objc_synthesize_new_setter() for details.
1004 if (GenSetProperty) {
1005 Setr += "objc_setProperty (self, _cmd, ";
1006 RewriteIvarOffsetComputation(OID, Setr);
1007 Setr += ", (id)";
1008 Setr += PD->getName();
1009 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001010 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001011 Setr += "0, ";
1012 else
1013 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001014 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001015 Setr += "1)";
1016 else
1017 Setr += "0)";
1018 }
1019 else {
1020 Setr += getIvarAccessString(OID) + " = ";
1021 Setr += PD->getName();
1022 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001023 Setr += "; }\n";
1024 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001025}
1026
1027static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1028 std::string &typedefString) {
1029 typedefString += "#ifndef _REWRITER_typedef_";
1030 typedefString += ForwardDecl->getNameAsString();
1031 typedefString += "\n";
1032 typedefString += "#define _REWRITER_typedef_";
1033 typedefString += ForwardDecl->getNameAsString();
1034 typedefString += "\n";
1035 typedefString += "typedef struct objc_object ";
1036 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001037 // typedef struct { } _objc_exc_Classname;
1038 typedefString += ";\ntypedef struct {} _objc_exc_";
1039 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001040 typedefString += ";\n#endif\n";
1041}
1042
1043void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1044 const std::string &typedefString) {
1045 SourceLocation startLoc = ClassDecl->getLocStart();
1046 const char *startBuf = SM->getCharacterData(startLoc);
1047 const char *semiPtr = strchr(startBuf, ';');
1048 // Replace the @class with typedefs corresponding to the classes.
1049 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1050}
1051
1052void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1053 std::string typedefString;
1054 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1055 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1056 if (I == D.begin()) {
1057 // Translate to typedef's that forward reference structs with the same name
1058 // as the class. As a convenience, we include the original declaration
1059 // as a comment.
1060 typedefString += "// @class ";
1061 typedefString += ForwardDecl->getNameAsString();
1062 typedefString += ";\n";
1063 }
1064 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1065 }
1066 DeclGroupRef::iterator I = D.begin();
1067 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1068}
1069
1070void RewriteModernObjC::RewriteForwardClassDecl(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001071 const SmallVector<Decl *, 8> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001072 std::string typedefString;
1073 for (unsigned i = 0; i < D.size(); i++) {
1074 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1075 if (i == 0) {
1076 typedefString += "// @class ";
1077 typedefString += ForwardDecl->getNameAsString();
1078 typedefString += ";\n";
1079 }
1080 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1081 }
1082 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1083}
1084
1085void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1086 // When method is a synthesized one, such as a getter/setter there is
1087 // nothing to rewrite.
1088 if (Method->isImplicit())
1089 return;
1090 SourceLocation LocStart = Method->getLocStart();
1091 SourceLocation LocEnd = Method->getLocEnd();
1092
1093 if (SM->getExpansionLineNumber(LocEnd) >
1094 SM->getExpansionLineNumber(LocStart)) {
1095 InsertText(LocStart, "#if 0\n");
1096 ReplaceText(LocEnd, 1, ";\n#endif\n");
1097 } else {
1098 InsertText(LocStart, "// ");
1099 }
1100}
1101
1102void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1103 SourceLocation Loc = prop->getAtLoc();
1104
1105 ReplaceText(Loc, 0, "// ");
1106 // FIXME: handle properties that are declared across multiple lines.
1107}
1108
1109void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1110 SourceLocation LocStart = CatDecl->getLocStart();
1111
1112 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001113 if (CatDecl->getIvarRBraceLoc().isValid()) {
1114 ReplaceText(LocStart, 1, "/** ");
1115 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1116 }
1117 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001118 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001119 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001120
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001121 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1122 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001123 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001124
1125 for (ObjCCategoryDecl::instmeth_iterator
1126 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1127 I != E; ++I)
1128 RewriteMethodDeclaration(*I);
1129 for (ObjCCategoryDecl::classmeth_iterator
1130 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1131 I != E; ++I)
1132 RewriteMethodDeclaration(*I);
1133
1134 // Lastly, comment out the @end.
1135 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1136 strlen("@end"), "/* @end */");
1137}
1138
1139void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1140 SourceLocation LocStart = PDecl->getLocStart();
1141 assert(PDecl->isThisDeclarationADefinition());
1142
1143 // FIXME: handle protocol headers that are declared across multiple lines.
1144 ReplaceText(LocStart, 0, "// ");
1145
1146 for (ObjCProtocolDecl::instmeth_iterator
1147 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1148 I != E; ++I)
1149 RewriteMethodDeclaration(*I);
1150 for (ObjCProtocolDecl::classmeth_iterator
1151 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1152 I != E; ++I)
1153 RewriteMethodDeclaration(*I);
1154
1155 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1156 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001157 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001158
1159 // Lastly, comment out the @end.
1160 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1161 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1162
1163 // Must comment out @optional/@required
1164 const char *startBuf = SM->getCharacterData(LocStart);
1165 const char *endBuf = SM->getCharacterData(LocEnd);
1166 for (const char *p = startBuf; p < endBuf; p++) {
1167 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1168 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1169 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1170
1171 }
1172 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1173 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1174 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1175
1176 }
1177 }
1178}
1179
1180void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1181 SourceLocation LocStart = (*D.begin())->getLocStart();
1182 if (LocStart.isInvalid())
1183 llvm_unreachable("Invalid SourceLocation");
1184 // FIXME: handle forward protocol that are declared across multiple lines.
1185 ReplaceText(LocStart, 0, "// ");
1186}
1187
1188void
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001189RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001190 SourceLocation LocStart = DG[0]->getLocStart();
1191 if (LocStart.isInvalid())
1192 llvm_unreachable("Invalid SourceLocation");
1193 // FIXME: handle forward protocol that are declared across multiple lines.
1194 ReplaceText(LocStart, 0, "// ");
1195}
1196
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001197void
1198RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1199 SourceLocation LocStart = LSD->getExternLoc();
1200 if (LocStart.isInvalid())
1201 llvm_unreachable("Invalid extern SourceLocation");
1202
1203 ReplaceText(LocStart, 0, "// ");
1204 if (!LSD->hasBraces())
1205 return;
1206 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1207 SourceLocation LocRBrace = LSD->getRBraceLoc();
1208 if (LocRBrace.isInvalid())
1209 llvm_unreachable("Invalid rbrace SourceLocation");
1210 ReplaceText(LocRBrace, 0, "// ");
1211}
1212
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001213void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1214 const FunctionType *&FPRetType) {
1215 if (T->isObjCQualifiedIdType())
1216 ResultStr += "id";
1217 else if (T->isFunctionPointerType() ||
1218 T->isBlockPointerType()) {
1219 // needs special handling, since pointer-to-functions have special
1220 // syntax (where a decaration models use).
1221 QualType retType = T;
1222 QualType PointeeTy;
1223 if (const PointerType* PT = retType->getAs<PointerType>())
1224 PointeeTy = PT->getPointeeType();
1225 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1226 PointeeTy = BPT->getPointeeType();
1227 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1228 ResultStr += FPRetType->getResultType().getAsString(
1229 Context->getPrintingPolicy());
1230 ResultStr += "(*";
1231 }
1232 } else
1233 ResultStr += T.getAsString(Context->getPrintingPolicy());
1234}
1235
1236void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1237 ObjCMethodDecl *OMD,
1238 std::string &ResultStr) {
1239 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1240 const FunctionType *FPRetType = 0;
1241 ResultStr += "\nstatic ";
1242 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1243 ResultStr += " ";
1244
1245 // Unique method name
1246 std::string NameStr;
1247
1248 if (OMD->isInstanceMethod())
1249 NameStr += "_I_";
1250 else
1251 NameStr += "_C_";
1252
1253 NameStr += IDecl->getNameAsString();
1254 NameStr += "_";
1255
1256 if (ObjCCategoryImplDecl *CID =
1257 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1258 NameStr += CID->getNameAsString();
1259 NameStr += "_";
1260 }
1261 // Append selector names, replacing ':' with '_'
1262 {
1263 std::string selString = OMD->getSelector().getAsString();
1264 int len = selString.size();
1265 for (int i = 0; i < len; i++)
1266 if (selString[i] == ':')
1267 selString[i] = '_';
1268 NameStr += selString;
1269 }
1270 // Remember this name for metadata emission
1271 MethodInternalNames[OMD] = NameStr;
1272 ResultStr += NameStr;
1273
1274 // Rewrite arguments
1275 ResultStr += "(";
1276
1277 // invisible arguments
1278 if (OMD->isInstanceMethod()) {
1279 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1280 selfTy = Context->getPointerType(selfTy);
1281 if (!LangOpts.MicrosoftExt) {
1282 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1283 ResultStr += "struct ";
1284 }
1285 // When rewriting for Microsoft, explicitly omit the structure name.
1286 ResultStr += IDecl->getNameAsString();
1287 ResultStr += " *";
1288 }
1289 else
1290 ResultStr += Context->getObjCClassType().getAsString(
1291 Context->getPrintingPolicy());
1292
1293 ResultStr += " self, ";
1294 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1295 ResultStr += " _cmd";
1296
1297 // Method arguments.
1298 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1299 E = OMD->param_end(); PI != E; ++PI) {
1300 ParmVarDecl *PDecl = *PI;
1301 ResultStr += ", ";
1302 if (PDecl->getType()->isObjCQualifiedIdType()) {
1303 ResultStr += "id ";
1304 ResultStr += PDecl->getNameAsString();
1305 } else {
1306 std::string Name = PDecl->getNameAsString();
1307 QualType QT = PDecl->getType();
1308 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001309 (void)convertBlockPointerToFunctionPointer(QT);
1310 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001311 ResultStr += Name;
1312 }
1313 }
1314 if (OMD->isVariadic())
1315 ResultStr += ", ...";
1316 ResultStr += ") ";
1317
1318 if (FPRetType) {
1319 ResultStr += ")"; // close the precedence "scope" for "*".
1320
1321 // Now, emit the argument types (if any).
1322 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1323 ResultStr += "(";
1324 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1325 if (i) ResultStr += ", ";
1326 std::string ParamStr = FT->getArgType(i).getAsString(
1327 Context->getPrintingPolicy());
1328 ResultStr += ParamStr;
1329 }
1330 if (FT->isVariadic()) {
1331 if (FT->getNumArgs()) ResultStr += ", ";
1332 ResultStr += "...";
1333 }
1334 ResultStr += ")";
1335 } else {
1336 ResultStr += "()";
1337 }
1338 }
1339}
1340void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1341 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1342 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1343
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001344 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001345 if (IMD->getIvarRBraceLoc().isValid()) {
1346 ReplaceText(IMD->getLocStart(), 1, "/** ");
1347 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001348 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001349 else {
1350 InsertText(IMD->getLocStart(), "// ");
1351 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001352 }
1353 else
1354 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001355
1356 for (ObjCCategoryImplDecl::instmeth_iterator
1357 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1358 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1359 I != E; ++I) {
1360 std::string ResultStr;
1361 ObjCMethodDecl *OMD = *I;
1362 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1363 SourceLocation LocStart = OMD->getLocStart();
1364 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1365
1366 const char *startBuf = SM->getCharacterData(LocStart);
1367 const char *endBuf = SM->getCharacterData(LocEnd);
1368 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1369 }
1370
1371 for (ObjCCategoryImplDecl::classmeth_iterator
1372 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1373 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1374 I != E; ++I) {
1375 std::string ResultStr;
1376 ObjCMethodDecl *OMD = *I;
1377 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1378 SourceLocation LocStart = OMD->getLocStart();
1379 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1380
1381 const char *startBuf = SM->getCharacterData(LocStart);
1382 const char *endBuf = SM->getCharacterData(LocEnd);
1383 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1384 }
1385 for (ObjCCategoryImplDecl::propimpl_iterator
1386 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1387 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1388 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001389 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001390 }
1391
1392 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1393}
1394
1395void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001396 // Do not synthesize more than once.
1397 if (ObjCSynthesizedStructs.count(ClassDecl))
1398 return;
1399 // Make sure super class's are written before current class is written.
1400 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1401 while (SuperClass) {
1402 RewriteInterfaceDecl(SuperClass);
1403 SuperClass = SuperClass->getSuperClass();
1404 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001405 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001406 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001407 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001408 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001409 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1410
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001411 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001412 // Mark this typedef as having been written into its c++ equivalent.
1413 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001414
1415 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001416 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001417 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001418 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001419 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001420 I != E; ++I)
1421 RewriteMethodDeclaration(*I);
1422 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001423 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001424 I != E; ++I)
1425 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001426
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001427 // Lastly, comment out the @end.
1428 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1429 "/* @end */");
1430 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001431}
1432
1433Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1434 SourceRange OldRange = PseudoOp->getSourceRange();
1435
1436 // We just magically know some things about the structure of this
1437 // expression.
1438 ObjCMessageExpr *OldMsg =
1439 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1440 PseudoOp->getNumSemanticExprs() - 1));
1441
1442 // Because the rewriter doesn't allow us to rewrite rewritten code,
1443 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001444 Expr *Base;
1445 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001446 {
1447 DisableReplaceStmtScope S(*this);
1448
1449 // Rebuild the base expression if we have one.
1450 Base = 0;
1451 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1452 Base = OldMsg->getInstanceReceiver();
1453 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1454 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1455 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001456
1457 unsigned numArgs = OldMsg->getNumArgs();
1458 for (unsigned i = 0; i < numArgs; i++) {
1459 Expr *Arg = OldMsg->getArg(i);
1460 if (isa<OpaqueValueExpr>(Arg))
1461 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1462 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1463 Args.push_back(Arg);
1464 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001465 }
1466
1467 // TODO: avoid this copy.
1468 SmallVector<SourceLocation, 1> SelLocs;
1469 OldMsg->getSelectorLocs(SelLocs);
1470
1471 ObjCMessageExpr *NewMsg = 0;
1472 switch (OldMsg->getReceiverKind()) {
1473 case ObjCMessageExpr::Class:
1474 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1475 OldMsg->getValueKind(),
1476 OldMsg->getLeftLoc(),
1477 OldMsg->getClassReceiverTypeInfo(),
1478 OldMsg->getSelector(),
1479 SelLocs,
1480 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001481 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001482 OldMsg->getRightLoc(),
1483 OldMsg->isImplicit());
1484 break;
1485
1486 case ObjCMessageExpr::Instance:
1487 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1488 OldMsg->getValueKind(),
1489 OldMsg->getLeftLoc(),
1490 Base,
1491 OldMsg->getSelector(),
1492 SelLocs,
1493 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001494 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001495 OldMsg->getRightLoc(),
1496 OldMsg->isImplicit());
1497 break;
1498
1499 case ObjCMessageExpr::SuperClass:
1500 case ObjCMessageExpr::SuperInstance:
1501 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1502 OldMsg->getValueKind(),
1503 OldMsg->getLeftLoc(),
1504 OldMsg->getSuperLoc(),
1505 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1506 OldMsg->getSuperType(),
1507 OldMsg->getSelector(),
1508 SelLocs,
1509 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001510 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001511 OldMsg->getRightLoc(),
1512 OldMsg->isImplicit());
1513 break;
1514 }
1515
1516 Stmt *Replacement = SynthMessageExpr(NewMsg);
1517 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1518 return Replacement;
1519}
1520
1521Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1522 SourceRange OldRange = PseudoOp->getSourceRange();
1523
1524 // We just magically know some things about the structure of this
1525 // expression.
1526 ObjCMessageExpr *OldMsg =
1527 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1528
1529 // Because the rewriter doesn't allow us to rewrite rewritten code,
1530 // we need to suppress rewriting the sub-statements.
1531 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001532 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001533 {
1534 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001535 // Rebuild the base expression if we have one.
1536 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1537 Base = OldMsg->getInstanceReceiver();
1538 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1539 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1540 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001541 unsigned numArgs = OldMsg->getNumArgs();
1542 for (unsigned i = 0; i < numArgs; i++) {
1543 Expr *Arg = OldMsg->getArg(i);
1544 if (isa<OpaqueValueExpr>(Arg))
1545 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1546 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1547 Args.push_back(Arg);
1548 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001549 }
1550
1551 // Intentionally empty.
1552 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001553
1554 ObjCMessageExpr *NewMsg = 0;
1555 switch (OldMsg->getReceiverKind()) {
1556 case ObjCMessageExpr::Class:
1557 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1558 OldMsg->getValueKind(),
1559 OldMsg->getLeftLoc(),
1560 OldMsg->getClassReceiverTypeInfo(),
1561 OldMsg->getSelector(),
1562 SelLocs,
1563 OldMsg->getMethodDecl(),
1564 Args,
1565 OldMsg->getRightLoc(),
1566 OldMsg->isImplicit());
1567 break;
1568
1569 case ObjCMessageExpr::Instance:
1570 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1571 OldMsg->getValueKind(),
1572 OldMsg->getLeftLoc(),
1573 Base,
1574 OldMsg->getSelector(),
1575 SelLocs,
1576 OldMsg->getMethodDecl(),
1577 Args,
1578 OldMsg->getRightLoc(),
1579 OldMsg->isImplicit());
1580 break;
1581
1582 case ObjCMessageExpr::SuperClass:
1583 case ObjCMessageExpr::SuperInstance:
1584 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1585 OldMsg->getValueKind(),
1586 OldMsg->getLeftLoc(),
1587 OldMsg->getSuperLoc(),
1588 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1589 OldMsg->getSuperType(),
1590 OldMsg->getSelector(),
1591 SelLocs,
1592 OldMsg->getMethodDecl(),
1593 Args,
1594 OldMsg->getRightLoc(),
1595 OldMsg->isImplicit());
1596 break;
1597 }
1598
1599 Stmt *Replacement = SynthMessageExpr(NewMsg);
1600 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1601 return Replacement;
1602}
1603
1604/// SynthCountByEnumWithState - To print:
1605/// ((unsigned int (*)
1606/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1607/// (void *)objc_msgSend)((id)l_collection,
1608/// sel_registerName(
1609/// "countByEnumeratingWithState:objects:count:"),
1610/// &enumState,
1611/// (id *)__rw_items, (unsigned int)16)
1612///
1613void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1614 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1615 "id *, unsigned int))(void *)objc_msgSend)";
1616 buf += "\n\t\t";
1617 buf += "((id)l_collection,\n\t\t";
1618 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1619 buf += "\n\t\t";
1620 buf += "&enumState, "
1621 "(id *)__rw_items, (unsigned int)16)";
1622}
1623
1624/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1625/// statement to exit to its outer synthesized loop.
1626///
1627Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1628 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1629 return S;
1630 // replace break with goto __break_label
1631 std::string buf;
1632
1633 SourceLocation startLoc = S->getLocStart();
1634 buf = "goto __break_label_";
1635 buf += utostr(ObjCBcLabelNo.back());
1636 ReplaceText(startLoc, strlen("break"), buf);
1637
1638 return 0;
1639}
1640
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001641void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1642 SourceLocation Loc,
1643 std::string &LineString) {
1644 if (Loc.isFileID()) {
1645 LineString += "\n#line ";
1646 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1647 LineString += utostr(PLoc.getLine());
1648 LineString += " \"";
1649 LineString += Lexer::Stringify(PLoc.getFilename());
1650 LineString += "\"\n";
1651 }
1652}
1653
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001654/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1655/// statement to continue with its inner synthesized loop.
1656///
1657Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1658 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1659 return S;
1660 // replace continue with goto __continue_label
1661 std::string buf;
1662
1663 SourceLocation startLoc = S->getLocStart();
1664 buf = "goto __continue_label_";
1665 buf += utostr(ObjCBcLabelNo.back());
1666 ReplaceText(startLoc, strlen("continue"), buf);
1667
1668 return 0;
1669}
1670
1671/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1672/// It rewrites:
1673/// for ( type elem in collection) { stmts; }
1674
1675/// Into:
1676/// {
1677/// type elem;
1678/// struct __objcFastEnumerationState enumState = { 0 };
1679/// id __rw_items[16];
1680/// id l_collection = (id)collection;
1681/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1682/// objects:__rw_items count:16];
1683/// if (limit) {
1684/// unsigned long startMutations = *enumState.mutationsPtr;
1685/// do {
1686/// unsigned long counter = 0;
1687/// do {
1688/// if (startMutations != *enumState.mutationsPtr)
1689/// objc_enumerationMutation(l_collection);
1690/// elem = (type)enumState.itemsPtr[counter++];
1691/// stmts;
1692/// __continue_label: ;
1693/// } while (counter < limit);
1694/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1695/// objects:__rw_items count:16]);
1696/// elem = nil;
1697/// __break_label: ;
1698/// }
1699/// else
1700/// elem = nil;
1701/// }
1702///
1703Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1704 SourceLocation OrigEnd) {
1705 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1706 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1707 "ObjCForCollectionStmt Statement stack mismatch");
1708 assert(!ObjCBcLabelNo.empty() &&
1709 "ObjCForCollectionStmt - Label No stack empty");
1710
1711 SourceLocation startLoc = S->getLocStart();
1712 const char *startBuf = SM->getCharacterData(startLoc);
1713 StringRef elementName;
1714 std::string elementTypeAsString;
1715 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001716 // line directive first.
1717 SourceLocation ForEachLoc = S->getForLoc();
1718 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1719 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001720 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1721 // type elem;
1722 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1723 QualType ElementType = cast<ValueDecl>(D)->getType();
1724 if (ElementType->isObjCQualifiedIdType() ||
1725 ElementType->isObjCQualifiedInterfaceType())
1726 // Simply use 'id' for all qualified types.
1727 elementTypeAsString = "id";
1728 else
1729 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1730 buf += elementTypeAsString;
1731 buf += " ";
1732 elementName = D->getName();
1733 buf += elementName;
1734 buf += ";\n\t";
1735 }
1736 else {
1737 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1738 elementName = DR->getDecl()->getName();
1739 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1740 if (VD->getType()->isObjCQualifiedIdType() ||
1741 VD->getType()->isObjCQualifiedInterfaceType())
1742 // Simply use 'id' for all qualified types.
1743 elementTypeAsString = "id";
1744 else
1745 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1746 }
1747
1748 // struct __objcFastEnumerationState enumState = { 0 };
1749 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1750 // id __rw_items[16];
1751 buf += "id __rw_items[16];\n\t";
1752 // id l_collection = (id)
1753 buf += "id l_collection = (id)";
1754 // Find start location of 'collection' the hard way!
1755 const char *startCollectionBuf = startBuf;
1756 startCollectionBuf += 3; // skip 'for'
1757 startCollectionBuf = strchr(startCollectionBuf, '(');
1758 startCollectionBuf++; // skip '('
1759 // find 'in' and skip it.
1760 while (*startCollectionBuf != ' ' ||
1761 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1762 (*(startCollectionBuf+3) != ' ' &&
1763 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1764 startCollectionBuf++;
1765 startCollectionBuf += 3;
1766
1767 // Replace: "for (type element in" with string constructed thus far.
1768 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1769 // Replace ')' in for '(' type elem in collection ')' with ';'
1770 SourceLocation rightParenLoc = S->getRParenLoc();
1771 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1772 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1773 buf = ";\n\t";
1774
1775 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1776 // objects:__rw_items count:16];
1777 // which is synthesized into:
1778 // unsigned int limit =
1779 // ((unsigned int (*)
1780 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1781 // (void *)objc_msgSend)((id)l_collection,
1782 // sel_registerName(
1783 // "countByEnumeratingWithState:objects:count:"),
1784 // (struct __objcFastEnumerationState *)&state,
1785 // (id *)__rw_items, (unsigned int)16);
1786 buf += "unsigned long limit =\n\t\t";
1787 SynthCountByEnumWithState(buf);
1788 buf += ";\n\t";
1789 /// if (limit) {
1790 /// unsigned long startMutations = *enumState.mutationsPtr;
1791 /// do {
1792 /// unsigned long counter = 0;
1793 /// do {
1794 /// if (startMutations != *enumState.mutationsPtr)
1795 /// objc_enumerationMutation(l_collection);
1796 /// elem = (type)enumState.itemsPtr[counter++];
1797 buf += "if (limit) {\n\t";
1798 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1799 buf += "do {\n\t\t";
1800 buf += "unsigned long counter = 0;\n\t\t";
1801 buf += "do {\n\t\t\t";
1802 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1803 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1804 buf += elementName;
1805 buf += " = (";
1806 buf += elementTypeAsString;
1807 buf += ")enumState.itemsPtr[counter++];";
1808 // Replace ')' in for '(' type elem in collection ')' with all of these.
1809 ReplaceText(lparenLoc, 1, buf);
1810
1811 /// __continue_label: ;
1812 /// } while (counter < limit);
1813 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1814 /// objects:__rw_items count:16]);
1815 /// elem = nil;
1816 /// __break_label: ;
1817 /// }
1818 /// else
1819 /// elem = nil;
1820 /// }
1821 ///
1822 buf = ";\n\t";
1823 buf += "__continue_label_";
1824 buf += utostr(ObjCBcLabelNo.back());
1825 buf += ": ;";
1826 buf += "\n\t\t";
1827 buf += "} while (counter < limit);\n\t";
1828 buf += "} while (limit = ";
1829 SynthCountByEnumWithState(buf);
1830 buf += ");\n\t";
1831 buf += elementName;
1832 buf += " = ((";
1833 buf += elementTypeAsString;
1834 buf += ")0);\n\t";
1835 buf += "__break_label_";
1836 buf += utostr(ObjCBcLabelNo.back());
1837 buf += ": ;\n\t";
1838 buf += "}\n\t";
1839 buf += "else\n\t\t";
1840 buf += elementName;
1841 buf += " = ((";
1842 buf += elementTypeAsString;
1843 buf += ")0);\n\t";
1844 buf += "}\n";
1845
1846 // Insert all these *after* the statement body.
1847 // FIXME: If this should support Obj-C++, support CXXTryStmt
1848 if (isa<CompoundStmt>(S->getBody())) {
1849 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1850 InsertText(endBodyLoc, buf);
1851 } else {
1852 /* Need to treat single statements specially. For example:
1853 *
1854 * for (A *a in b) if (stuff()) break;
1855 * for (A *a in b) xxxyy;
1856 *
1857 * The following code simply scans ahead to the semi to find the actual end.
1858 */
1859 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1860 const char *semiBuf = strchr(stmtBuf, ';');
1861 assert(semiBuf && "Can't find ';'");
1862 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1863 InsertText(endBodyLoc, buf);
1864 }
1865 Stmts.pop_back();
1866 ObjCBcLabelNo.pop_back();
1867 return 0;
1868}
1869
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001870static void Write_RethrowObject(std::string &buf) {
1871 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1872 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1873 buf += "\tid rethrow;\n";
1874 buf += "\t} _fin_force_rethow(_rethrow);";
1875}
1876
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001877/// RewriteObjCSynchronizedStmt -
1878/// This routine rewrites @synchronized(expr) stmt;
1879/// into:
1880/// objc_sync_enter(expr);
1881/// @try stmt @finally { objc_sync_exit(expr); }
1882///
1883Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1884 // Get the start location and compute the semi location.
1885 SourceLocation startLoc = S->getLocStart();
1886 const char *startBuf = SM->getCharacterData(startLoc);
1887
1888 assert((*startBuf == '@') && "bogus @synchronized location");
1889
1890 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001891 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1892 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1893 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001895 const char *lparenBuf = startBuf;
1896 while (*lparenBuf != '(') lparenBuf++;
1897 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001898
1899 buf = "; objc_sync_enter(_sync_obj);\n";
1900 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1901 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1902 buf += "\n\tid sync_exit;";
1903 buf += "\n\t} _sync_exit(_sync_obj);\n";
1904
1905 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1906 // the sync expression is typically a message expression that's already
1907 // been rewritten! (which implies the SourceLocation's are invalid).
1908 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1909 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1910 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1911 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1912
1913 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1914 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1915 assert (*LBraceLocBuf == '{');
1916 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001917
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001918 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001919 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1920 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001921
1922 buf = "} catch (id e) {_rethrow = e;}\n";
1923 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001924 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001925 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001926
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001927 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001928
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001929 return 0;
1930}
1931
1932void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1933{
1934 // Perform a bottom up traversal of all children.
1935 for (Stmt::child_range CI = S->children(); CI; ++CI)
1936 if (*CI)
1937 WarnAboutReturnGotoStmts(*CI);
1938
1939 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1940 Diags.Report(Context->getFullLoc(S->getLocStart()),
1941 TryFinallyContainsReturnDiag);
1942 }
1943 return;
1944}
1945
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001946Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1947 SourceLocation startLoc = S->getAtLoc();
1948 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001949 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1950 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001951
1952 return 0;
1953}
1954
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001955Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001956 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001957 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001958 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001959 SourceLocation TryLocation = S->getAtTryLoc();
1960 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001961
1962 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001963 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001964 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001965 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001966 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001967 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001968 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001969 // Get the start location and compute the semi location.
1970 SourceLocation startLoc = S->getLocStart();
1971 const char *startBuf = SM->getCharacterData(startLoc);
1972
1973 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001974 if (finalStmt)
1975 ReplaceText(startLoc, 1, buf);
1976 else
1977 // @try -> try
1978 ReplaceText(startLoc, 1, "");
1979
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001980 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1981 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001982 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001983
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001984 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001985 bool AtRemoved = false;
1986 if (catchDecl) {
1987 QualType t = catchDecl->getType();
1988 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1989 // Should be a pointer to a class.
1990 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1991 if (IDecl) {
1992 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001993 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1994
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001995 startBuf = SM->getCharacterData(startLoc);
1996 assert((*startBuf == '@') && "bogus @catch location");
1997 SourceLocation rParenLoc = Catch->getRParenLoc();
1998 const char *rParenBuf = SM->getCharacterData(rParenLoc);
1999
2000 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002001 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002002 Result += " *_"; Result += catchDecl->getNameAsString();
2003 Result += ")";
2004 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2005 // Foo *e = (Foo *)_e;
2006 Result.clear();
2007 Result = "{ ";
2008 Result += IDecl->getNameAsString();
2009 Result += " *"; Result += catchDecl->getNameAsString();
2010 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2011 Result += "_"; Result += catchDecl->getNameAsString();
2012
2013 Result += "; ";
2014 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2015 ReplaceText(lBraceLoc, 1, Result);
2016 AtRemoved = true;
2017 }
2018 }
2019 }
2020 if (!AtRemoved)
2021 // @catch -> catch
2022 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002023
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002024 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002025 if (finalStmt) {
2026 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002027 SourceLocation FinallyLoc = finalStmt->getLocStart();
2028
2029 if (noCatch) {
2030 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2031 buf += "catch (id e) {_rethrow = e;}\n";
2032 }
2033 else {
2034 buf += "}\n";
2035 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2036 buf += "catch (id e) {_rethrow = e;}\n";
2037 }
2038
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002039 SourceLocation startFinalLoc = finalStmt->getLocStart();
2040 ReplaceText(startFinalLoc, 8, buf);
2041 Stmt *body = finalStmt->getFinallyBody();
2042 SourceLocation startFinalBodyLoc = body->getLocStart();
2043 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002044 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002045 ReplaceText(startFinalBodyLoc, 1, buf);
2046
2047 SourceLocation endFinalBodyLoc = body->getLocEnd();
2048 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002049 // Now check for any return/continue/go statements within the @try.
2050 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002051 }
2052
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002053 return 0;
2054}
2055
2056// This can't be done with ReplaceStmt(S, ThrowExpr), since
2057// the throw expression is typically a message expression that's already
2058// been rewritten! (which implies the SourceLocation's are invalid).
2059Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2060 // Get the start location and compute the semi location.
2061 SourceLocation startLoc = S->getLocStart();
2062 const char *startBuf = SM->getCharacterData(startLoc);
2063
2064 assert((*startBuf == '@') && "bogus @throw location");
2065
2066 std::string buf;
2067 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2068 if (S->getThrowExpr())
2069 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002070 else
2071 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002072
2073 // handle "@ throw" correctly.
2074 const char *wBuf = strchr(startBuf, 'w');
2075 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2076 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2077
2078 const char *semiBuf = strchr(startBuf, ';');
2079 assert((*semiBuf == ';') && "@throw: can't find ';'");
2080 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002081 if (S->getThrowExpr())
2082 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002083 return 0;
2084}
2085
2086Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2087 // Create a new string expression.
2088 QualType StrType = Context->getPointerType(Context->CharTy);
2089 std::string StrEncoding;
2090 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2091 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2092 StringLiteral::Ascii, false,
2093 StrType, SourceLocation());
2094 ReplaceStmt(Exp, Replacement);
2095
2096 // Replace this subexpr in the parent.
2097 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2098 return Replacement;
2099}
2100
2101Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2102 if (!SelGetUidFunctionDecl)
2103 SynthSelGetUidFunctionDecl();
2104 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2105 // Create a call to sel_registerName("selName").
2106 SmallVector<Expr*, 8> SelExprs;
2107 QualType argType = Context->getPointerType(Context->CharTy);
2108 SelExprs.push_back(StringLiteral::Create(*Context,
2109 Exp->getSelector().getAsString(),
2110 StringLiteral::Ascii, false,
2111 argType, SourceLocation()));
2112 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2113 &SelExprs[0], SelExprs.size());
2114 ReplaceStmt(Exp, SelExp);
2115 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2116 return SelExp;
2117}
2118
2119CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2120 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2121 SourceLocation EndLoc) {
2122 // Get the type, we will need to reference it in a couple spots.
2123 QualType msgSendType = FD->getType();
2124
2125 // Create a reference to the objc_msgSend() declaration.
2126 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002127 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002128
2129 // Now, we cast the reference to a pointer to the objc_msgSend type.
2130 QualType pToFunc = Context->getPointerType(msgSendType);
2131 ImplicitCastExpr *ICE =
2132 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2133 DRE, 0, VK_RValue);
2134
2135 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2136
2137 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002138 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002139 FT->getCallResultType(*Context),
2140 VK_RValue, EndLoc);
2141 return Exp;
2142}
2143
2144static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2145 const char *&startRef, const char *&endRef) {
2146 while (startBuf < endBuf) {
2147 if (*startBuf == '<')
2148 startRef = startBuf; // mark the start.
2149 if (*startBuf == '>') {
2150 if (startRef && *startRef == '<') {
2151 endRef = startBuf; // mark the end.
2152 return true;
2153 }
2154 return false;
2155 }
2156 startBuf++;
2157 }
2158 return false;
2159}
2160
2161static void scanToNextArgument(const char *&argRef) {
2162 int angle = 0;
2163 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2164 if (*argRef == '<')
2165 angle++;
2166 else if (*argRef == '>')
2167 angle--;
2168 argRef++;
2169 }
2170 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2171}
2172
2173bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2174 if (T->isObjCQualifiedIdType())
2175 return true;
2176 if (const PointerType *PT = T->getAs<PointerType>()) {
2177 if (PT->getPointeeType()->isObjCQualifiedIdType())
2178 return true;
2179 }
2180 if (T->isObjCObjectPointerType()) {
2181 T = T->getPointeeType();
2182 return T->isObjCQualifiedInterfaceType();
2183 }
2184 if (T->isArrayType()) {
2185 QualType ElemTy = Context->getBaseElementType(T);
2186 return needToScanForQualifiers(ElemTy);
2187 }
2188 return false;
2189}
2190
2191void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2192 QualType Type = E->getType();
2193 if (needToScanForQualifiers(Type)) {
2194 SourceLocation Loc, EndLoc;
2195
2196 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2197 Loc = ECE->getLParenLoc();
2198 EndLoc = ECE->getRParenLoc();
2199 } else {
2200 Loc = E->getLocStart();
2201 EndLoc = E->getLocEnd();
2202 }
2203 // This will defend against trying to rewrite synthesized expressions.
2204 if (Loc.isInvalid() || EndLoc.isInvalid())
2205 return;
2206
2207 const char *startBuf = SM->getCharacterData(Loc);
2208 const char *endBuf = SM->getCharacterData(EndLoc);
2209 const char *startRef = 0, *endRef = 0;
2210 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2211 // Get the locations of the startRef, endRef.
2212 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2213 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2214 // Comment out the protocol references.
2215 InsertText(LessLoc, "/*");
2216 InsertText(GreaterLoc, "*/");
2217 }
2218 }
2219}
2220
2221void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2222 SourceLocation Loc;
2223 QualType Type;
2224 const FunctionProtoType *proto = 0;
2225 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2226 Loc = VD->getLocation();
2227 Type = VD->getType();
2228 }
2229 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2230 Loc = FD->getLocation();
2231 // Check for ObjC 'id' and class types that have been adorned with protocol
2232 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2233 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2234 assert(funcType && "missing function type");
2235 proto = dyn_cast<FunctionProtoType>(funcType);
2236 if (!proto)
2237 return;
2238 Type = proto->getResultType();
2239 }
2240 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2241 Loc = FD->getLocation();
2242 Type = FD->getType();
2243 }
2244 else
2245 return;
2246
2247 if (needToScanForQualifiers(Type)) {
2248 // Since types are unique, we need to scan the buffer.
2249
2250 const char *endBuf = SM->getCharacterData(Loc);
2251 const char *startBuf = endBuf;
2252 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2253 startBuf--; // scan backward (from the decl location) for return type.
2254 const char *startRef = 0, *endRef = 0;
2255 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2256 // Get the locations of the startRef, endRef.
2257 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2258 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2259 // Comment out the protocol references.
2260 InsertText(LessLoc, "/*");
2261 InsertText(GreaterLoc, "*/");
2262 }
2263 }
2264 if (!proto)
2265 return; // most likely, was a variable
2266 // Now check arguments.
2267 const char *startBuf = SM->getCharacterData(Loc);
2268 const char *startFuncBuf = startBuf;
2269 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2270 if (needToScanForQualifiers(proto->getArgType(i))) {
2271 // Since types are unique, we need to scan the buffer.
2272
2273 const char *endBuf = startBuf;
2274 // scan forward (from the decl location) for argument types.
2275 scanToNextArgument(endBuf);
2276 const char *startRef = 0, *endRef = 0;
2277 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2278 // Get the locations of the startRef, endRef.
2279 SourceLocation LessLoc =
2280 Loc.getLocWithOffset(startRef-startFuncBuf);
2281 SourceLocation GreaterLoc =
2282 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2283 // Comment out the protocol references.
2284 InsertText(LessLoc, "/*");
2285 InsertText(GreaterLoc, "*/");
2286 }
2287 startBuf = ++endBuf;
2288 }
2289 else {
2290 // If the function name is derived from a macro expansion, then the
2291 // argument buffer will not follow the name. Need to speak with Chris.
2292 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2293 startBuf++; // scan forward (from the decl location) for argument types.
2294 startBuf++;
2295 }
2296 }
2297}
2298
2299void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2300 QualType QT = ND->getType();
2301 const Type* TypePtr = QT->getAs<Type>();
2302 if (!isa<TypeOfExprType>(TypePtr))
2303 return;
2304 while (isa<TypeOfExprType>(TypePtr)) {
2305 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2306 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2307 TypePtr = QT->getAs<Type>();
2308 }
2309 // FIXME. This will not work for multiple declarators; as in:
2310 // __typeof__(a) b,c,d;
2311 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2312 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2313 const char *startBuf = SM->getCharacterData(DeclLoc);
2314 if (ND->getInit()) {
2315 std::string Name(ND->getNameAsString());
2316 TypeAsString += " " + Name + " = ";
2317 Expr *E = ND->getInit();
2318 SourceLocation startLoc;
2319 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2320 startLoc = ECE->getLParenLoc();
2321 else
2322 startLoc = E->getLocStart();
2323 startLoc = SM->getExpansionLoc(startLoc);
2324 const char *endBuf = SM->getCharacterData(startLoc);
2325 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2326 }
2327 else {
2328 SourceLocation X = ND->getLocEnd();
2329 X = SM->getExpansionLoc(X);
2330 const char *endBuf = SM->getCharacterData(X);
2331 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2332 }
2333}
2334
2335// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2336void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2337 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2338 SmallVector<QualType, 16> ArgTys;
2339 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2340 QualType getFuncType =
2341 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2342 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002343 SourceLocation(),
2344 SourceLocation(),
2345 SelGetUidIdent, getFuncType, 0,
2346 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002347}
2348
2349void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2350 // declared in <objc/objc.h>
2351 if (FD->getIdentifier() &&
2352 FD->getName() == "sel_registerName") {
2353 SelGetUidFunctionDecl = FD;
2354 return;
2355 }
2356 RewriteObjCQualifiedInterfaceTypes(FD);
2357}
2358
2359void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2360 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2361 const char *argPtr = TypeString.c_str();
2362 if (!strchr(argPtr, '^')) {
2363 Str += TypeString;
2364 return;
2365 }
2366 while (*argPtr) {
2367 Str += (*argPtr == '^' ? '*' : *argPtr);
2368 argPtr++;
2369 }
2370}
2371
2372// FIXME. Consolidate this routine with RewriteBlockPointerType.
2373void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2374 ValueDecl *VD) {
2375 QualType Type = VD->getType();
2376 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2377 const char *argPtr = TypeString.c_str();
2378 int paren = 0;
2379 while (*argPtr) {
2380 switch (*argPtr) {
2381 case '(':
2382 Str += *argPtr;
2383 paren++;
2384 break;
2385 case ')':
2386 Str += *argPtr;
2387 paren--;
2388 break;
2389 case '^':
2390 Str += '*';
2391 if (paren == 1)
2392 Str += VD->getNameAsString();
2393 break;
2394 default:
2395 Str += *argPtr;
2396 break;
2397 }
2398 argPtr++;
2399 }
2400}
2401
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002402void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2403 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2404 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2405 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2406 if (!proto)
2407 return;
2408 QualType Type = proto->getResultType();
2409 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2410 FdStr += " ";
2411 FdStr += FD->getName();
2412 FdStr += "(";
2413 unsigned numArgs = proto->getNumArgs();
2414 for (unsigned i = 0; i < numArgs; i++) {
2415 QualType ArgType = proto->getArgType(i);
2416 RewriteBlockPointerType(FdStr, ArgType);
2417 if (i+1 < numArgs)
2418 FdStr += ", ";
2419 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002420 if (FD->isVariadic()) {
2421 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2422 }
2423 else
2424 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002425 InsertText(FunLocStart, FdStr);
2426}
2427
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002428// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002429void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2430 if (SuperContructorFunctionDecl)
2431 return;
2432 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2433 SmallVector<QualType, 16> ArgTys;
2434 QualType argT = Context->getObjCIdType();
2435 assert(!argT.isNull() && "Can't find 'id' type");
2436 ArgTys.push_back(argT);
2437 ArgTys.push_back(argT);
2438 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2439 &ArgTys[0], ArgTys.size());
2440 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002441 SourceLocation(),
2442 SourceLocation(),
2443 msgSendIdent, msgSendType,
2444 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002445}
2446
2447// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2448void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2449 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2450 SmallVector<QualType, 16> ArgTys;
2451 QualType argT = Context->getObjCIdType();
2452 assert(!argT.isNull() && "Can't find 'id' type");
2453 ArgTys.push_back(argT);
2454 argT = Context->getObjCSelType();
2455 assert(!argT.isNull() && "Can't find 'SEL' type");
2456 ArgTys.push_back(argT);
2457 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2458 &ArgTys[0], ArgTys.size(),
2459 true /*isVariadic*/);
2460 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002461 SourceLocation(),
2462 SourceLocation(),
2463 msgSendIdent, msgSendType, 0,
2464 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002465}
2466
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002467// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002468void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2469 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002470 SmallVector<QualType, 2> ArgTys;
2471 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002472 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002473 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002474 true /*isVariadic*/);
2475 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002476 SourceLocation(),
2477 SourceLocation(),
2478 msgSendIdent, msgSendType, 0,
2479 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002480}
2481
2482// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2483void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2484 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2485 SmallVector<QualType, 16> ArgTys;
2486 QualType argT = Context->getObjCIdType();
2487 assert(!argT.isNull() && "Can't find 'id' type");
2488 ArgTys.push_back(argT);
2489 argT = Context->getObjCSelType();
2490 assert(!argT.isNull() && "Can't find 'SEL' type");
2491 ArgTys.push_back(argT);
2492 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2493 &ArgTys[0], ArgTys.size(),
2494 true /*isVariadic*/);
2495 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002496 SourceLocation(),
2497 SourceLocation(),
2498 msgSendIdent, msgSendType, 0,
2499 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002500}
2501
2502// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002503// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002504void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2505 IdentifierInfo *msgSendIdent =
2506 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002507 SmallVector<QualType, 2> ArgTys;
2508 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002509 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002510 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002511 true /*isVariadic*/);
2512 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2513 SourceLocation(),
2514 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002515 msgSendIdent,
2516 msgSendType, 0,
2517 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002518}
2519
2520// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2521void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2522 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2523 SmallVector<QualType, 16> ArgTys;
2524 QualType argT = Context->getObjCIdType();
2525 assert(!argT.isNull() && "Can't find 'id' type");
2526 ArgTys.push_back(argT);
2527 argT = Context->getObjCSelType();
2528 assert(!argT.isNull() && "Can't find 'SEL' type");
2529 ArgTys.push_back(argT);
2530 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2531 &ArgTys[0], ArgTys.size(),
2532 true /*isVariadic*/);
2533 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002534 SourceLocation(),
2535 SourceLocation(),
2536 msgSendIdent, msgSendType, 0,
2537 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002538}
2539
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002540// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002541void RewriteModernObjC::SynthGetClassFunctionDecl() {
2542 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2543 SmallVector<QualType, 16> ArgTys;
2544 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002545 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002546 &ArgTys[0], ArgTys.size());
2547 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002548 SourceLocation(),
2549 SourceLocation(),
2550 getClassIdent, getClassType, 0,
2551 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002552}
2553
2554// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2555void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2556 IdentifierInfo *getSuperClassIdent =
2557 &Context->Idents.get("class_getSuperclass");
2558 SmallVector<QualType, 16> ArgTys;
2559 ArgTys.push_back(Context->getObjCClassType());
2560 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2561 &ArgTys[0], ArgTys.size());
2562 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2563 SourceLocation(),
2564 SourceLocation(),
2565 getSuperClassIdent,
2566 getClassType, 0,
Chad Rosiere3b29882013-01-04 22:40:33 +00002567 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002568}
2569
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002570// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002571void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2572 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2573 SmallVector<QualType, 16> ArgTys;
2574 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002575 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002576 &ArgTys[0], ArgTys.size());
2577 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002578 SourceLocation(),
2579 SourceLocation(),
2580 getClassIdent, getClassType,
2581 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002582}
2583
2584Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2585 QualType strType = getConstantStringStructType();
2586
2587 std::string S = "__NSConstantStringImpl_";
2588
2589 std::string tmpName = InFileName;
2590 unsigned i;
2591 for (i=0; i < tmpName.length(); i++) {
2592 char c = tmpName.at(i);
2593 // replace any non alphanumeric characters with '_'.
2594 if (!isalpha(c) && (c < '0' || c > '9'))
2595 tmpName[i] = '_';
2596 }
2597 S += tmpName;
2598 S += "_";
2599 S += utostr(NumObjCStringLiterals++);
2600
2601 Preamble += "static __NSConstantStringImpl " + S;
2602 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2603 Preamble += "0x000007c8,"; // utf8_str
2604 // The pretty printer for StringLiteral handles escape characters properly.
2605 std::string prettyBufS;
2606 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002607 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002608 Preamble += prettyBuf.str();
2609 Preamble += ",";
2610 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2611
2612 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2613 SourceLocation(), &Context->Idents.get(S),
2614 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002615 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002616 SourceLocation());
2617 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2618 Context->getPointerType(DRE->getType()),
2619 VK_RValue, OK_Ordinary,
2620 SourceLocation());
2621 // cast to NSConstantString *
2622 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2623 CK_CPointerToObjCPointerCast, Unop);
2624 ReplaceStmt(Exp, cast);
2625 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2626 return cast;
2627}
2628
Fariborz Jahanian55947042012-03-27 20:17:30 +00002629Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2630 unsigned IntSize =
2631 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2632
2633 Expr *FlagExp = IntegerLiteral::Create(*Context,
2634 llvm::APInt(IntSize, Exp->getValue()),
2635 Context->IntTy, Exp->getLocation());
2636 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2637 CK_BitCast, FlagExp);
2638 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2639 cast);
2640 ReplaceStmt(Exp, PE);
2641 return PE;
2642}
2643
Patrick Beardeb382ec2012-04-19 00:25:12 +00002644Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002645 // synthesize declaration of helper functions needed in this routine.
2646 if (!SelGetUidFunctionDecl)
2647 SynthSelGetUidFunctionDecl();
2648 // use objc_msgSend() for all.
2649 if (!MsgSendFunctionDecl)
2650 SynthMsgSendFunctionDecl();
2651 if (!GetClassFunctionDecl)
2652 SynthGetClassFunctionDecl();
2653
2654 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2655 SourceLocation StartLoc = Exp->getLocStart();
2656 SourceLocation EndLoc = Exp->getLocEnd();
2657
2658 // Synthesize a call to objc_msgSend().
2659 SmallVector<Expr*, 4> MsgExprs;
2660 SmallVector<Expr*, 4> ClsExprs;
2661 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002662
Patrick Beardeb382ec2012-04-19 00:25:12 +00002663 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2664 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2665 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002666
Patrick Beardeb382ec2012-04-19 00:25:12 +00002667 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002668 ClsExprs.push_back(StringLiteral::Create(*Context,
2669 clsName->getName(),
2670 StringLiteral::Ascii, false,
2671 argType, SourceLocation()));
2672 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2673 &ClsExprs[0],
2674 ClsExprs.size(),
2675 StartLoc, EndLoc);
2676 MsgExprs.push_back(Cls);
2677
Patrick Beardeb382ec2012-04-19 00:25:12 +00002678 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002679 // it will be the 2nd argument.
2680 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002681 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002682 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002683 StringLiteral::Ascii, false,
2684 argType, SourceLocation()));
2685 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2686 &SelExprs[0], SelExprs.size(),
2687 StartLoc, EndLoc);
2688 MsgExprs.push_back(SelExp);
2689
Patrick Beardeb382ec2012-04-19 00:25:12 +00002690 // User provided sub-expression is the 3rd, and last, argument.
2691 Expr *subExpr = Exp->getSubExpr();
2692 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002693 QualType type = ICE->getType();
2694 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2695 CastKind CK = CK_BitCast;
2696 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2697 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002698 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002699 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002700 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002701
2702 SmallVector<QualType, 4> ArgTypes;
2703 ArgTypes.push_back(Context->getObjCIdType());
2704 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002705 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2706 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002707 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002708
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002709 QualType returnType = Exp->getType();
2710 // Get the type, we will need to reference it in a couple spots.
2711 QualType msgSendType = MsgSendFlavor->getType();
2712
2713 // Create a reference to the objc_msgSend() declaration.
2714 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2715 VK_LValue, SourceLocation());
2716
2717 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002718 Context->getPointerType(Context->VoidTy),
2719 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002720
2721 // Now do the "normal" pointer to function cast.
2722 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002723 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2724 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002725 castType = Context->getPointerType(castType);
2726 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2727 cast);
2728
2729 // Don't forget the parens to enforce the proper binding.
2730 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2731
2732 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002733 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002734 FT->getResultType(), VK_RValue,
2735 EndLoc);
2736 ReplaceStmt(Exp, CE);
2737 return CE;
2738}
2739
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002740Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2741 // synthesize declaration of helper functions needed in this routine.
2742 if (!SelGetUidFunctionDecl)
2743 SynthSelGetUidFunctionDecl();
2744 // use objc_msgSend() for all.
2745 if (!MsgSendFunctionDecl)
2746 SynthMsgSendFunctionDecl();
2747 if (!GetClassFunctionDecl)
2748 SynthGetClassFunctionDecl();
2749
2750 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2751 SourceLocation StartLoc = Exp->getLocStart();
2752 SourceLocation EndLoc = Exp->getLocEnd();
2753
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002754 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002755 QualType IntQT = Context->IntTy;
2756 QualType NSArrayFType =
2757 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002758 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002759 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2760 DeclRefExpr *NSArrayDRE =
2761 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2762 SourceLocation());
2763
2764 SmallVector<Expr*, 16> InitExprs;
2765 unsigned NumElements = Exp->getNumElements();
2766 unsigned UnsignedIntSize =
2767 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2768 Expr *count = IntegerLiteral::Create(*Context,
2769 llvm::APInt(UnsignedIntSize, NumElements),
2770 Context->UnsignedIntTy, SourceLocation());
2771 InitExprs.push_back(count);
2772 for (unsigned i = 0; i < NumElements; i++)
2773 InitExprs.push_back(Exp->getElement(i));
2774 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002775 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002776 NSArrayFType, VK_LValue, SourceLocation());
2777
2778 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2779 SourceLocation(),
2780 &Context->Idents.get("arr"),
2781 Context->getPointerType(Context->VoidPtrTy), 0,
2782 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002783 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002784 MemberExpr *ArrayLiteralME =
2785 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2786 SourceLocation(),
2787 ARRFD->getType(), VK_LValue,
2788 OK_Ordinary);
2789 QualType ConstIdT = Context->getObjCIdType().withConst();
2790 CStyleCastExpr * ArrayLiteralObjects =
2791 NoTypeInfoCStyleCastExpr(Context,
2792 Context->getPointerType(ConstIdT),
2793 CK_BitCast,
2794 ArrayLiteralME);
2795
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002796 // Synthesize a call to objc_msgSend().
2797 SmallVector<Expr*, 32> MsgExprs;
2798 SmallVector<Expr*, 4> ClsExprs;
2799 QualType argType = Context->getPointerType(Context->CharTy);
2800 QualType expType = Exp->getType();
2801
2802 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2803 ObjCInterfaceDecl *Class =
2804 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2805
2806 IdentifierInfo *clsName = Class->getIdentifier();
2807 ClsExprs.push_back(StringLiteral::Create(*Context,
2808 clsName->getName(),
2809 StringLiteral::Ascii, false,
2810 argType, SourceLocation()));
2811 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2812 &ClsExprs[0],
2813 ClsExprs.size(),
2814 StartLoc, EndLoc);
2815 MsgExprs.push_back(Cls);
2816
2817 // Create a call to sel_registerName("arrayWithObjects:count:").
2818 // it will be the 2nd argument.
2819 SmallVector<Expr*, 4> SelExprs;
2820 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2821 SelExprs.push_back(StringLiteral::Create(*Context,
2822 ArrayMethod->getSelector().getAsString(),
2823 StringLiteral::Ascii, false,
2824 argType, SourceLocation()));
2825 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2826 &SelExprs[0], SelExprs.size(),
2827 StartLoc, EndLoc);
2828 MsgExprs.push_back(SelExp);
2829
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002830 // (const id [])objects
2831 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002832
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002833 // (NSUInteger)cnt
2834 Expr *cnt = IntegerLiteral::Create(*Context,
2835 llvm::APInt(UnsignedIntSize, NumElements),
2836 Context->UnsignedIntTy, SourceLocation());
2837 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002838
2839
2840 SmallVector<QualType, 4> ArgTypes;
2841 ArgTypes.push_back(Context->getObjCIdType());
2842 ArgTypes.push_back(Context->getObjCSelType());
2843 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2844 E = ArrayMethod->param_end(); PI != E; ++PI)
2845 ArgTypes.push_back((*PI)->getType());
2846
2847 QualType returnType = Exp->getType();
2848 // Get the type, we will need to reference it in a couple spots.
2849 QualType msgSendType = MsgSendFlavor->getType();
2850
2851 // Create a reference to the objc_msgSend() declaration.
2852 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2853 VK_LValue, SourceLocation());
2854
2855 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2856 Context->getPointerType(Context->VoidTy),
2857 CK_BitCast, DRE);
2858
2859 // Now do the "normal" pointer to function cast.
2860 QualType castType =
2861 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2862 ArrayMethod->isVariadic());
2863 castType = Context->getPointerType(castType);
2864 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2865 cast);
2866
2867 // Don't forget the parens to enforce the proper binding.
2868 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2869
2870 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002871 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002872 FT->getResultType(), VK_RValue,
2873 EndLoc);
2874 ReplaceStmt(Exp, CE);
2875 return CE;
2876}
2877
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002878Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2879 // synthesize declaration of helper functions needed in this routine.
2880 if (!SelGetUidFunctionDecl)
2881 SynthSelGetUidFunctionDecl();
2882 // use objc_msgSend() for all.
2883 if (!MsgSendFunctionDecl)
2884 SynthMsgSendFunctionDecl();
2885 if (!GetClassFunctionDecl)
2886 SynthGetClassFunctionDecl();
2887
2888 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2889 SourceLocation StartLoc = Exp->getLocStart();
2890 SourceLocation EndLoc = Exp->getLocEnd();
2891
2892 // Build the expression: __NSContainer_literal(int, ...).arr
2893 QualType IntQT = Context->IntTy;
2894 QualType NSDictFType =
2895 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2896 std::string NSDictFName("__NSContainer_literal");
2897 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2898 DeclRefExpr *NSDictDRE =
2899 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2900 SourceLocation());
2901
2902 SmallVector<Expr*, 16> KeyExprs;
2903 SmallVector<Expr*, 16> ValueExprs;
2904
2905 unsigned NumElements = Exp->getNumElements();
2906 unsigned UnsignedIntSize =
2907 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2908 Expr *count = IntegerLiteral::Create(*Context,
2909 llvm::APInt(UnsignedIntSize, NumElements),
2910 Context->UnsignedIntTy, SourceLocation());
2911 KeyExprs.push_back(count);
2912 ValueExprs.push_back(count);
2913 for (unsigned i = 0; i < NumElements; i++) {
2914 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2915 KeyExprs.push_back(Element.Key);
2916 ValueExprs.push_back(Element.Value);
2917 }
2918
2919 // (const id [])objects
2920 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002921 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002922 NSDictFType, VK_LValue, SourceLocation());
2923
2924 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2925 SourceLocation(),
2926 &Context->Idents.get("arr"),
2927 Context->getPointerType(Context->VoidPtrTy), 0,
2928 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002929 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002930 MemberExpr *DictLiteralValueME =
2931 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2932 SourceLocation(),
2933 ARRFD->getType(), VK_LValue,
2934 OK_Ordinary);
2935 QualType ConstIdT = Context->getObjCIdType().withConst();
2936 CStyleCastExpr * DictValueObjects =
2937 NoTypeInfoCStyleCastExpr(Context,
2938 Context->getPointerType(ConstIdT),
2939 CK_BitCast,
2940 DictLiteralValueME);
2941 // (const id <NSCopying> [])keys
2942 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002943 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002944 NSDictFType, VK_LValue, SourceLocation());
2945
2946 MemberExpr *DictLiteralKeyME =
2947 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2948 SourceLocation(),
2949 ARRFD->getType(), VK_LValue,
2950 OK_Ordinary);
2951
2952 CStyleCastExpr * DictKeyObjects =
2953 NoTypeInfoCStyleCastExpr(Context,
2954 Context->getPointerType(ConstIdT),
2955 CK_BitCast,
2956 DictLiteralKeyME);
2957
2958
2959
2960 // Synthesize a call to objc_msgSend().
2961 SmallVector<Expr*, 32> MsgExprs;
2962 SmallVector<Expr*, 4> ClsExprs;
2963 QualType argType = Context->getPointerType(Context->CharTy);
2964 QualType expType = Exp->getType();
2965
2966 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2967 ObjCInterfaceDecl *Class =
2968 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2969
2970 IdentifierInfo *clsName = Class->getIdentifier();
2971 ClsExprs.push_back(StringLiteral::Create(*Context,
2972 clsName->getName(),
2973 StringLiteral::Ascii, false,
2974 argType, SourceLocation()));
2975 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2976 &ClsExprs[0],
2977 ClsExprs.size(),
2978 StartLoc, EndLoc);
2979 MsgExprs.push_back(Cls);
2980
2981 // Create a call to sel_registerName("arrayWithObjects:count:").
2982 // it will be the 2nd argument.
2983 SmallVector<Expr*, 4> SelExprs;
2984 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2985 SelExprs.push_back(StringLiteral::Create(*Context,
2986 DictMethod->getSelector().getAsString(),
2987 StringLiteral::Ascii, false,
2988 argType, SourceLocation()));
2989 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2990 &SelExprs[0], SelExprs.size(),
2991 StartLoc, EndLoc);
2992 MsgExprs.push_back(SelExp);
2993
2994 // (const id [])objects
2995 MsgExprs.push_back(DictValueObjects);
2996
2997 // (const id <NSCopying> [])keys
2998 MsgExprs.push_back(DictKeyObjects);
2999
3000 // (NSUInteger)cnt
3001 Expr *cnt = IntegerLiteral::Create(*Context,
3002 llvm::APInt(UnsignedIntSize, NumElements),
3003 Context->UnsignedIntTy, SourceLocation());
3004 MsgExprs.push_back(cnt);
3005
3006
3007 SmallVector<QualType, 8> ArgTypes;
3008 ArgTypes.push_back(Context->getObjCIdType());
3009 ArgTypes.push_back(Context->getObjCSelType());
3010 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3011 E = DictMethod->param_end(); PI != E; ++PI) {
3012 QualType T = (*PI)->getType();
3013 if (const PointerType* PT = T->getAs<PointerType>()) {
3014 QualType PointeeTy = PT->getPointeeType();
3015 convertToUnqualifiedObjCType(PointeeTy);
3016 T = Context->getPointerType(PointeeTy);
3017 }
3018 ArgTypes.push_back(T);
3019 }
3020
3021 QualType returnType = Exp->getType();
3022 // Get the type, we will need to reference it in a couple spots.
3023 QualType msgSendType = MsgSendFlavor->getType();
3024
3025 // Create a reference to the objc_msgSend() declaration.
3026 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3027 VK_LValue, SourceLocation());
3028
3029 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3030 Context->getPointerType(Context->VoidTy),
3031 CK_BitCast, DRE);
3032
3033 // Now do the "normal" pointer to function cast.
3034 QualType castType =
3035 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3036 DictMethod->isVariadic());
3037 castType = Context->getPointerType(castType);
3038 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3039 cast);
3040
3041 // Don't forget the parens to enforce the proper binding.
3042 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3043
3044 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003045 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003046 FT->getResultType(), VK_RValue,
3047 EndLoc);
3048 ReplaceStmt(Exp, CE);
3049 return CE;
3050}
3051
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003052// struct __rw_objc_super {
3053// struct objc_object *object; struct objc_object *superClass;
3054// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003055QualType RewriteModernObjC::getSuperStructType() {
3056 if (!SuperStructDecl) {
3057 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3058 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003059 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003060 QualType FieldTypes[2];
3061
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003062 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003063 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003064 // struct objc_object *superClass;
3065 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003066
3067 // Create fields
3068 for (unsigned i = 0; i < 2; ++i) {
3069 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3070 SourceLocation(),
3071 SourceLocation(), 0,
3072 FieldTypes[i], 0,
3073 /*BitWidth=*/0,
3074 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003075 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003076 }
3077
3078 SuperStructDecl->completeDefinition();
3079 }
3080 return Context->getTagDeclType(SuperStructDecl);
3081}
3082
3083QualType RewriteModernObjC::getConstantStringStructType() {
3084 if (!ConstantStringDecl) {
3085 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3086 SourceLocation(), SourceLocation(),
3087 &Context->Idents.get("__NSConstantStringImpl"));
3088 QualType FieldTypes[4];
3089
3090 // struct objc_object *receiver;
3091 FieldTypes[0] = Context->getObjCIdType();
3092 // int flags;
3093 FieldTypes[1] = Context->IntTy;
3094 // char *str;
3095 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3096 // long length;
3097 FieldTypes[3] = Context->LongTy;
3098
3099 // Create fields
3100 for (unsigned i = 0; i < 4; ++i) {
3101 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3102 ConstantStringDecl,
3103 SourceLocation(),
3104 SourceLocation(), 0,
3105 FieldTypes[i], 0,
3106 /*BitWidth=*/0,
3107 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003108 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003109 }
3110
3111 ConstantStringDecl->completeDefinition();
3112 }
3113 return Context->getTagDeclType(ConstantStringDecl);
3114}
3115
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003116/// getFunctionSourceLocation - returns start location of a function
3117/// definition. Complication arises when function has declared as
3118/// extern "C" or extern "C" {...}
3119static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3120 FunctionDecl *FD) {
3121 if (FD->isExternC() && !FD->isMain()) {
3122 const DeclContext *DC = FD->getDeclContext();
3123 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3124 // if it is extern "C" {...}, return function decl's own location.
3125 if (!LSD->getRBraceLoc().isValid())
3126 return LSD->getExternLoc();
3127 }
3128 if (FD->getStorageClassAsWritten() != SC_None)
3129 R.RewriteBlockLiteralFunctionDecl(FD);
3130 return FD->getTypeSpecStartLoc();
3131}
3132
Fariborz Jahanian96205962012-11-06 17:30:23 +00003133void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3134
3135 SourceLocation Location = D->getLocation();
3136
3137 if (Location.isFileID()) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003138 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003139 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3140 LineString += utostr(PLoc.getLine());
3141 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003142 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003143 if (isa<ObjCMethodDecl>(D))
3144 LineString += "\"";
3145 else LineString += "\"\n";
3146
3147 Location = D->getLocStart();
3148 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3149 if (FD->isExternC() && !FD->isMain()) {
3150 const DeclContext *DC = FD->getDeclContext();
3151 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3152 // if it is extern "C" {...}, return function decl's own location.
3153 if (!LSD->getRBraceLoc().isValid())
3154 Location = LSD->getExternLoc();
3155 }
3156 }
3157 InsertText(Location, LineString);
3158 }
3159}
3160
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003161/// SynthMsgSendStretCallExpr - This routine translates message expression
3162/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3163/// nil check on receiver must be performed before calling objc_msgSend_stret.
3164/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3165/// msgSendType - function type of objc_msgSend_stret(...)
3166/// returnType - Result type of the method being synthesized.
3167/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3168/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3169/// starting with receiver.
3170/// Method - Method being rewritten.
3171Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3172 QualType msgSendType,
3173 QualType returnType,
3174 SmallVectorImpl<QualType> &ArgTypes,
3175 SmallVectorImpl<Expr*> &MsgExprs,
3176 ObjCMethodDecl *Method) {
3177 // Now do the "normal" pointer to function cast.
3178 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3179 Method ? Method->isVariadic() : false);
3180 castType = Context->getPointerType(castType);
3181
3182 // build type for containing the objc_msgSend_stret object.
3183 static unsigned stretCount=0;
3184 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003185 std::string str =
3186 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3187 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003188 str += " {\n\t";
3189 str += name;
3190 str += "(id receiver, SEL sel";
3191 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003192 std::string ArgName = "arg"; ArgName += utostr(i);
3193 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3194 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003195 }
3196 // could be vararg.
3197 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003198 std::string ArgName = "arg"; ArgName += utostr(i);
3199 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3200 Context->getPrintingPolicy());
3201 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003202 }
3203
3204 str += ") {\n";
3205 str += "\t if (receiver == 0)\n";
3206 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3207 str += "\t else\n";
3208 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3209 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3210 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3211 str += ", arg"; str += utostr(i);
3212 }
3213 // could be vararg.
3214 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3215 str += ", arg"; str += utostr(i);
3216 }
3217
3218 str += ");\n";
3219 str += "\t}\n";
3220 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3221 str += " s;\n";
3222 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003223 SourceLocation FunLocStart;
3224 if (CurFunctionDef)
3225 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3226 else {
3227 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3228 FunLocStart = CurMethodDef->getLocStart();
3229 }
3230
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003231 InsertText(FunLocStart, str);
3232 ++stretCount;
3233
3234 // AST for __Stretn(receiver, args).s;
3235 IdentifierInfo *ID = &Context->Idents.get(name);
3236 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003237 SourceLocation(), ID, castType, 0,
3238 SC_Extern, SC_None, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003239 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3240 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003241 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003242 castType, VK_LValue, SourceLocation());
3243
3244 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3245 SourceLocation(),
3246 &Context->Idents.get("s"),
3247 returnType, 0,
3248 /*BitWidth=*/0, /*Mutable=*/true,
3249 ICIS_NoInit);
3250 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3251 FieldD->getType(), VK_LValue,
3252 OK_Ordinary);
3253
3254 return ME;
3255}
3256
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003257Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3258 SourceLocation StartLoc,
3259 SourceLocation EndLoc) {
3260 if (!SelGetUidFunctionDecl)
3261 SynthSelGetUidFunctionDecl();
3262 if (!MsgSendFunctionDecl)
3263 SynthMsgSendFunctionDecl();
3264 if (!MsgSendSuperFunctionDecl)
3265 SynthMsgSendSuperFunctionDecl();
3266 if (!MsgSendStretFunctionDecl)
3267 SynthMsgSendStretFunctionDecl();
3268 if (!MsgSendSuperStretFunctionDecl)
3269 SynthMsgSendSuperStretFunctionDecl();
3270 if (!MsgSendFpretFunctionDecl)
3271 SynthMsgSendFpretFunctionDecl();
3272 if (!GetClassFunctionDecl)
3273 SynthGetClassFunctionDecl();
3274 if (!GetSuperClassFunctionDecl)
3275 SynthGetSuperClassFunctionDecl();
3276 if (!GetMetaClassFunctionDecl)
3277 SynthGetMetaClassFunctionDecl();
3278
3279 // default to objc_msgSend().
3280 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3281 // May need to use objc_msgSend_stret() as well.
3282 FunctionDecl *MsgSendStretFlavor = 0;
3283 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3284 QualType resultType = mDecl->getResultType();
3285 if (resultType->isRecordType())
3286 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3287 else if (resultType->isRealFloatingType())
3288 MsgSendFlavor = MsgSendFpretFunctionDecl;
3289 }
3290
3291 // Synthesize a call to objc_msgSend().
3292 SmallVector<Expr*, 8> MsgExprs;
3293 switch (Exp->getReceiverKind()) {
3294 case ObjCMessageExpr::SuperClass: {
3295 MsgSendFlavor = MsgSendSuperFunctionDecl;
3296 if (MsgSendStretFlavor)
3297 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3298 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3299
3300 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3301
3302 SmallVector<Expr*, 4> InitExprs;
3303
3304 // set the receiver to self, the first argument to all methods.
3305 InitExprs.push_back(
3306 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3307 CK_BitCast,
3308 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003309 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003310 Context->getObjCIdType(),
3311 VK_RValue,
3312 SourceLocation()))
3313 ); // set the 'receiver'.
3314
3315 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3316 SmallVector<Expr*, 8> ClsExprs;
3317 QualType argType = Context->getPointerType(Context->CharTy);
3318 ClsExprs.push_back(StringLiteral::Create(*Context,
3319 ClassDecl->getIdentifier()->getName(),
3320 StringLiteral::Ascii, false,
3321 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003322 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003323 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3324 &ClsExprs[0],
3325 ClsExprs.size(),
3326 StartLoc,
3327 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003328 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003329 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003330 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3331 &ClsExprs[0], ClsExprs.size(),
3332 StartLoc, EndLoc);
3333
3334 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3335 // To turn off a warning, type-cast to 'id'
3336 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3337 NoTypeInfoCStyleCastExpr(Context,
3338 Context->getObjCIdType(),
3339 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003340 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003341 QualType superType = getSuperStructType();
3342 Expr *SuperRep;
3343
3344 if (LangOpts.MicrosoftExt) {
3345 SynthSuperContructorFunctionDecl();
3346 // Simulate a contructor call...
3347 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003348 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003349 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003350 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003351 superType, VK_LValue,
3352 SourceLocation());
3353 // The code for super is a little tricky to prevent collision with
3354 // the structure definition in the header. The rewriter has it's own
3355 // internal definition (__rw_objc_super) that is uses. This is why
3356 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003357 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003358 //
3359 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3360 Context->getPointerType(SuperRep->getType()),
3361 VK_RValue, OK_Ordinary,
3362 SourceLocation());
3363 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3364 Context->getPointerType(superType),
3365 CK_BitCast, SuperRep);
3366 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003367 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003368 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003369 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003370 SourceLocation());
3371 TypeSourceInfo *superTInfo
3372 = Context->getTrivialTypeSourceInfo(superType);
3373 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3374 superType, VK_LValue,
3375 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003376 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003377 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3378 Context->getPointerType(SuperRep->getType()),
3379 VK_RValue, OK_Ordinary,
3380 SourceLocation());
3381 }
3382 MsgExprs.push_back(SuperRep);
3383 break;
3384 }
3385
3386 case ObjCMessageExpr::Class: {
3387 SmallVector<Expr*, 8> ClsExprs;
3388 QualType argType = Context->getPointerType(Context->CharTy);
3389 ObjCInterfaceDecl *Class
3390 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3391 IdentifierInfo *clsName = Class->getIdentifier();
3392 ClsExprs.push_back(StringLiteral::Create(*Context,
3393 clsName->getName(),
3394 StringLiteral::Ascii, false,
3395 argType, SourceLocation()));
3396 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3397 &ClsExprs[0],
3398 ClsExprs.size(),
3399 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003400 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3401 Context->getObjCIdType(),
3402 CK_BitCast, Cls);
3403 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003404 break;
3405 }
3406
3407 case ObjCMessageExpr::SuperInstance:{
3408 MsgSendFlavor = MsgSendSuperFunctionDecl;
3409 if (MsgSendStretFlavor)
3410 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3411 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3412 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3413 SmallVector<Expr*, 4> InitExprs;
3414
3415 InitExprs.push_back(
3416 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3417 CK_BitCast,
3418 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003419 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003420 Context->getObjCIdType(),
3421 VK_RValue, SourceLocation()))
3422 ); // set the 'receiver'.
3423
3424 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3425 SmallVector<Expr*, 8> ClsExprs;
3426 QualType argType = Context->getPointerType(Context->CharTy);
3427 ClsExprs.push_back(StringLiteral::Create(*Context,
3428 ClassDecl->getIdentifier()->getName(),
3429 StringLiteral::Ascii, false, argType,
3430 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003431 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003432 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3433 &ClsExprs[0],
3434 ClsExprs.size(),
3435 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003436 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003437 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003438 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3439 &ClsExprs[0], ClsExprs.size(),
3440 StartLoc, EndLoc);
3441
3442 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3443 // To turn off a warning, type-cast to 'id'
3444 InitExprs.push_back(
3445 // set 'super class', using class_getSuperclass().
3446 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3447 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003448 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003449 QualType superType = getSuperStructType();
3450 Expr *SuperRep;
3451
3452 if (LangOpts.MicrosoftExt) {
3453 SynthSuperContructorFunctionDecl();
3454 // Simulate a contructor call...
3455 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003456 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003457 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003458 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003459 superType, VK_LValue, SourceLocation());
3460 // The code for super is a little tricky to prevent collision with
3461 // the structure definition in the header. The rewriter has it's own
3462 // internal definition (__rw_objc_super) that is uses. This is why
3463 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003464 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003465 //
3466 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3467 Context->getPointerType(SuperRep->getType()),
3468 VK_RValue, OK_Ordinary,
3469 SourceLocation());
3470 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3471 Context->getPointerType(superType),
3472 CK_BitCast, SuperRep);
3473 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003474 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003475 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003476 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003477 SourceLocation());
3478 TypeSourceInfo *superTInfo
3479 = Context->getTrivialTypeSourceInfo(superType);
3480 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3481 superType, VK_RValue, ILE,
3482 false);
3483 }
3484 MsgExprs.push_back(SuperRep);
3485 break;
3486 }
3487
3488 case ObjCMessageExpr::Instance: {
3489 // Remove all type-casts because it may contain objc-style types; e.g.
3490 // Foo<Proto> *.
3491 Expr *recExpr = Exp->getInstanceReceiver();
3492 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3493 recExpr = CE->getSubExpr();
3494 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3495 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3496 ? CK_BlockPointerToObjCPointerCast
3497 : CK_CPointerToObjCPointerCast;
3498
3499 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3500 CK, recExpr);
3501 MsgExprs.push_back(recExpr);
3502 break;
3503 }
3504 }
3505
3506 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3507 SmallVector<Expr*, 8> SelExprs;
3508 QualType argType = Context->getPointerType(Context->CharTy);
3509 SelExprs.push_back(StringLiteral::Create(*Context,
3510 Exp->getSelector().getAsString(),
3511 StringLiteral::Ascii, false,
3512 argType, SourceLocation()));
3513 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3514 &SelExprs[0], SelExprs.size(),
3515 StartLoc,
3516 EndLoc);
3517 MsgExprs.push_back(SelExp);
3518
3519 // Now push any user supplied arguments.
3520 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3521 Expr *userExpr = Exp->getArg(i);
3522 // Make all implicit casts explicit...ICE comes in handy:-)
3523 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3524 // Reuse the ICE type, it is exactly what the doctor ordered.
3525 QualType type = ICE->getType();
3526 if (needToScanForQualifiers(type))
3527 type = Context->getObjCIdType();
3528 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3529 (void)convertBlockPointerToFunctionPointer(type);
3530 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3531 CastKind CK;
3532 if (SubExpr->getType()->isIntegralType(*Context) &&
3533 type->isBooleanType()) {
3534 CK = CK_IntegralToBoolean;
3535 } else if (type->isObjCObjectPointerType()) {
3536 if (SubExpr->getType()->isBlockPointerType()) {
3537 CK = CK_BlockPointerToObjCPointerCast;
3538 } else if (SubExpr->getType()->isPointerType()) {
3539 CK = CK_CPointerToObjCPointerCast;
3540 } else {
3541 CK = CK_BitCast;
3542 }
3543 } else {
3544 CK = CK_BitCast;
3545 }
3546
3547 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3548 }
3549 // Make id<P...> cast into an 'id' cast.
3550 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3551 if (CE->getType()->isObjCQualifiedIdType()) {
3552 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3553 userExpr = CE->getSubExpr();
3554 CastKind CK;
3555 if (userExpr->getType()->isIntegralType(*Context)) {
3556 CK = CK_IntegralToPointer;
3557 } else if (userExpr->getType()->isBlockPointerType()) {
3558 CK = CK_BlockPointerToObjCPointerCast;
3559 } else if (userExpr->getType()->isPointerType()) {
3560 CK = CK_CPointerToObjCPointerCast;
3561 } else {
3562 CK = CK_BitCast;
3563 }
3564 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3565 CK, userExpr);
3566 }
3567 }
3568 MsgExprs.push_back(userExpr);
3569 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3570 // out the argument in the original expression (since we aren't deleting
3571 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3572 //Exp->setArg(i, 0);
3573 }
3574 // Generate the funky cast.
3575 CastExpr *cast;
3576 SmallVector<QualType, 8> ArgTypes;
3577 QualType returnType;
3578
3579 // Push 'id' and 'SEL', the 2 implicit arguments.
3580 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3581 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3582 else
3583 ArgTypes.push_back(Context->getObjCIdType());
3584 ArgTypes.push_back(Context->getObjCSelType());
3585 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3586 // Push any user argument types.
3587 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3588 E = OMD->param_end(); PI != E; ++PI) {
3589 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3590 ? Context->getObjCIdType()
3591 : (*PI)->getType();
3592 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3593 (void)convertBlockPointerToFunctionPointer(t);
3594 ArgTypes.push_back(t);
3595 }
3596 returnType = Exp->getType();
3597 convertToUnqualifiedObjCType(returnType);
3598 (void)convertBlockPointerToFunctionPointer(returnType);
3599 } else {
3600 returnType = Context->getObjCIdType();
3601 }
3602 // Get the type, we will need to reference it in a couple spots.
3603 QualType msgSendType = MsgSendFlavor->getType();
3604
3605 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003606 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003607 VK_LValue, SourceLocation());
3608
3609 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3610 // If we don't do this cast, we get the following bizarre warning/note:
3611 // xx.m:13: warning: function called through a non-compatible type
3612 // xx.m:13: note: if this code is reached, the program will abort
3613 cast = NoTypeInfoCStyleCastExpr(Context,
3614 Context->getPointerType(Context->VoidTy),
3615 CK_BitCast, DRE);
3616
3617 // Now do the "normal" pointer to function cast.
3618 QualType castType =
3619 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3620 // If we don't have a method decl, force a variadic cast.
3621 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3622 castType = Context->getPointerType(castType);
3623 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3624 cast);
3625
3626 // Don't forget the parens to enforce the proper binding.
3627 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3628
3629 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003630 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3631 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003632 Stmt *ReplacingStmt = CE;
3633 if (MsgSendStretFlavor) {
3634 // We have the method which returns a struct/union. Must also generate
3635 // call to objc_msgSend_stret and hang both varieties on a conditional
3636 // expression which dictate which one to envoke depending on size of
3637 // method's return type.
3638
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003639 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3640 msgSendType, returnType,
3641 ArgTypes, MsgExprs,
3642 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003643
3644 // Build sizeof(returnType)
3645 UnaryExprOrTypeTraitExpr *sizeofExpr =
3646 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3647 Context->getTrivialTypeSourceInfo(returnType),
3648 Context->getSizeType(), SourceLocation(),
3649 SourceLocation());
3650 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3651 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3652 // For X86 it is more complicated and some kind of target specific routine
3653 // is needed to decide what to do.
3654 unsigned IntSize =
3655 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3656 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3657 llvm::APInt(IntSize, 8),
3658 Context->IntTy,
3659 SourceLocation());
3660 BinaryOperator *lessThanExpr =
3661 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003662 VK_RValue, OK_Ordinary, SourceLocation(),
3663 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003664 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3665 ConditionalOperator *CondExpr =
3666 new (Context) ConditionalOperator(lessThanExpr,
3667 SourceLocation(), CE,
3668 SourceLocation(), STCE,
3669 returnType, VK_RValue, OK_Ordinary);
3670 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3671 CondExpr);
3672 }
3673 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3674 return ReplacingStmt;
3675}
3676
3677Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3678 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3679 Exp->getLocEnd());
3680
3681 // Now do the actual rewrite.
3682 ReplaceStmt(Exp, ReplacingStmt);
3683
3684 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3685 return ReplacingStmt;
3686}
3687
3688// typedef struct objc_object Protocol;
3689QualType RewriteModernObjC::getProtocolType() {
3690 if (!ProtocolTypeDecl) {
3691 TypeSourceInfo *TInfo
3692 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3693 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3694 SourceLocation(), SourceLocation(),
3695 &Context->Idents.get("Protocol"),
3696 TInfo);
3697 }
3698 return Context->getTypeDeclType(ProtocolTypeDecl);
3699}
3700
3701/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3702/// a synthesized/forward data reference (to the protocol's metadata).
3703/// The forward references (and metadata) are generated in
3704/// RewriteModernObjC::HandleTranslationUnit().
3705Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003706 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3707 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003708 IdentifierInfo *ID = &Context->Idents.get(Name);
3709 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3710 SourceLocation(), ID, getProtocolType(), 0,
3711 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003712 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3713 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003714 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3715 Context->getPointerType(DRE->getType()),
3716 VK_RValue, OK_Ordinary, SourceLocation());
3717 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3718 CK_BitCast,
3719 DerefExpr);
3720 ReplaceStmt(Exp, castExpr);
3721 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3722 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3723 return castExpr;
3724
3725}
3726
3727bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3728 const char *endBuf) {
3729 while (startBuf < endBuf) {
3730 if (*startBuf == '#') {
3731 // Skip whitespace.
3732 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3733 ;
3734 if (!strncmp(startBuf, "if", strlen("if")) ||
3735 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3736 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3737 !strncmp(startBuf, "define", strlen("define")) ||
3738 !strncmp(startBuf, "undef", strlen("undef")) ||
3739 !strncmp(startBuf, "else", strlen("else")) ||
3740 !strncmp(startBuf, "elif", strlen("elif")) ||
3741 !strncmp(startBuf, "endif", strlen("endif")) ||
3742 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3743 !strncmp(startBuf, "include", strlen("include")) ||
3744 !strncmp(startBuf, "import", strlen("import")) ||
3745 !strncmp(startBuf, "include_next", strlen("include_next")))
3746 return true;
3747 }
3748 startBuf++;
3749 }
3750 return false;
3751}
3752
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003753/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3754/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003755bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003756 TagDecl *Tag,
3757 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003758 if (!IDecl)
3759 return false;
3760 SourceLocation TagLocation;
3761 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3762 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003763 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003764 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003765 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003766 TagLocation = RD->getLocation();
3767 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003768 IDecl->getLocation(), TagLocation);
3769 }
3770 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3771 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3772 return false;
3773 IsNamedDefinition = true;
3774 TagLocation = ED->getLocation();
3775 return Context->getSourceManager().isBeforeInTranslationUnit(
3776 IDecl->getLocation(), TagLocation);
3777
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003778 }
3779 return false;
3780}
3781
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003782/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003783/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003784bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3785 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003786 if (isa<TypedefType>(Type)) {
3787 Result += "\t";
3788 return false;
3789 }
3790
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003791 if (Type->isArrayType()) {
3792 QualType ElemTy = Context->getBaseElementType(Type);
3793 return RewriteObjCFieldDeclType(ElemTy, Result);
3794 }
3795 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003796 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3797 if (RD->isCompleteDefinition()) {
3798 if (RD->isStruct())
3799 Result += "\n\tstruct ";
3800 else if (RD->isUnion())
3801 Result += "\n\tunion ";
3802 else
3803 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003804
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003805 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003806 if (GlobalDefinedTags.count(RD)) {
3807 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003808 Result += " ";
3809 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003810 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003811 Result += " {\n";
3812 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003813 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003814 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003815 RewriteObjCFieldDecl(FD, Result);
3816 }
3817 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003818 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003819 }
3820 }
3821 else if (Type->isEnumeralType()) {
3822 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3823 if (ED->isCompleteDefinition()) {
3824 Result += "\n\tenum ";
3825 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003826 if (GlobalDefinedTags.count(ED)) {
3827 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003828 Result += " ";
3829 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003830 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003831
3832 Result += " {\n";
3833 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3834 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3835 Result += "\t"; Result += EC->getName(); Result += " = ";
3836 llvm::APSInt Val = EC->getInitVal();
3837 Result += Val.toString(10);
3838 Result += ",\n";
3839 }
3840 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003841 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003842 }
3843 }
3844
3845 Result += "\t";
3846 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003847 return false;
3848}
3849
3850
3851/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3852/// It handles elaborated types, as well as enum types in the process.
3853void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3854 std::string &Result) {
3855 QualType Type = fieldDecl->getType();
3856 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003857
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003858 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3859 if (!EleboratedType)
3860 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003861 Result += Name;
3862 if (fieldDecl->isBitField()) {
3863 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3864 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003865 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003866 const ArrayType *AT = Context->getAsArrayType(Type);
3867 do {
3868 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003869 Result += "[";
3870 llvm::APInt Dim = CAT->getSize();
3871 Result += utostr(Dim.getZExtValue());
3872 Result += "]";
3873 }
Eli Friedman6febf122012-12-13 01:43:21 +00003874 AT = Context->getAsArrayType(AT->getElementType());
3875 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003876 }
3877
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003878 Result += ";\n";
3879}
3880
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003881/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3882/// named aggregate types into the input buffer.
3883void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3884 std::string &Result) {
3885 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003886 if (isa<TypedefType>(Type))
3887 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003888 if (Type->isArrayType())
3889 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003890 ObjCContainerDecl *IDecl =
3891 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003892
3893 TagDecl *TD = 0;
3894 if (Type->isRecordType()) {
3895 TD = Type->getAs<RecordType>()->getDecl();
3896 }
3897 else if (Type->isEnumeralType()) {
3898 TD = Type->getAs<EnumType>()->getDecl();
3899 }
3900
3901 if (TD) {
3902 if (GlobalDefinedTags.count(TD))
3903 return;
3904
3905 bool IsNamedDefinition = false;
3906 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3907 RewriteObjCFieldDeclType(Type, Result);
3908 Result += ";";
3909 }
3910 if (IsNamedDefinition)
3911 GlobalDefinedTags.insert(TD);
3912 }
3913
3914}
3915
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003916unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3917 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3918 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3919 return IvarGroupNumber[IV];
3920 }
3921 unsigned GroupNo = 0;
3922 SmallVector<const ObjCIvarDecl *, 8> IVars;
3923 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3924 IVD; IVD = IVD->getNextIvar())
3925 IVars.push_back(IVD);
3926
3927 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3928 if (IVars[i]->isBitField()) {
3929 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3930 while (i < e && IVars[i]->isBitField())
3931 IvarGroupNumber[IVars[i++]] = GroupNo;
3932 if (i < e)
3933 --i;
3934 }
3935
3936 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3937 return IvarGroupNumber[IV];
3938}
3939
3940QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3941 ObjCIvarDecl *IV,
3942 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3943 std::string StructTagName;
3944 ObjCIvarBitfieldGroupType(IV, StructTagName);
3945 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3946 Context->getTranslationUnitDecl(),
3947 SourceLocation(), SourceLocation(),
3948 &Context->Idents.get(StructTagName));
3949 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3950 ObjCIvarDecl *Ivar = IVars[i];
3951 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3952 &Context->Idents.get(Ivar->getName()),
3953 Ivar->getType(),
3954 0, /*Expr *BW */Ivar->getBitWidth(), false,
3955 ICIS_NoInit));
3956 }
3957 RD->completeDefinition();
3958 return Context->getTagDeclType(RD);
3959}
3960
3961QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3962 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3963 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3964 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3965 if (GroupRecordType.count(tuple))
3966 return GroupRecordType[tuple];
3967
3968 SmallVector<ObjCIvarDecl *, 8> IVars;
3969 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3970 IVD; IVD = IVD->getNextIvar()) {
3971 if (IVD->isBitField())
3972 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3973 else {
3974 if (!IVars.empty()) {
3975 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3976 // Generate the struct type for this group of bitfield ivars.
3977 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3978 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3979 IVars.clear();
3980 }
3981 }
3982 }
3983 if (!IVars.empty()) {
3984 // Do the last one.
3985 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3986 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3987 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3988 }
3989 QualType RetQT = GroupRecordType[tuple];
3990 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3991
3992 return RetQT;
3993}
3994
3995/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3996/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3997void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3998 std::string &Result) {
3999 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4000 Result += CDecl->getName();
4001 Result += "__GRBF_";
4002 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4003 Result += utostr(GroupNo);
4004 return;
4005}
4006
4007/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4008/// Name of the struct would be: classname__T_n where n is the group number for
4009/// this ivar.
4010void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4011 std::string &Result) {
4012 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4013 Result += CDecl->getName();
4014 Result += "__T_";
4015 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4016 Result += utostr(GroupNo);
4017 return;
4018}
4019
4020/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4021/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4022/// this ivar.
4023void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4024 std::string &Result) {
4025 Result += "OBJC_IVAR_$_";
4026 ObjCIvarBitfieldGroupDecl(IV, Result);
4027}
4028
4029#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4030 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4031 ++IX; \
4032 if (IX < ENDIX) \
4033 --IX; \
4034}
4035
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004036/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4037/// an objective-c class with ivars.
4038void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4039 std::string &Result) {
4040 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4041 assert(CDecl->getName() != "" &&
4042 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004043 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004044 SmallVector<ObjCIvarDecl *, 8> IVars;
4045 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004046 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004047 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004048
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004049 SourceLocation LocStart = CDecl->getLocStart();
4050 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004051
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004052 const char *startBuf = SM->getCharacterData(LocStart);
4053 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004054
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004055 // If no ivars and no root or if its root, directly or indirectly,
4056 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004057 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004058 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4059 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4060 ReplaceText(LocStart, endBuf-startBuf, Result);
4061 return;
4062 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004063
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004064 // Insert named struct/union definitions inside class to
4065 // outer scope. This follows semantics of locally defined
4066 // struct/unions in objective-c classes.
4067 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4068 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004069
4070 // Insert named structs which are syntheized to group ivar bitfields
4071 // to outer scope as well.
4072 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4073 if (IVars[i]->isBitField()) {
4074 ObjCIvarDecl *IV = IVars[i];
4075 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4076 RewriteObjCFieldDeclType(QT, Result);
4077 Result += ";";
4078 // skip over ivar bitfields in this group.
4079 SKIP_BITFIELDS(i , e, IVars);
4080 }
4081
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004082 Result += "\nstruct ";
4083 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004084 Result += "_IMPL {\n";
4085
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004086 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004087 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4088 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4089 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004090 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004091
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004092 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4093 if (IVars[i]->isBitField()) {
4094 ObjCIvarDecl *IV = IVars[i];
4095 Result += "\tstruct ";
4096 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4097 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4098 // skip over ivar bitfields in this group.
4099 SKIP_BITFIELDS(i , e, IVars);
4100 }
4101 else
4102 RewriteObjCFieldDecl(IVars[i], Result);
4103 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004104
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004105 Result += "};\n";
4106 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4107 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004108 // Mark this struct as having been generated.
4109 if (!ObjCSynthesizedStructs.insert(CDecl))
4110 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004111}
4112
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004113/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4114/// have been referenced in an ivar access expression.
4115void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4116 std::string &Result) {
4117 // write out ivar offset symbols which have been referenced in an ivar
4118 // access expression.
4119 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4120 if (Ivars.empty())
4121 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004122
4123 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004124 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4125 e = Ivars.end(); i != e; i++) {
4126 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004127 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4128 unsigned GroupNo = 0;
4129 if (IvarDecl->isBitField()) {
4130 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4131 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4132 continue;
4133 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004134 Result += "\n";
4135 if (LangOpts.MicrosoftExt)
4136 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004137 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004138 if (LangOpts.MicrosoftExt &&
4139 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004140 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4141 Result += "__declspec(dllimport) ";
4142
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004143 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004144 if (IvarDecl->isBitField()) {
4145 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4146 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4147 }
4148 else
4149 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004150 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004151 }
4152}
4153
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004154//===----------------------------------------------------------------------===//
4155// Meta Data Emission
4156//===----------------------------------------------------------------------===//
4157
4158
4159/// RewriteImplementations - This routine rewrites all method implementations
4160/// and emits meta-data.
4161
4162void RewriteModernObjC::RewriteImplementations() {
4163 int ClsDefCount = ClassImplementation.size();
4164 int CatDefCount = CategoryImplementation.size();
4165
4166 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004167 for (int i = 0; i < ClsDefCount; i++) {
4168 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4169 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4170 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004171 assert(false &&
4172 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004173 RewriteImplementationDecl(OIMP);
4174 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004175
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004176 for (int i = 0; i < CatDefCount; i++) {
4177 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4178 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4179 if (CDecl->isImplicitInterfaceDecl())
4180 assert(false &&
4181 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004182 RewriteImplementationDecl(CIMP);
4183 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004184}
4185
4186void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4187 const std::string &Name,
4188 ValueDecl *VD, bool def) {
4189 assert(BlockByRefDeclNo.count(VD) &&
4190 "RewriteByRefString: ByRef decl missing");
4191 if (def)
4192 ResultStr += "struct ";
4193 ResultStr += "__Block_byref_" + Name +
4194 "_" + utostr(BlockByRefDeclNo[VD]) ;
4195}
4196
4197static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4198 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4199 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4200 return false;
4201}
4202
4203std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4204 StringRef funcName,
4205 std::string Tag) {
4206 const FunctionType *AFT = CE->getFunctionType();
4207 QualType RT = AFT->getResultType();
4208 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004209 SourceLocation BlockLoc = CE->getExprLoc();
4210 std::string S;
4211 ConvertSourceLocationToLineDirective(BlockLoc, S);
4212
4213 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4214 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004215
4216 BlockDecl *BD = CE->getBlockDecl();
4217
4218 if (isa<FunctionNoProtoType>(AFT)) {
4219 // No user-supplied arguments. Still need to pass in a pointer to the
4220 // block (to reference imported block decl refs).
4221 S += "(" + StructRef + " *__cself)";
4222 } else if (BD->param_empty()) {
4223 S += "(" + StructRef + " *__cself)";
4224 } else {
4225 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4226 assert(FT && "SynthesizeBlockFunc: No function proto");
4227 S += '(';
4228 // first add the implicit argument.
4229 S += StructRef + " *__cself, ";
4230 std::string ParamStr;
4231 for (BlockDecl::param_iterator AI = BD->param_begin(),
4232 E = BD->param_end(); AI != E; ++AI) {
4233 if (AI != BD->param_begin()) S += ", ";
4234 ParamStr = (*AI)->getNameAsString();
4235 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004236 (void)convertBlockPointerToFunctionPointer(QT);
4237 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004238 S += ParamStr;
4239 }
4240 if (FT->isVariadic()) {
4241 if (!BD->param_empty()) S += ", ";
4242 S += "...";
4243 }
4244 S += ')';
4245 }
4246 S += " {\n";
4247
4248 // Create local declarations to avoid rewriting all closure decl ref exprs.
4249 // First, emit a declaration for all "by ref" decls.
4250 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4251 E = BlockByRefDecls.end(); I != E; ++I) {
4252 S += " ";
4253 std::string Name = (*I)->getNameAsString();
4254 std::string TypeString;
4255 RewriteByRefString(TypeString, Name, (*I));
4256 TypeString += " *";
4257 Name = TypeString + Name;
4258 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4259 }
4260 // Next, emit a declaration for all "by copy" declarations.
4261 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4262 E = BlockByCopyDecls.end(); I != E; ++I) {
4263 S += " ";
4264 // Handle nested closure invocation. For example:
4265 //
4266 // void (^myImportedClosure)(void);
4267 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4268 //
4269 // void (^anotherClosure)(void);
4270 // anotherClosure = ^(void) {
4271 // myImportedClosure(); // import and invoke the closure
4272 // };
4273 //
4274 if (isTopLevelBlockPointerType((*I)->getType())) {
4275 RewriteBlockPointerTypeVariable(S, (*I));
4276 S += " = (";
4277 RewriteBlockPointerType(S, (*I)->getType());
4278 S += ")";
4279 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4280 }
4281 else {
4282 std::string Name = (*I)->getNameAsString();
4283 QualType QT = (*I)->getType();
4284 if (HasLocalVariableExternalStorage(*I))
4285 QT = Context->getPointerType(QT);
4286 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4287 S += Name + " = __cself->" +
4288 (*I)->getNameAsString() + "; // bound by copy\n";
4289 }
4290 }
4291 std::string RewrittenStr = RewrittenBlockExprs[CE];
4292 const char *cstr = RewrittenStr.c_str();
4293 while (*cstr++ != '{') ;
4294 S += cstr;
4295 S += "\n";
4296 return S;
4297}
4298
4299std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4300 StringRef funcName,
4301 std::string Tag) {
4302 std::string StructRef = "struct " + Tag;
4303 std::string S = "static void __";
4304
4305 S += funcName;
4306 S += "_block_copy_" + utostr(i);
4307 S += "(" + StructRef;
4308 S += "*dst, " + StructRef;
4309 S += "*src) {";
4310 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4311 E = ImportedBlockDecls.end(); I != E; ++I) {
4312 ValueDecl *VD = (*I);
4313 S += "_Block_object_assign((void*)&dst->";
4314 S += (*I)->getNameAsString();
4315 S += ", (void*)src->";
4316 S += (*I)->getNameAsString();
4317 if (BlockByRefDeclsPtrSet.count((*I)))
4318 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4319 else if (VD->getType()->isBlockPointerType())
4320 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4321 else
4322 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4323 }
4324 S += "}\n";
4325
4326 S += "\nstatic void __";
4327 S += funcName;
4328 S += "_block_dispose_" + utostr(i);
4329 S += "(" + StructRef;
4330 S += "*src) {";
4331 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4332 E = ImportedBlockDecls.end(); I != E; ++I) {
4333 ValueDecl *VD = (*I);
4334 S += "_Block_object_dispose((void*)src->";
4335 S += (*I)->getNameAsString();
4336 if (BlockByRefDeclsPtrSet.count((*I)))
4337 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4338 else if (VD->getType()->isBlockPointerType())
4339 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4340 else
4341 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4342 }
4343 S += "}\n";
4344 return S;
4345}
4346
4347std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4348 std::string Desc) {
4349 std::string S = "\nstruct " + Tag;
4350 std::string Constructor = " " + Tag;
4351
4352 S += " {\n struct __block_impl impl;\n";
4353 S += " struct " + Desc;
4354 S += "* Desc;\n";
4355
4356 Constructor += "(void *fp, "; // Invoke function pointer.
4357 Constructor += "struct " + Desc; // Descriptor pointer.
4358 Constructor += " *desc";
4359
4360 if (BlockDeclRefs.size()) {
4361 // Output all "by copy" declarations.
4362 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4363 E = BlockByCopyDecls.end(); I != E; ++I) {
4364 S += " ";
4365 std::string FieldName = (*I)->getNameAsString();
4366 std::string ArgName = "_" + FieldName;
4367 // Handle nested closure invocation. For example:
4368 //
4369 // void (^myImportedBlock)(void);
4370 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4371 //
4372 // void (^anotherBlock)(void);
4373 // anotherBlock = ^(void) {
4374 // myImportedBlock(); // import and invoke the closure
4375 // };
4376 //
4377 if (isTopLevelBlockPointerType((*I)->getType())) {
4378 S += "struct __block_impl *";
4379 Constructor += ", void *" + ArgName;
4380 } else {
4381 QualType QT = (*I)->getType();
4382 if (HasLocalVariableExternalStorage(*I))
4383 QT = Context->getPointerType(QT);
4384 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4385 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4386 Constructor += ", " + ArgName;
4387 }
4388 S += FieldName + ";\n";
4389 }
4390 // Output all "by ref" declarations.
4391 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4392 E = BlockByRefDecls.end(); I != E; ++I) {
4393 S += " ";
4394 std::string FieldName = (*I)->getNameAsString();
4395 std::string ArgName = "_" + FieldName;
4396 {
4397 std::string TypeString;
4398 RewriteByRefString(TypeString, FieldName, (*I));
4399 TypeString += " *";
4400 FieldName = TypeString + FieldName;
4401 ArgName = TypeString + ArgName;
4402 Constructor += ", " + ArgName;
4403 }
4404 S += FieldName + "; // by ref\n";
4405 }
4406 // Finish writing the constructor.
4407 Constructor += ", int flags=0)";
4408 // Initialize all "by copy" arguments.
4409 bool firsTime = true;
4410 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4411 E = BlockByCopyDecls.end(); I != E; ++I) {
4412 std::string Name = (*I)->getNameAsString();
4413 if (firsTime) {
4414 Constructor += " : ";
4415 firsTime = false;
4416 }
4417 else
4418 Constructor += ", ";
4419 if (isTopLevelBlockPointerType((*I)->getType()))
4420 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4421 else
4422 Constructor += Name + "(_" + Name + ")";
4423 }
4424 // Initialize all "by ref" arguments.
4425 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4426 E = BlockByRefDecls.end(); I != E; ++I) {
4427 std::string Name = (*I)->getNameAsString();
4428 if (firsTime) {
4429 Constructor += " : ";
4430 firsTime = false;
4431 }
4432 else
4433 Constructor += ", ";
4434 Constructor += Name + "(_" + Name + "->__forwarding)";
4435 }
4436
4437 Constructor += " {\n";
4438 if (GlobalVarDecl)
4439 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4440 else
4441 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4442 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4443
4444 Constructor += " Desc = desc;\n";
4445 } else {
4446 // Finish writing the constructor.
4447 Constructor += ", int flags=0) {\n";
4448 if (GlobalVarDecl)
4449 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4450 else
4451 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4452 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4453 Constructor += " Desc = desc;\n";
4454 }
4455 Constructor += " ";
4456 Constructor += "}\n";
4457 S += Constructor;
4458 S += "};\n";
4459 return S;
4460}
4461
4462std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4463 std::string ImplTag, int i,
4464 StringRef FunName,
4465 unsigned hasCopy) {
4466 std::string S = "\nstatic struct " + DescTag;
4467
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004468 S += " {\n size_t reserved;\n";
4469 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004470 if (hasCopy) {
4471 S += " void (*copy)(struct ";
4472 S += ImplTag; S += "*, struct ";
4473 S += ImplTag; S += "*);\n";
4474
4475 S += " void (*dispose)(struct ";
4476 S += ImplTag; S += "*);\n";
4477 }
4478 S += "} ";
4479
4480 S += DescTag + "_DATA = { 0, sizeof(struct ";
4481 S += ImplTag + ")";
4482 if (hasCopy) {
4483 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4484 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4485 }
4486 S += "};\n";
4487 return S;
4488}
4489
4490void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4491 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004492 bool RewriteSC = (GlobalVarDecl &&
4493 !Blocks.empty() &&
4494 GlobalVarDecl->getStorageClass() == SC_Static &&
4495 GlobalVarDecl->getType().getCVRQualifiers());
4496 if (RewriteSC) {
4497 std::string SC(" void __");
4498 SC += GlobalVarDecl->getNameAsString();
4499 SC += "() {}";
4500 InsertText(FunLocStart, SC);
4501 }
4502
4503 // Insert closures that were part of the function.
4504 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4505 CollectBlockDeclRefInfo(Blocks[i]);
4506 // Need to copy-in the inner copied-in variables not actually used in this
4507 // block.
4508 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004509 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004510 ValueDecl *VD = Exp->getDecl();
4511 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004512 if (!VD->hasAttr<BlocksAttr>()) {
4513 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4514 BlockByCopyDeclsPtrSet.insert(VD);
4515 BlockByCopyDecls.push_back(VD);
4516 }
4517 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004518 }
John McCallf4b88a42012-03-10 09:33:50 +00004519
4520 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004521 BlockByRefDeclsPtrSet.insert(VD);
4522 BlockByRefDecls.push_back(VD);
4523 }
John McCallf4b88a42012-03-10 09:33:50 +00004524
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004525 // imported objects in the inner blocks not used in the outer
4526 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004527 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004528 VD->getType()->isBlockPointerType())
4529 ImportedBlockDecls.insert(VD);
4530 }
4531
4532 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4533 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4534
4535 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4536
4537 InsertText(FunLocStart, CI);
4538
4539 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4540
4541 InsertText(FunLocStart, CF);
4542
4543 if (ImportedBlockDecls.size()) {
4544 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4545 InsertText(FunLocStart, HF);
4546 }
4547 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4548 ImportedBlockDecls.size() > 0);
4549 InsertText(FunLocStart, BD);
4550
4551 BlockDeclRefs.clear();
4552 BlockByRefDecls.clear();
4553 BlockByRefDeclsPtrSet.clear();
4554 BlockByCopyDecls.clear();
4555 BlockByCopyDeclsPtrSet.clear();
4556 ImportedBlockDecls.clear();
4557 }
4558 if (RewriteSC) {
4559 // Must insert any 'const/volatile/static here. Since it has been
4560 // removed as result of rewriting of block literals.
4561 std::string SC;
4562 if (GlobalVarDecl->getStorageClass() == SC_Static)
4563 SC = "static ";
4564 if (GlobalVarDecl->getType().isConstQualified())
4565 SC += "const ";
4566 if (GlobalVarDecl->getType().isVolatileQualified())
4567 SC += "volatile ";
4568 if (GlobalVarDecl->getType().isRestrictQualified())
4569 SC += "restrict ";
4570 InsertText(FunLocStart, SC);
4571 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004572 if (GlobalConstructionExp) {
4573 // extra fancy dance for global literal expression.
4574
4575 // Always the latest block expression on the block stack.
4576 std::string Tag = "__";
4577 Tag += FunName;
4578 Tag += "_block_impl_";
4579 Tag += utostr(Blocks.size()-1);
4580 std::string globalBuf = "static ";
4581 globalBuf += Tag; globalBuf += " ";
4582 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004583
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004584 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004585 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004586 PrintingPolicy(LangOpts));
4587 globalBuf += constructorExprBuf.str();
4588 globalBuf += ";\n";
4589 InsertText(FunLocStart, globalBuf);
4590 GlobalConstructionExp = 0;
4591 }
4592
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004593 Blocks.clear();
4594 InnerDeclRefsCount.clear();
4595 InnerDeclRefs.clear();
4596 RewrittenBlockExprs.clear();
4597}
4598
4599void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004600 SourceLocation FunLocStart =
4601 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4602 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004603 StringRef FuncName = FD->getName();
4604
4605 SynthesizeBlockLiterals(FunLocStart, FuncName);
4606}
4607
4608static void BuildUniqueMethodName(std::string &Name,
4609 ObjCMethodDecl *MD) {
4610 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4611 Name = IFace->getName();
4612 Name += "__" + MD->getSelector().getAsString();
4613 // Convert colons to underscores.
4614 std::string::size_type loc = 0;
4615 while ((loc = Name.find(":", loc)) != std::string::npos)
4616 Name.replace(loc, 1, "_");
4617}
4618
4619void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4620 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4621 //SourceLocation FunLocStart = MD->getLocStart();
4622 SourceLocation FunLocStart = MD->getLocStart();
4623 std::string FuncName;
4624 BuildUniqueMethodName(FuncName, MD);
4625 SynthesizeBlockLiterals(FunLocStart, FuncName);
4626}
4627
4628void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4629 for (Stmt::child_range CI = S->children(); CI; ++CI)
4630 if (*CI) {
4631 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4632 GetBlockDeclRefExprs(CBE->getBody());
4633 else
4634 GetBlockDeclRefExprs(*CI);
4635 }
4636 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004637 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4638 if (DRE->refersToEnclosingLocal()) {
4639 // FIXME: Handle enums.
4640 if (!isa<FunctionDecl>(DRE->getDecl()))
4641 BlockDeclRefs.push_back(DRE);
4642 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4643 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004644 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004645 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004646
4647 return;
4648}
4649
4650void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004651 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004652 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4653 for (Stmt::child_range CI = S->children(); CI; ++CI)
4654 if (*CI) {
4655 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4656 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4657 GetInnerBlockDeclRefExprs(CBE->getBody(),
4658 InnerBlockDeclRefs,
4659 InnerContexts);
4660 }
4661 else
4662 GetInnerBlockDeclRefExprs(*CI,
4663 InnerBlockDeclRefs,
4664 InnerContexts);
4665
4666 }
4667 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004668 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4669 if (DRE->refersToEnclosingLocal()) {
4670 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4671 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4672 InnerBlockDeclRefs.push_back(DRE);
4673 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4674 if (Var->isFunctionOrMethodVarDecl())
4675 ImportedLocalExternalDecls.insert(Var);
4676 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004677 }
4678
4679 return;
4680}
4681
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004682/// convertObjCTypeToCStyleType - This routine converts such objc types
4683/// as qualified objects, and blocks to their closest c/c++ types that
4684/// it can. It returns true if input type was modified.
4685bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4686 QualType oldT = T;
4687 convertBlockPointerToFunctionPointer(T);
4688 if (T->isFunctionPointerType()) {
4689 QualType PointeeTy;
4690 if (const PointerType* PT = T->getAs<PointerType>()) {
4691 PointeeTy = PT->getPointeeType();
4692 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4693 T = convertFunctionTypeOfBlocks(FT);
4694 T = Context->getPointerType(T);
4695 }
4696 }
4697 }
4698
4699 convertToUnqualifiedObjCType(T);
4700 return T != oldT;
4701}
4702
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004703/// convertFunctionTypeOfBlocks - This routine converts a function type
4704/// whose result type may be a block pointer or whose argument type(s)
4705/// might be block pointers to an equivalent function type replacing
4706/// all block pointers to function pointers.
4707QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4708 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4709 // FTP will be null for closures that don't take arguments.
4710 // Generate a funky cast.
4711 SmallVector<QualType, 8> ArgTypes;
4712 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004713 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004714
4715 if (FTP) {
4716 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4717 E = FTP->arg_type_end(); I && (I != E); ++I) {
4718 QualType t = *I;
4719 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004720 if (convertObjCTypeToCStyleType(t))
4721 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004722 ArgTypes.push_back(t);
4723 }
4724 }
4725 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004726 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004727 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4728 else FuncType = QualType(FT, 0);
4729 return FuncType;
4730}
4731
4732Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4733 // Navigate to relevant type information.
4734 const BlockPointerType *CPT = 0;
4735
4736 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4737 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004738 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4739 CPT = MExpr->getType()->getAs<BlockPointerType>();
4740 }
4741 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4742 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4743 }
4744 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4745 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4746 else if (const ConditionalOperator *CEXPR =
4747 dyn_cast<ConditionalOperator>(BlockExp)) {
4748 Expr *LHSExp = CEXPR->getLHS();
4749 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4750 Expr *RHSExp = CEXPR->getRHS();
4751 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4752 Expr *CONDExp = CEXPR->getCond();
4753 ConditionalOperator *CondExpr =
4754 new (Context) ConditionalOperator(CONDExp,
4755 SourceLocation(), cast<Expr>(LHSStmt),
4756 SourceLocation(), cast<Expr>(RHSStmt),
4757 Exp->getType(), VK_RValue, OK_Ordinary);
4758 return CondExpr;
4759 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4760 CPT = IRE->getType()->getAs<BlockPointerType>();
4761 } else if (const PseudoObjectExpr *POE
4762 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4763 CPT = POE->getType()->castAs<BlockPointerType>();
4764 } else {
4765 assert(1 && "RewriteBlockClass: Bad type");
4766 }
4767 assert(CPT && "RewriteBlockClass: Bad type");
4768 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4769 assert(FT && "RewriteBlockClass: Bad type");
4770 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4771 // FTP will be null for closures that don't take arguments.
4772
4773 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4774 SourceLocation(), SourceLocation(),
4775 &Context->Idents.get("__block_impl"));
4776 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4777
4778 // Generate a funky cast.
4779 SmallVector<QualType, 8> ArgTypes;
4780
4781 // Push the block argument type.
4782 ArgTypes.push_back(PtrBlock);
4783 if (FTP) {
4784 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4785 E = FTP->arg_type_end(); I && (I != E); ++I) {
4786 QualType t = *I;
4787 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4788 if (!convertBlockPointerToFunctionPointer(t))
4789 convertToUnqualifiedObjCType(t);
4790 ArgTypes.push_back(t);
4791 }
4792 }
4793 // Now do the pointer to function cast.
4794 QualType PtrToFuncCastType
4795 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4796
4797 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4798
4799 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4800 CK_BitCast,
4801 const_cast<Expr*>(BlockExp));
4802 // Don't forget the parens to enforce the proper binding.
4803 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4804 BlkCast);
4805 //PE->dump();
4806
4807 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4808 SourceLocation(),
4809 &Context->Idents.get("FuncPtr"),
4810 Context->VoidPtrTy, 0,
4811 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004812 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004813 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4814 FD->getType(), VK_LValue,
4815 OK_Ordinary);
4816
4817
4818 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4819 CK_BitCast, ME);
4820 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4821
4822 SmallVector<Expr*, 8> BlkExprs;
4823 // Add the implicit argument.
4824 BlkExprs.push_back(BlkCast);
4825 // Add the user arguments.
4826 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4827 E = Exp->arg_end(); I != E; ++I) {
4828 BlkExprs.push_back(*I);
4829 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004830 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004831 Exp->getType(), VK_RValue,
4832 SourceLocation());
4833 return CE;
4834}
4835
4836// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004837// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004838// For example:
4839//
4840// int main() {
4841// __block Foo *f;
4842// __block int i;
4843//
4844// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004845// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004846// i = 77;
4847// };
4848//}
John McCallf4b88a42012-03-10 09:33:50 +00004849Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004850 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4851 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004852 ValueDecl *VD = DeclRefExp->getDecl();
4853 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004854
4855 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4856 SourceLocation(),
4857 &Context->Idents.get("__forwarding"),
4858 Context->VoidPtrTy, 0,
4859 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004860 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004861 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4862 FD, SourceLocation(),
4863 FD->getType(), VK_LValue,
4864 OK_Ordinary);
4865
4866 StringRef Name = VD->getName();
4867 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4868 &Context->Idents.get(Name),
4869 Context->VoidPtrTy, 0,
4870 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004871 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004872 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4873 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4874
4875
4876
4877 // Need parens to enforce precedence.
4878 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4879 DeclRefExp->getExprLoc(),
4880 ME);
4881 ReplaceStmt(DeclRefExp, PE);
4882 return PE;
4883}
4884
4885// Rewrites the imported local variable V with external storage
4886// (static, extern, etc.) as *V
4887//
4888Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4889 ValueDecl *VD = DRE->getDecl();
4890 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4891 if (!ImportedLocalExternalDecls.count(Var))
4892 return DRE;
4893 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4894 VK_LValue, OK_Ordinary,
4895 DRE->getLocation());
4896 // Need parens to enforce precedence.
4897 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4898 Exp);
4899 ReplaceStmt(DRE, PE);
4900 return PE;
4901}
4902
4903void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4904 SourceLocation LocStart = CE->getLParenLoc();
4905 SourceLocation LocEnd = CE->getRParenLoc();
4906
4907 // Need to avoid trying to rewrite synthesized casts.
4908 if (LocStart.isInvalid())
4909 return;
4910 // Need to avoid trying to rewrite casts contained in macros.
4911 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4912 return;
4913
4914 const char *startBuf = SM->getCharacterData(LocStart);
4915 const char *endBuf = SM->getCharacterData(LocEnd);
4916 QualType QT = CE->getType();
4917 const Type* TypePtr = QT->getAs<Type>();
4918 if (isa<TypeOfExprType>(TypePtr)) {
4919 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4920 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4921 std::string TypeAsString = "(";
4922 RewriteBlockPointerType(TypeAsString, QT);
4923 TypeAsString += ")";
4924 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4925 return;
4926 }
4927 // advance the location to startArgList.
4928 const char *argPtr = startBuf;
4929
4930 while (*argPtr++ && (argPtr < endBuf)) {
4931 switch (*argPtr) {
4932 case '^':
4933 // Replace the '^' with '*'.
4934 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4935 ReplaceText(LocStart, 1, "*");
4936 break;
4937 }
4938 }
4939 return;
4940}
4941
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004942void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4943 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004944 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4945 CastKind != CK_AnyPointerToBlockPointerCast)
4946 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004947
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004948 QualType QT = IC->getType();
4949 (void)convertBlockPointerToFunctionPointer(QT);
4950 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4951 std::string Str = "(";
4952 Str += TypeString;
4953 Str += ")";
4954 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4955
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004956 return;
4957}
4958
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004959void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4960 SourceLocation DeclLoc = FD->getLocation();
4961 unsigned parenCount = 0;
4962
4963 // We have 1 or more arguments that have closure pointers.
4964 const char *startBuf = SM->getCharacterData(DeclLoc);
4965 const char *startArgList = strchr(startBuf, '(');
4966
4967 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4968
4969 parenCount++;
4970 // advance the location to startArgList.
4971 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4972 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4973
4974 const char *argPtr = startArgList;
4975
4976 while (*argPtr++ && parenCount) {
4977 switch (*argPtr) {
4978 case '^':
4979 // Replace the '^' with '*'.
4980 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4981 ReplaceText(DeclLoc, 1, "*");
4982 break;
4983 case '(':
4984 parenCount++;
4985 break;
4986 case ')':
4987 parenCount--;
4988 break;
4989 }
4990 }
4991 return;
4992}
4993
4994bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4995 const FunctionProtoType *FTP;
4996 const PointerType *PT = QT->getAs<PointerType>();
4997 if (PT) {
4998 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4999 } else {
5000 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5001 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5002 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5003 }
5004 if (FTP) {
5005 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5006 E = FTP->arg_type_end(); I != E; ++I)
5007 if (isTopLevelBlockPointerType(*I))
5008 return true;
5009 }
5010 return false;
5011}
5012
5013bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5014 const FunctionProtoType *FTP;
5015 const PointerType *PT = QT->getAs<PointerType>();
5016 if (PT) {
5017 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5018 } else {
5019 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5020 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5021 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5022 }
5023 if (FTP) {
5024 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5025 E = FTP->arg_type_end(); I != E; ++I) {
5026 if ((*I)->isObjCQualifiedIdType())
5027 return true;
5028 if ((*I)->isObjCObjectPointerType() &&
5029 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5030 return true;
5031 }
5032
5033 }
5034 return false;
5035}
5036
5037void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5038 const char *&RParen) {
5039 const char *argPtr = strchr(Name, '(');
5040 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5041
5042 LParen = argPtr; // output the start.
5043 argPtr++; // skip past the left paren.
5044 unsigned parenCount = 1;
5045
5046 while (*argPtr && parenCount) {
5047 switch (*argPtr) {
5048 case '(': parenCount++; break;
5049 case ')': parenCount--; break;
5050 default: break;
5051 }
5052 if (parenCount) argPtr++;
5053 }
5054 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5055 RParen = argPtr; // output the end
5056}
5057
5058void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5059 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5060 RewriteBlockPointerFunctionArgs(FD);
5061 return;
5062 }
5063 // Handle Variables and Typedefs.
5064 SourceLocation DeclLoc = ND->getLocation();
5065 QualType DeclT;
5066 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5067 DeclT = VD->getType();
5068 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5069 DeclT = TDD->getUnderlyingType();
5070 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5071 DeclT = FD->getType();
5072 else
5073 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5074
5075 const char *startBuf = SM->getCharacterData(DeclLoc);
5076 const char *endBuf = startBuf;
5077 // scan backward (from the decl location) for the end of the previous decl.
5078 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5079 startBuf--;
5080 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5081 std::string buf;
5082 unsigned OrigLength=0;
5083 // *startBuf != '^' if we are dealing with a pointer to function that
5084 // may take block argument types (which will be handled below).
5085 if (*startBuf == '^') {
5086 // Replace the '^' with '*', computing a negative offset.
5087 buf = '*';
5088 startBuf++;
5089 OrigLength++;
5090 }
5091 while (*startBuf != ')') {
5092 buf += *startBuf;
5093 startBuf++;
5094 OrigLength++;
5095 }
5096 buf += ')';
5097 OrigLength++;
5098
5099 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5100 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5101 // Replace the '^' with '*' for arguments.
5102 // Replace id<P> with id/*<>*/
5103 DeclLoc = ND->getLocation();
5104 startBuf = SM->getCharacterData(DeclLoc);
5105 const char *argListBegin, *argListEnd;
5106 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5107 while (argListBegin < argListEnd) {
5108 if (*argListBegin == '^')
5109 buf += '*';
5110 else if (*argListBegin == '<') {
5111 buf += "/*";
5112 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005113 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005114 while (*argListBegin != '>') {
5115 buf += *argListBegin++;
5116 OrigLength++;
5117 }
5118 buf += *argListBegin;
5119 buf += "*/";
5120 }
5121 else
5122 buf += *argListBegin;
5123 argListBegin++;
5124 OrigLength++;
5125 }
5126 buf += ')';
5127 OrigLength++;
5128 }
5129 ReplaceText(Start, OrigLength, buf);
5130
5131 return;
5132}
5133
5134
5135/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5136/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5137/// struct Block_byref_id_object *src) {
5138/// _Block_object_assign (&_dest->object, _src->object,
5139/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5140/// [|BLOCK_FIELD_IS_WEAK]) // object
5141/// _Block_object_assign(&_dest->object, _src->object,
5142/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5143/// [|BLOCK_FIELD_IS_WEAK]) // block
5144/// }
5145/// And:
5146/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5147/// _Block_object_dispose(_src->object,
5148/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5149/// [|BLOCK_FIELD_IS_WEAK]) // object
5150/// _Block_object_dispose(_src->object,
5151/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5152/// [|BLOCK_FIELD_IS_WEAK]) // block
5153/// }
5154
5155std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5156 int flag) {
5157 std::string S;
5158 if (CopyDestroyCache.count(flag))
5159 return S;
5160 CopyDestroyCache.insert(flag);
5161 S = "static void __Block_byref_id_object_copy_";
5162 S += utostr(flag);
5163 S += "(void *dst, void *src) {\n";
5164
5165 // offset into the object pointer is computed as:
5166 // void * + void* + int + int + void* + void *
5167 unsigned IntSize =
5168 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5169 unsigned VoidPtrSize =
5170 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5171
5172 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5173 S += " _Block_object_assign((char*)dst + ";
5174 S += utostr(offset);
5175 S += ", *(void * *) ((char*)src + ";
5176 S += utostr(offset);
5177 S += "), ";
5178 S += utostr(flag);
5179 S += ");\n}\n";
5180
5181 S += "static void __Block_byref_id_object_dispose_";
5182 S += utostr(flag);
5183 S += "(void *src) {\n";
5184 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5185 S += utostr(offset);
5186 S += "), ";
5187 S += utostr(flag);
5188 S += ");\n}\n";
5189 return S;
5190}
5191
5192/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5193/// the declaration into:
5194/// struct __Block_byref_ND {
5195/// void *__isa; // NULL for everything except __weak pointers
5196/// struct __Block_byref_ND *__forwarding;
5197/// int32_t __flags;
5198/// int32_t __size;
5199/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5200/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5201/// typex ND;
5202/// };
5203///
5204/// It then replaces declaration of ND variable with:
5205/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5206/// __size=sizeof(struct __Block_byref_ND),
5207/// ND=initializer-if-any};
5208///
5209///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005210void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5211 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005212 int flag = 0;
5213 int isa = 0;
5214 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5215 if (DeclLoc.isInvalid())
5216 // If type location is missing, it is because of missing type (a warning).
5217 // Use variable's location which is good for this case.
5218 DeclLoc = ND->getLocation();
5219 const char *startBuf = SM->getCharacterData(DeclLoc);
5220 SourceLocation X = ND->getLocEnd();
5221 X = SM->getExpansionLoc(X);
5222 const char *endBuf = SM->getCharacterData(X);
5223 std::string Name(ND->getNameAsString());
5224 std::string ByrefType;
5225 RewriteByRefString(ByrefType, Name, ND, true);
5226 ByrefType += " {\n";
5227 ByrefType += " void *__isa;\n";
5228 RewriteByRefString(ByrefType, Name, ND);
5229 ByrefType += " *__forwarding;\n";
5230 ByrefType += " int __flags;\n";
5231 ByrefType += " int __size;\n";
5232 // Add void *__Block_byref_id_object_copy;
5233 // void *__Block_byref_id_object_dispose; if needed.
5234 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005235 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005236 if (HasCopyAndDispose) {
5237 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5238 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5239 }
5240
5241 QualType T = Ty;
5242 (void)convertBlockPointerToFunctionPointer(T);
5243 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5244
5245 ByrefType += " " + Name + ";\n";
5246 ByrefType += "};\n";
5247 // Insert this type in global scope. It is needed by helper function.
5248 SourceLocation FunLocStart;
5249 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005250 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005251 else {
5252 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5253 FunLocStart = CurMethodDef->getLocStart();
5254 }
5255 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005256
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005257 if (Ty.isObjCGCWeak()) {
5258 flag |= BLOCK_FIELD_IS_WEAK;
5259 isa = 1;
5260 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005261 if (HasCopyAndDispose) {
5262 flag = BLOCK_BYREF_CALLER;
5263 QualType Ty = ND->getType();
5264 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5265 if (Ty->isBlockPointerType())
5266 flag |= BLOCK_FIELD_IS_BLOCK;
5267 else
5268 flag |= BLOCK_FIELD_IS_OBJECT;
5269 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5270 if (!HF.empty())
5271 InsertText(FunLocStart, HF);
5272 }
5273
5274 // struct __Block_byref_ND ND =
5275 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5276 // initializer-if-any};
5277 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005278 // FIXME. rewriter does not support __block c++ objects which
5279 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005280 if (hasInit)
5281 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5282 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5283 if (CXXDecl && CXXDecl->isDefaultConstructor())
5284 hasInit = false;
5285 }
5286
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005287 unsigned flags = 0;
5288 if (HasCopyAndDispose)
5289 flags |= BLOCK_HAS_COPY_DISPOSE;
5290 Name = ND->getNameAsString();
5291 ByrefType.clear();
5292 RewriteByRefString(ByrefType, Name, ND);
5293 std::string ForwardingCastType("(");
5294 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005295 ByrefType += " " + Name + " = {(void*)";
5296 ByrefType += utostr(isa);
5297 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5298 ByrefType += utostr(flags);
5299 ByrefType += ", ";
5300 ByrefType += "sizeof(";
5301 RewriteByRefString(ByrefType, Name, ND);
5302 ByrefType += ")";
5303 if (HasCopyAndDispose) {
5304 ByrefType += ", __Block_byref_id_object_copy_";
5305 ByrefType += utostr(flag);
5306 ByrefType += ", __Block_byref_id_object_dispose_";
5307 ByrefType += utostr(flag);
5308 }
5309
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005310 if (!firstDecl) {
5311 // In multiple __block declarations, and for all but 1st declaration,
5312 // find location of the separating comma. This would be start location
5313 // where new text is to be inserted.
5314 DeclLoc = ND->getLocation();
5315 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5316 const char *commaBuf = startDeclBuf;
5317 while (*commaBuf != ',')
5318 commaBuf--;
5319 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5320 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5321 startBuf = commaBuf;
5322 }
5323
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005324 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005325 ByrefType += "};\n";
5326 unsigned nameSize = Name.size();
5327 // for block or function pointer declaration. Name is aleady
5328 // part of the declaration.
5329 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5330 nameSize = 1;
5331 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5332 }
5333 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005334 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005335 SourceLocation startLoc;
5336 Expr *E = ND->getInit();
5337 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5338 startLoc = ECE->getLParenLoc();
5339 else
5340 startLoc = E->getLocStart();
5341 startLoc = SM->getExpansionLoc(startLoc);
5342 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005343 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005344
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005345 const char separator = lastDecl ? ';' : ',';
5346 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5347 const char *separatorBuf = strchr(startInitializerBuf, separator);
5348 assert((*separatorBuf == separator) &&
5349 "RewriteByRefVar: can't find ';' or ','");
5350 SourceLocation separatorLoc =
5351 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5352
5353 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005354 }
5355 return;
5356}
5357
5358void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5359 // Add initializers for any closure decl refs.
5360 GetBlockDeclRefExprs(Exp->getBody());
5361 if (BlockDeclRefs.size()) {
5362 // Unique all "by copy" declarations.
5363 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005364 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005365 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5366 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5367 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5368 }
5369 }
5370 // Unique all "by ref" declarations.
5371 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005372 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005373 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5374 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5375 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5376 }
5377 }
5378 // Find any imported blocks...they will need special attention.
5379 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005380 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005381 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5382 BlockDeclRefs[i]->getType()->isBlockPointerType())
5383 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5384 }
5385}
5386
5387FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5388 IdentifierInfo *ID = &Context->Idents.get(name);
5389 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5390 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5391 SourceLocation(), ID, FType, 0, SC_Extern,
5392 SC_None, false, false);
5393}
5394
5395Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005396 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005397
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005398 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005399
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005400 Blocks.push_back(Exp);
5401
5402 CollectBlockDeclRefInfo(Exp);
5403
5404 // Add inner imported variables now used in current block.
5405 int countOfInnerDecls = 0;
5406 if (!InnerBlockDeclRefs.empty()) {
5407 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005408 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005409 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005410 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005411 // We need to save the copied-in variables in nested
5412 // blocks because it is needed at the end for some of the API generations.
5413 // See SynthesizeBlockLiterals routine.
5414 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5415 BlockDeclRefs.push_back(Exp);
5416 BlockByCopyDeclsPtrSet.insert(VD);
5417 BlockByCopyDecls.push_back(VD);
5418 }
John McCallf4b88a42012-03-10 09:33:50 +00005419 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005420 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5421 BlockDeclRefs.push_back(Exp);
5422 BlockByRefDeclsPtrSet.insert(VD);
5423 BlockByRefDecls.push_back(VD);
5424 }
5425 }
5426 // Find any imported blocks...they will need special attention.
5427 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005428 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005429 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5430 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5431 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5432 }
5433 InnerDeclRefsCount.push_back(countOfInnerDecls);
5434
5435 std::string FuncName;
5436
5437 if (CurFunctionDef)
5438 FuncName = CurFunctionDef->getNameAsString();
5439 else if (CurMethodDef)
5440 BuildUniqueMethodName(FuncName, CurMethodDef);
5441 else if (GlobalVarDecl)
5442 FuncName = std::string(GlobalVarDecl->getNameAsString());
5443
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005444 bool GlobalBlockExpr =
5445 block->getDeclContext()->getRedeclContext()->isFileContext();
5446
5447 if (GlobalBlockExpr && !GlobalVarDecl) {
5448 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5449 GlobalBlockExpr = false;
5450 }
5451
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005452 std::string BlockNumber = utostr(Blocks.size()-1);
5453
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005454 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5455
5456 // Get a pointer to the function type so we can cast appropriately.
5457 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5458 QualType FType = Context->getPointerType(BFT);
5459
5460 FunctionDecl *FD;
5461 Expr *NewRep;
5462
5463 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005464 std::string Tag;
5465
5466 if (GlobalBlockExpr)
5467 Tag = "__global_";
5468 else
5469 Tag = "__";
5470 Tag += FuncName + "_block_impl_" + BlockNumber;
5471
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005472 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005473 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005474 SourceLocation());
5475
5476 SmallVector<Expr*, 4> InitExprs;
5477
5478 // Initialize the block function.
5479 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005480 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5481 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005482 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5483 CK_BitCast, Arg);
5484 InitExprs.push_back(castExpr);
5485
5486 // Initialize the block descriptor.
5487 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5488
5489 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5490 SourceLocation(), SourceLocation(),
5491 &Context->Idents.get(DescData.c_str()),
5492 Context->VoidPtrTy, 0,
5493 SC_Static, SC_None);
5494 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005495 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005496 Context->VoidPtrTy,
5497 VK_LValue,
5498 SourceLocation()),
5499 UO_AddrOf,
5500 Context->getPointerType(Context->VoidPtrTy),
5501 VK_RValue, OK_Ordinary,
5502 SourceLocation());
5503 InitExprs.push_back(DescRefExpr);
5504
5505 // Add initializers for any closure decl refs.
5506 if (BlockDeclRefs.size()) {
5507 Expr *Exp;
5508 // Output all "by copy" declarations.
5509 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5510 E = BlockByCopyDecls.end(); I != E; ++I) {
5511 if (isObjCType((*I)->getType())) {
5512 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5513 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005514 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5515 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005516 if (HasLocalVariableExternalStorage(*I)) {
5517 QualType QT = (*I)->getType();
5518 QT = Context->getPointerType(QT);
5519 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5520 OK_Ordinary, SourceLocation());
5521 }
5522 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5523 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005524 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5525 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005526 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5527 CK_BitCast, Arg);
5528 } else {
5529 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005530 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5531 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005532 if (HasLocalVariableExternalStorage(*I)) {
5533 QualType QT = (*I)->getType();
5534 QT = Context->getPointerType(QT);
5535 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5536 OK_Ordinary, SourceLocation());
5537 }
5538
5539 }
5540 InitExprs.push_back(Exp);
5541 }
5542 // Output all "by ref" declarations.
5543 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5544 E = BlockByRefDecls.end(); I != E; ++I) {
5545 ValueDecl *ND = (*I);
5546 std::string Name(ND->getNameAsString());
5547 std::string RecName;
5548 RewriteByRefString(RecName, Name, ND, true);
5549 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5550 + sizeof("struct"));
5551 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5552 SourceLocation(), SourceLocation(),
5553 II);
5554 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5555 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5556
5557 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005558 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005559 SourceLocation());
5560 bool isNestedCapturedVar = false;
5561 if (block)
5562 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5563 ce = block->capture_end(); ci != ce; ++ci) {
5564 const VarDecl *variable = ci->getVariable();
5565 if (variable == ND && ci->isNested()) {
5566 assert (ci->isByRef() &&
5567 "SynthBlockInitExpr - captured block variable is not byref");
5568 isNestedCapturedVar = true;
5569 break;
5570 }
5571 }
5572 // captured nested byref variable has its address passed. Do not take
5573 // its address again.
5574 if (!isNestedCapturedVar)
5575 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5576 Context->getPointerType(Exp->getType()),
5577 VK_RValue, OK_Ordinary, SourceLocation());
5578 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5579 InitExprs.push_back(Exp);
5580 }
5581 }
5582 if (ImportedBlockDecls.size()) {
5583 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5584 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5585 unsigned IntSize =
5586 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5587 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5588 Context->IntTy, SourceLocation());
5589 InitExprs.push_back(FlagExp);
5590 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005591 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005592 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005593
5594 if (GlobalBlockExpr) {
5595 assert (GlobalConstructionExp == 0 &&
5596 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5597 GlobalConstructionExp = NewRep;
5598 NewRep = DRE;
5599 }
5600
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005601 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5602 Context->getPointerType(NewRep->getType()),
5603 VK_RValue, OK_Ordinary, SourceLocation());
5604 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5605 NewRep);
5606 BlockDeclRefs.clear();
5607 BlockByRefDecls.clear();
5608 BlockByRefDeclsPtrSet.clear();
5609 BlockByCopyDecls.clear();
5610 BlockByCopyDeclsPtrSet.clear();
5611 ImportedBlockDecls.clear();
5612 return NewRep;
5613}
5614
5615bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5616 if (const ObjCForCollectionStmt * CS =
5617 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5618 return CS->getElement() == DS;
5619 return false;
5620}
5621
5622//===----------------------------------------------------------------------===//
5623// Function Body / Expression rewriting
5624//===----------------------------------------------------------------------===//
5625
5626Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5627 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5628 isa<DoStmt>(S) || isa<ForStmt>(S))
5629 Stmts.push_back(S);
5630 else if (isa<ObjCForCollectionStmt>(S)) {
5631 Stmts.push_back(S);
5632 ObjCBcLabelNo.push_back(++BcLabelCount);
5633 }
5634
5635 // Pseudo-object operations and ivar references need special
5636 // treatment because we're going to recursively rewrite them.
5637 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5638 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5639 return RewritePropertyOrImplicitSetter(PseudoOp);
5640 } else {
5641 return RewritePropertyOrImplicitGetter(PseudoOp);
5642 }
5643 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5644 return RewriteObjCIvarRefExpr(IvarRefExpr);
5645 }
5646
5647 SourceRange OrigStmtRange = S->getSourceRange();
5648
5649 // Perform a bottom up rewrite of all children.
5650 for (Stmt::child_range CI = S->children(); CI; ++CI)
5651 if (*CI) {
5652 Stmt *childStmt = (*CI);
5653 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5654 if (newStmt) {
5655 *CI = newStmt;
5656 }
5657 }
5658
5659 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005660 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005661 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5662 InnerContexts.insert(BE->getBlockDecl());
5663 ImportedLocalExternalDecls.clear();
5664 GetInnerBlockDeclRefExprs(BE->getBody(),
5665 InnerBlockDeclRefs, InnerContexts);
5666 // Rewrite the block body in place.
5667 Stmt *SaveCurrentBody = CurrentBody;
5668 CurrentBody = BE->getBody();
5669 PropParentMap = 0;
5670 // block literal on rhs of a property-dot-sytax assignment
5671 // must be replaced by its synthesize ast so getRewrittenText
5672 // works as expected. In this case, what actually ends up on RHS
5673 // is the blockTranscribed which is the helper function for the
5674 // block literal; as in: self.c = ^() {[ace ARR];};
5675 bool saveDisableReplaceStmt = DisableReplaceStmt;
5676 DisableReplaceStmt = false;
5677 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5678 DisableReplaceStmt = saveDisableReplaceStmt;
5679 CurrentBody = SaveCurrentBody;
5680 PropParentMap = 0;
5681 ImportedLocalExternalDecls.clear();
5682 // Now we snarf the rewritten text and stash it away for later use.
5683 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5684 RewrittenBlockExprs[BE] = Str;
5685
5686 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5687
5688 //blockTranscribed->dump();
5689 ReplaceStmt(S, blockTranscribed);
5690 return blockTranscribed;
5691 }
5692 // Handle specific things.
5693 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5694 return RewriteAtEncode(AtEncode);
5695
5696 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5697 return RewriteAtSelector(AtSelector);
5698
5699 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5700 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005701
5702 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5703 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005704
Patrick Beardeb382ec2012-04-19 00:25:12 +00005705 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5706 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005707
5708 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5709 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005710
5711 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5712 dyn_cast<ObjCDictionaryLiteral>(S))
5713 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005714
5715 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5716#if 0
5717 // Before we rewrite it, put the original message expression in a comment.
5718 SourceLocation startLoc = MessExpr->getLocStart();
5719 SourceLocation endLoc = MessExpr->getLocEnd();
5720
5721 const char *startBuf = SM->getCharacterData(startLoc);
5722 const char *endBuf = SM->getCharacterData(endLoc);
5723
5724 std::string messString;
5725 messString += "// ";
5726 messString.append(startBuf, endBuf-startBuf+1);
5727 messString += "\n";
5728
5729 // FIXME: Missing definition of
5730 // InsertText(clang::SourceLocation, char const*, unsigned int).
5731 // InsertText(startLoc, messString.c_str(), messString.size());
5732 // Tried this, but it didn't work either...
5733 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5734#endif
5735 return RewriteMessageExpr(MessExpr);
5736 }
5737
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005738 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5739 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5740 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5741 }
5742
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005743 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5744 return RewriteObjCTryStmt(StmtTry);
5745
5746 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5747 return RewriteObjCSynchronizedStmt(StmtTry);
5748
5749 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5750 return RewriteObjCThrowStmt(StmtThrow);
5751
5752 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5753 return RewriteObjCProtocolExpr(ProtocolExp);
5754
5755 if (ObjCForCollectionStmt *StmtForCollection =
5756 dyn_cast<ObjCForCollectionStmt>(S))
5757 return RewriteObjCForCollectionStmt(StmtForCollection,
5758 OrigStmtRange.getEnd());
5759 if (BreakStmt *StmtBreakStmt =
5760 dyn_cast<BreakStmt>(S))
5761 return RewriteBreakStmt(StmtBreakStmt);
5762 if (ContinueStmt *StmtContinueStmt =
5763 dyn_cast<ContinueStmt>(S))
5764 return RewriteContinueStmt(StmtContinueStmt);
5765
5766 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5767 // and cast exprs.
5768 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5769 // FIXME: What we're doing here is modifying the type-specifier that
5770 // precedes the first Decl. In the future the DeclGroup should have
5771 // a separate type-specifier that we can rewrite.
5772 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5773 // the context of an ObjCForCollectionStmt. For example:
5774 // NSArray *someArray;
5775 // for (id <FooProtocol> index in someArray) ;
5776 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5777 // and it depends on the original text locations/positions.
5778 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5779 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5780
5781 // Blocks rewrite rules.
5782 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5783 DI != DE; ++DI) {
5784 Decl *SD = *DI;
5785 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5786 if (isTopLevelBlockPointerType(ND->getType()))
5787 RewriteBlockPointerDecl(ND);
5788 else if (ND->getType()->isFunctionPointerType())
5789 CheckFunctionPointerDecl(ND->getType(), ND);
5790 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5791 if (VD->hasAttr<BlocksAttr>()) {
5792 static unsigned uniqueByrefDeclCount = 0;
5793 assert(!BlockByRefDeclNo.count(ND) &&
5794 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5795 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005796 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005797 }
5798 else
5799 RewriteTypeOfDecl(VD);
5800 }
5801 }
5802 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5803 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5804 RewriteBlockPointerDecl(TD);
5805 else if (TD->getUnderlyingType()->isFunctionPointerType())
5806 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5807 }
5808 }
5809 }
5810
5811 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5812 RewriteObjCQualifiedInterfaceTypes(CE);
5813
5814 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5815 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5816 assert(!Stmts.empty() && "Statement stack is empty");
5817 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5818 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5819 && "Statement stack mismatch");
5820 Stmts.pop_back();
5821 }
5822 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005823 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5824 ValueDecl *VD = DRE->getDecl();
5825 if (VD->hasAttr<BlocksAttr>())
5826 return RewriteBlockDeclRefExpr(DRE);
5827 if (HasLocalVariableExternalStorage(VD))
5828 return RewriteLocalVariableExternalStorage(DRE);
5829 }
5830
5831 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5832 if (CE->getCallee()->getType()->isBlockPointerType()) {
5833 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5834 ReplaceStmt(S, BlockCall);
5835 return BlockCall;
5836 }
5837 }
5838 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5839 RewriteCastExpr(CE);
5840 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005841 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5842 RewriteImplicitCastObjCExpr(ICE);
5843 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005844#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005845
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005846 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5847 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5848 ICE->getSubExpr(),
5849 SourceLocation());
5850 // Get the new text.
5851 std::string SStr;
5852 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005853 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005854 const std::string &Str = Buf.str();
5855
5856 printf("CAST = %s\n", &Str[0]);
5857 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5858 delete S;
5859 return Replacement;
5860 }
5861#endif
5862 // Return this stmt unmodified.
5863 return S;
5864}
5865
5866void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5867 for (RecordDecl::field_iterator i = RD->field_begin(),
5868 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005869 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005870 if (isTopLevelBlockPointerType(FD->getType()))
5871 RewriteBlockPointerDecl(FD);
5872 if (FD->getType()->isObjCQualifiedIdType() ||
5873 FD->getType()->isObjCQualifiedInterfaceType())
5874 RewriteObjCQualifiedInterfaceTypes(FD);
5875 }
5876}
5877
5878/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5879/// main file of the input.
5880void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5881 switch (D->getKind()) {
5882 case Decl::Function: {
5883 FunctionDecl *FD = cast<FunctionDecl>(D);
5884 if (FD->isOverloadedOperator())
5885 return;
5886
5887 // Since function prototypes don't have ParmDecl's, we check the function
5888 // prototype. This enables us to rewrite function declarations and
5889 // definitions using the same code.
5890 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5891
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005892 if (!FD->isThisDeclarationADefinition())
5893 break;
5894
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005895 // FIXME: If this should support Obj-C++, support CXXTryStmt
5896 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5897 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005898 CurrentBody = Body;
5899 Body =
5900 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5901 FD->setBody(Body);
5902 CurrentBody = 0;
5903 if (PropParentMap) {
5904 delete PropParentMap;
5905 PropParentMap = 0;
5906 }
5907 // This synthesizes and inserts the block "impl" struct, invoke function,
5908 // and any copy/dispose helper functions.
5909 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005910 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005911 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005912 }
5913 break;
5914 }
5915 case Decl::ObjCMethod: {
5916 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5917 if (CompoundStmt *Body = MD->getCompoundBody()) {
5918 CurMethodDef = MD;
5919 CurrentBody = Body;
5920 Body =
5921 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5922 MD->setBody(Body);
5923 CurrentBody = 0;
5924 if (PropParentMap) {
5925 delete PropParentMap;
5926 PropParentMap = 0;
5927 }
5928 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005929 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005930 CurMethodDef = 0;
5931 }
5932 break;
5933 }
5934 case Decl::ObjCImplementation: {
5935 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5936 ClassImplementation.push_back(CI);
5937 break;
5938 }
5939 case Decl::ObjCCategoryImpl: {
5940 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5941 CategoryImplementation.push_back(CI);
5942 break;
5943 }
5944 case Decl::Var: {
5945 VarDecl *VD = cast<VarDecl>(D);
5946 RewriteObjCQualifiedInterfaceTypes(VD);
5947 if (isTopLevelBlockPointerType(VD->getType()))
5948 RewriteBlockPointerDecl(VD);
5949 else if (VD->getType()->isFunctionPointerType()) {
5950 CheckFunctionPointerDecl(VD->getType(), VD);
5951 if (VD->getInit()) {
5952 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5953 RewriteCastExpr(CE);
5954 }
5955 }
5956 } else if (VD->getType()->isRecordType()) {
5957 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5958 if (RD->isCompleteDefinition())
5959 RewriteRecordBody(RD);
5960 }
5961 if (VD->getInit()) {
5962 GlobalVarDecl = VD;
5963 CurrentBody = VD->getInit();
5964 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5965 CurrentBody = 0;
5966 if (PropParentMap) {
5967 delete PropParentMap;
5968 PropParentMap = 0;
5969 }
5970 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5971 GlobalVarDecl = 0;
5972
5973 // This is needed for blocks.
5974 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5975 RewriteCastExpr(CE);
5976 }
5977 }
5978 break;
5979 }
5980 case Decl::TypeAlias:
5981 case Decl::Typedef: {
5982 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5983 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5984 RewriteBlockPointerDecl(TD);
5985 else if (TD->getUnderlyingType()->isFunctionPointerType())
5986 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5987 }
5988 break;
5989 }
5990 case Decl::CXXRecord:
5991 case Decl::Record: {
5992 RecordDecl *RD = cast<RecordDecl>(D);
5993 if (RD->isCompleteDefinition())
5994 RewriteRecordBody(RD);
5995 break;
5996 }
5997 default:
5998 break;
5999 }
6000 // Nothing yet.
6001}
6002
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006003/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6004/// protocol reference symbols in the for of:
6005/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6006static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6007 ObjCProtocolDecl *PDecl,
6008 std::string &Result) {
6009 // Also output .objc_protorefs$B section and its meta-data.
6010 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006011 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006012 Result += "struct _protocol_t *";
6013 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6014 Result += PDecl->getNameAsString();
6015 Result += " = &";
6016 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6017 Result += ";\n";
6018}
6019
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006020void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6021 if (Diags.hasErrorOccurred())
6022 return;
6023
6024 RewriteInclude();
6025
6026 // Here's a great place to add any extra declarations that may be needed.
6027 // Write out meta data for each @protocol(<expr>).
6028 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006029 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006030 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006031 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6032 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006033
6034 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006035
6036 if (ClassImplementation.size() || CategoryImplementation.size())
6037 RewriteImplementations();
6038
Fariborz Jahanian57317782012-02-21 23:58:41 +00006039 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6040 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6041 // Write struct declaration for the class matching its ivar declarations.
6042 // Note that for modern abi, this is postponed until the end of TU
6043 // because class extensions and the implementation might declare their own
6044 // private ivars.
6045 RewriteInterfaceDecl(CDecl);
6046 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006047
6048 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6049 // we are done.
6050 if (const RewriteBuffer *RewriteBuf =
6051 Rewrite.getRewriteBufferFor(MainFileID)) {
6052 //printf("Changed:\n");
6053 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6054 } else {
6055 llvm::errs() << "No changes\n";
6056 }
6057
6058 if (ClassImplementation.size() || CategoryImplementation.size() ||
6059 ProtocolExprDecls.size()) {
6060 // Rewrite Objective-c meta data*
6061 std::string ResultStr;
6062 RewriteMetaDataIntoBuffer(ResultStr);
6063 // Emit metadata.
6064 *OutFile << ResultStr;
6065 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006066 // Emit ImageInfo;
6067 {
6068 std::string ResultStr;
6069 WriteImageInfo(ResultStr);
6070 *OutFile << ResultStr;
6071 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006072 OutFile->flush();
6073}
6074
6075void RewriteModernObjC::Initialize(ASTContext &context) {
6076 InitializeCommon(context);
6077
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006078 Preamble += "#ifndef __OBJC2__\n";
6079 Preamble += "#define __OBJC2__\n";
6080 Preamble += "#endif\n";
6081
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006082 // declaring objc_selector outside the parameter list removes a silly
6083 // scope related warning...
6084 if (IsHeader)
6085 Preamble = "#pragma once\n";
6086 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006087 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6088 Preamble += "\n\tstruct objc_object *superClass; ";
6089 // Add a constructor for creating temporary objects.
6090 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6091 Preamble += ": object(o), superClass(s) {} ";
6092 Preamble += "\n};\n";
6093
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006094 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006095 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006096 // These are currently generated.
6097 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006098 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006099 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006100 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6101 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006102 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006103 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006104 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6105 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006106 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006107
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006108 // These need be generated for performance. Currently they are not,
6109 // using API calls instead.
6110 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6111 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6112 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6113
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006114 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006115 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6116 Preamble += "typedef struct objc_object Protocol;\n";
6117 Preamble += "#define _REWRITER_typedef_Protocol\n";
6118 Preamble += "#endif\n";
6119 if (LangOpts.MicrosoftExt) {
6120 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6121 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006122 }
6123 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006124 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006125
6126 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6127 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6128 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6129 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6130 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6131
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006132 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006133 Preamble += "(const char *);\n";
6134 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6135 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006136 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006137 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006138 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006139 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006140 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6141 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006142 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
6143 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6144 Preamble += "struct __objcFastEnumerationState {\n\t";
6145 Preamble += "unsigned long state;\n\t";
6146 Preamble += "void **itemsPtr;\n\t";
6147 Preamble += "unsigned long *mutationsPtr;\n\t";
6148 Preamble += "unsigned long extra[5];\n};\n";
6149 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6150 Preamble += "#define __FASTENUMERATIONSTATE\n";
6151 Preamble += "#endif\n";
6152 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6153 Preamble += "struct __NSConstantStringImpl {\n";
6154 Preamble += " int *isa;\n";
6155 Preamble += " int flags;\n";
6156 Preamble += " char *str;\n";
6157 Preamble += " long length;\n";
6158 Preamble += "};\n";
6159 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6160 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6161 Preamble += "#else\n";
6162 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6163 Preamble += "#endif\n";
6164 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6165 Preamble += "#endif\n";
6166 // Blocks preamble.
6167 Preamble += "#ifndef BLOCK_IMPL\n";
6168 Preamble += "#define BLOCK_IMPL\n";
6169 Preamble += "struct __block_impl {\n";
6170 Preamble += " void *isa;\n";
6171 Preamble += " int Flags;\n";
6172 Preamble += " int Reserved;\n";
6173 Preamble += " void *FuncPtr;\n";
6174 Preamble += "};\n";
6175 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6176 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6177 Preamble += "extern \"C\" __declspec(dllexport) "
6178 "void _Block_object_assign(void *, const void *, const int);\n";
6179 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6180 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6181 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6182 Preamble += "#else\n";
6183 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6184 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6185 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6186 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6187 Preamble += "#endif\n";
6188 Preamble += "#endif\n";
6189 if (LangOpts.MicrosoftExt) {
6190 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6191 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6192 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6193 Preamble += "#define __attribute__(X)\n";
6194 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006195 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006196 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006197 Preamble += "#endif\n";
6198 Preamble += "#ifndef __block\n";
6199 Preamble += "#define __block\n";
6200 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006201 }
6202 else {
6203 Preamble += "#define __block\n";
6204 Preamble += "#define __weak\n";
6205 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006206
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006207 // Declarations required for modern objective-c array and dictionary literals.
6208 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006209 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006210 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006211 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006212 Preamble += "\tva_list marker;\n";
6213 Preamble += "\tva_start(marker, count);\n";
6214 Preamble += "\tarr = new void *[count];\n";
6215 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6216 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6217 Preamble += "\tva_end( marker );\n";
6218 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006219 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006220 Preamble += "\tdelete[] arr;\n";
6221 Preamble += " }\n";
6222 Preamble += "};\n";
6223
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006224 // Declaration required for implementation of @autoreleasepool statement.
6225 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6226 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6227 Preamble += "struct __AtAutoreleasePool {\n";
6228 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6229 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6230 Preamble += " void * atautoreleasepoolobj;\n";
6231 Preamble += "};\n";
6232
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006233 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6234 // as this avoids warning in any 64bit/32bit compilation model.
6235 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6236}
6237
6238/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6239/// ivar offset.
6240void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6241 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006242 Result += "__OFFSETOFIVAR__(struct ";
6243 Result += ivar->getContainingInterface()->getNameAsString();
6244 if (LangOpts.MicrosoftExt)
6245 Result += "_IMPL";
6246 Result += ", ";
6247 if (ivar->isBitField())
6248 ObjCIvarBitfieldGroupDecl(ivar, Result);
6249 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006250 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006251 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006252}
6253
6254/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6255/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006256/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006257/// char *attributes;
6258/// }
6259
6260/// struct _prop_list_t {
6261/// uint32_t entsize; // sizeof(struct _prop_t)
6262/// uint32_t count_of_properties;
6263/// struct _prop_t prop_list[count_of_properties];
6264/// }
6265
6266/// struct _protocol_t;
6267
6268/// struct _protocol_list_t {
6269/// long protocol_count; // Note, this is 32/64 bit
6270/// struct _protocol_t * protocol_list[protocol_count];
6271/// }
6272
6273/// struct _objc_method {
6274/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006275/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006276/// char *_imp;
6277/// }
6278
6279/// struct _method_list_t {
6280/// uint32_t entsize; // sizeof(struct _objc_method)
6281/// uint32_t method_count;
6282/// struct _objc_method method_list[method_count];
6283/// }
6284
6285/// struct _protocol_t {
6286/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006287/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006288/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006289/// const struct method_list_t *instance_methods;
6290/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006291/// const struct method_list_t *optionalInstanceMethods;
6292/// const struct method_list_t *optionalClassMethods;
6293/// const struct _prop_list_t * properties;
6294/// const uint32_t size; // sizeof(struct _protocol_t)
6295/// const uint32_t flags; // = 0
6296/// const char ** extendedMethodTypes;
6297/// }
6298
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006299/// struct _ivar_t {
6300/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006301/// const char *name;
6302/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006303/// uint32_t alignment;
6304/// uint32_t size;
6305/// }
6306
6307/// struct _ivar_list_t {
6308/// uint32 entsize; // sizeof(struct _ivar_t)
6309/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006310/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006311/// }
6312
6313/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006314/// uint32_t flags;
6315/// uint32_t instanceStart;
6316/// uint32_t instanceSize;
6317/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006318/// const uint8_t *ivarLayout;
6319/// const char *name;
6320/// const struct _method_list_t *baseMethods;
6321/// const struct _protocol_list_t *baseProtocols;
6322/// const struct _ivar_list_t *ivars;
6323/// const uint8_t *weakIvarLayout;
6324/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006325/// }
6326
6327/// struct _class_t {
6328/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006329/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006330/// void *cache;
6331/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006332/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006333/// }
6334
6335/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006336/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006337/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006338/// const struct _method_list_t *instance_methods;
6339/// const struct _method_list_t *class_methods;
6340/// const struct _protocol_list_t *protocols;
6341/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006342/// }
6343
6344/// MessageRefTy - LLVM for:
6345/// struct _message_ref_t {
6346/// IMP messenger;
6347/// SEL name;
6348/// };
6349
6350/// SuperMessageRefTy - LLVM for:
6351/// struct _super_message_ref_t {
6352/// SUPER_IMP messenger;
6353/// SEL name;
6354/// };
6355
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006356static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006357 static bool meta_data_declared = false;
6358 if (meta_data_declared)
6359 return;
6360
6361 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006362 Result += "\tconst char *name;\n";
6363 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006364 Result += "};\n";
6365
6366 Result += "\nstruct _protocol_t;\n";
6367
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006368 Result += "\nstruct _objc_method {\n";
6369 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006370 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006371 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006372 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006373
6374 Result += "\nstruct _protocol_t {\n";
6375 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006376 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006377 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006378 Result += "\tconst struct method_list_t *instance_methods;\n";
6379 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006380 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6381 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6382 Result += "\tconst struct _prop_list_t * properties;\n";
6383 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6384 Result += "\tconst unsigned int flags; // = 0\n";
6385 Result += "\tconst char ** extendedMethodTypes;\n";
6386 Result += "};\n";
6387
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006388 Result += "\nstruct _ivar_t {\n";
6389 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006390 Result += "\tconst char *name;\n";
6391 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006392 Result += "\tunsigned int alignment;\n";
6393 Result += "\tunsigned int size;\n";
6394 Result += "};\n";
6395
6396 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006397 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006398 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006399 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006400 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6401 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006402 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006403 Result += "\tconst unsigned char *ivarLayout;\n";
6404 Result += "\tconst char *name;\n";
6405 Result += "\tconst struct _method_list_t *baseMethods;\n";
6406 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6407 Result += "\tconst struct _ivar_list_t *ivars;\n";
6408 Result += "\tconst unsigned char *weakIvarLayout;\n";
6409 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006410 Result += "};\n";
6411
6412 Result += "\nstruct _class_t {\n";
6413 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006414 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006415 Result += "\tvoid *cache;\n";
6416 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006417 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006418 Result += "};\n";
6419
6420 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006421 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006422 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006423 Result += "\tconst struct _method_list_t *instance_methods;\n";
6424 Result += "\tconst struct _method_list_t *class_methods;\n";
6425 Result += "\tconst struct _protocol_list_t *protocols;\n";
6426 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006427 Result += "};\n";
6428
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006429 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006430 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006431 meta_data_declared = true;
6432}
6433
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006434static void Write_protocol_list_t_TypeDecl(std::string &Result,
6435 long super_protocol_count) {
6436 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6437 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6438 Result += "\tstruct _protocol_t *super_protocols[";
6439 Result += utostr(super_protocol_count); Result += "];\n";
6440 Result += "}";
6441}
6442
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006443static void Write_method_list_t_TypeDecl(std::string &Result,
6444 unsigned int method_count) {
6445 Result += "struct /*_method_list_t*/"; Result += " {\n";
6446 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6447 Result += "\tunsigned int method_count;\n";
6448 Result += "\tstruct _objc_method method_list[";
6449 Result += utostr(method_count); Result += "];\n";
6450 Result += "}";
6451}
6452
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006453static void Write__prop_list_t_TypeDecl(std::string &Result,
6454 unsigned int property_count) {
6455 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6456 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6457 Result += "\tunsigned int count_of_properties;\n";
6458 Result += "\tstruct _prop_t prop_list[";
6459 Result += utostr(property_count); Result += "];\n";
6460 Result += "}";
6461}
6462
Fariborz Jahanianae932952012-02-10 20:47:10 +00006463static void Write__ivar_list_t_TypeDecl(std::string &Result,
6464 unsigned int ivar_count) {
6465 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6466 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6467 Result += "\tunsigned int count;\n";
6468 Result += "\tstruct _ivar_t ivar_list[";
6469 Result += utostr(ivar_count); Result += "];\n";
6470 Result += "}";
6471}
6472
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006473static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6474 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6475 StringRef VarName,
6476 StringRef ProtocolName) {
6477 if (SuperProtocols.size() > 0) {
6478 Result += "\nstatic ";
6479 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6480 Result += " "; Result += VarName;
6481 Result += ProtocolName;
6482 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6483 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6484 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6485 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6486 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6487 Result += SuperPD->getNameAsString();
6488 if (i == e-1)
6489 Result += "\n};\n";
6490 else
6491 Result += ",\n";
6492 }
6493 }
6494}
6495
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006496static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6497 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006498 ArrayRef<ObjCMethodDecl *> Methods,
6499 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006500 StringRef TopLevelDeclName,
6501 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006502 if (Methods.size() > 0) {
6503 Result += "\nstatic ";
6504 Write_method_list_t_TypeDecl(Result, Methods.size());
6505 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006506 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006507 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6508 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6509 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6510 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6511 ObjCMethodDecl *MD = Methods[i];
6512 if (i == 0)
6513 Result += "\t{{(struct objc_selector *)\"";
6514 else
6515 Result += "\t{(struct objc_selector *)\"";
6516 Result += (MD)->getSelector().getAsString(); Result += "\"";
6517 Result += ", ";
6518 std::string MethodTypeString;
6519 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6520 Result += "\""; Result += MethodTypeString; Result += "\"";
6521 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006522 if (!MethodImpl)
6523 Result += "0";
6524 else {
6525 Result += "(void *)";
6526 Result += RewriteObj.MethodInternalNames[MD];
6527 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006528 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006529 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006530 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006531 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006532 }
6533 Result += "};\n";
6534 }
6535}
6536
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006537static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006538 ASTContext *Context, std::string &Result,
6539 ArrayRef<ObjCPropertyDecl *> Properties,
6540 const Decl *Container,
6541 StringRef VarName,
6542 StringRef ProtocolName) {
6543 if (Properties.size() > 0) {
6544 Result += "\nstatic ";
6545 Write__prop_list_t_TypeDecl(Result, Properties.size());
6546 Result += " "; Result += VarName;
6547 Result += ProtocolName;
6548 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6549 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6550 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6551 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6552 ObjCPropertyDecl *PropDecl = Properties[i];
6553 if (i == 0)
6554 Result += "\t{{\"";
6555 else
6556 Result += "\t{\"";
6557 Result += PropDecl->getName(); Result += "\",";
6558 std::string PropertyTypeString, QuotePropertyTypeString;
6559 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6560 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6561 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6562 if (i == e-1)
6563 Result += "}}\n";
6564 else
6565 Result += "},\n";
6566 }
6567 Result += "};\n";
6568 }
6569}
6570
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006571// Metadata flags
6572enum MetaDataDlags {
6573 CLS = 0x0,
6574 CLS_META = 0x1,
6575 CLS_ROOT = 0x2,
6576 OBJC2_CLS_HIDDEN = 0x10,
6577 CLS_EXCEPTION = 0x20,
6578
6579 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6580 CLS_HAS_IVAR_RELEASER = 0x40,
6581 /// class was compiled with -fobjc-arr
6582 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6583};
6584
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006585static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6586 unsigned int flags,
6587 const std::string &InstanceStart,
6588 const std::string &InstanceSize,
6589 ArrayRef<ObjCMethodDecl *>baseMethods,
6590 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6591 ArrayRef<ObjCIvarDecl *>ivars,
6592 ArrayRef<ObjCPropertyDecl *>Properties,
6593 StringRef VarName,
6594 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006595 Result += "\nstatic struct _class_ro_t ";
6596 Result += VarName; Result += ClassName;
6597 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6598 Result += "\t";
6599 Result += llvm::utostr(flags); Result += ", ";
6600 Result += InstanceStart; Result += ", ";
6601 Result += InstanceSize; Result += ", \n";
6602 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006603 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6604 if (Triple.getArch() == llvm::Triple::x86_64)
6605 // uint32_t const reserved; // only when building for 64bit targets
6606 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006607 // const uint8_t * const ivarLayout;
6608 Result += "0, \n\t";
6609 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006610 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006611 if (baseMethods.size() > 0) {
6612 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006613 if (metaclass)
6614 Result += "_OBJC_$_CLASS_METHODS_";
6615 else
6616 Result += "_OBJC_$_INSTANCE_METHODS_";
6617 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006618 Result += ",\n\t";
6619 }
6620 else
6621 Result += "0, \n\t";
6622
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006623 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006624 Result += "(const struct _objc_protocol_list *)&";
6625 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6626 Result += ",\n\t";
6627 }
6628 else
6629 Result += "0, \n\t";
6630
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006631 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006632 Result += "(const struct _ivar_list_t *)&";
6633 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6634 Result += ",\n\t";
6635 }
6636 else
6637 Result += "0, \n\t";
6638
6639 // weakIvarLayout
6640 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006641 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006642 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006643 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006644 Result += ",\n";
6645 }
6646 else
6647 Result += "0, \n";
6648
6649 Result += "};\n";
6650}
6651
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006652static void Write_class_t(ASTContext *Context, std::string &Result,
6653 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006654 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6655 bool rootClass = (!CDecl->getSuperClass());
6656 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006657
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006658 if (!rootClass) {
6659 // Find the Root class
6660 RootClass = CDecl->getSuperClass();
6661 while (RootClass->getSuperClass()) {
6662 RootClass = RootClass->getSuperClass();
6663 }
6664 }
6665
6666 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006667 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006668 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006669 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006670 if (CDecl->getImplementation())
6671 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006672 else
6673 Result += "__declspec(dllimport) ";
6674
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006675 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006676 Result += CDecl->getNameAsString();
6677 Result += ";\n";
6678 }
6679 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006680 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006681 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006682 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006683 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006684 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006685 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006686 else
6687 Result += "__declspec(dllimport) ";
6688
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006689 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006690 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006691 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006692 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006693
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006694 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006695 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006696 if (RootClass->getImplementation())
6697 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006698 else
6699 Result += "__declspec(dllimport) ";
6700
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006701 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006702 Result += VarName;
6703 Result += RootClass->getNameAsString();
6704 Result += ";\n";
6705 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006706 }
6707
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006708 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6709 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006710 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6711 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006712 if (metaclass) {
6713 if (!rootClass) {
6714 Result += "0, // &"; Result += VarName;
6715 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006716 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006717 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006718 Result += CDecl->getSuperClass()->getNameAsString();
6719 Result += ",\n\t";
6720 }
6721 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006722 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006723 Result += CDecl->getNameAsString();
6724 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006725 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006726 Result += ",\n\t";
6727 }
6728 }
6729 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006730 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006731 Result += CDecl->getNameAsString();
6732 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006733 if (!rootClass) {
6734 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006735 Result += CDecl->getSuperClass()->getNameAsString();
6736 Result += ",\n\t";
6737 }
6738 else
6739 Result += "0,\n\t";
6740 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006741 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6742 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6743 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006744 Result += "&_OBJC_METACLASS_RO_$_";
6745 else
6746 Result += "&_OBJC_CLASS_RO_$_";
6747 Result += CDecl->getNameAsString();
6748 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006749
6750 // Add static function to initialize some of the meta-data fields.
6751 // avoid doing it twice.
6752 if (metaclass)
6753 return;
6754
6755 const ObjCInterfaceDecl *SuperClass =
6756 rootClass ? CDecl : CDecl->getSuperClass();
6757
6758 Result += "static void OBJC_CLASS_SETUP_$_";
6759 Result += CDecl->getNameAsString();
6760 Result += "(void ) {\n";
6761 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6762 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006763 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006764
6765 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006766 Result += ".superclass = ";
6767 if (rootClass)
6768 Result += "&OBJC_CLASS_$_";
6769 else
6770 Result += "&OBJC_METACLASS_$_";
6771
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006772 Result += SuperClass->getNameAsString(); Result += ";\n";
6773
6774 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6775 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6776
6777 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6778 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6779 Result += CDecl->getNameAsString(); Result += ";\n";
6780
6781 if (!rootClass) {
6782 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6783 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6784 Result += SuperClass->getNameAsString(); Result += ";\n";
6785 }
6786
6787 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6788 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6789 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006790}
6791
Fariborz Jahanian61186122012-02-17 18:40:41 +00006792static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6793 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006794 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006795 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006796 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6797 ArrayRef<ObjCMethodDecl *> ClassMethods,
6798 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6799 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006800 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006801 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006802 // must declare an extern class object in case this class is not implemented
6803 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006804 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006805 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006806 if (ClassDecl->getImplementation())
6807 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006808 else
6809 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006810
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006811 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006812 Result += "OBJC_CLASS_$_"; Result += ClassName;
6813 Result += ";\n";
6814
Fariborz Jahanian61186122012-02-17 18:40:41 +00006815 Result += "\nstatic struct _category_t ";
6816 Result += "_OBJC_$_CATEGORY_";
6817 Result += ClassName; Result += "_$_"; Result += CatName;
6818 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6819 Result += "{\n";
6820 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006821 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006822 Result += ",\n";
6823 if (InstanceMethods.size() > 0) {
6824 Result += "\t(const struct _method_list_t *)&";
6825 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6826 Result += ClassName; Result += "_$_"; Result += CatName;
6827 Result += ",\n";
6828 }
6829 else
6830 Result += "\t0,\n";
6831
6832 if (ClassMethods.size() > 0) {
6833 Result += "\t(const struct _method_list_t *)&";
6834 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6835 Result += ClassName; Result += "_$_"; Result += CatName;
6836 Result += ",\n";
6837 }
6838 else
6839 Result += "\t0,\n";
6840
6841 if (RefedProtocols.size() > 0) {
6842 Result += "\t(const struct _protocol_list_t *)&";
6843 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6844 Result += ClassName; Result += "_$_"; Result += CatName;
6845 Result += ",\n";
6846 }
6847 else
6848 Result += "\t0,\n";
6849
6850 if (ClassProperties.size() > 0) {
6851 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6852 Result += ClassName; Result += "_$_"; Result += CatName;
6853 Result += ",\n";
6854 }
6855 else
6856 Result += "\t0,\n";
6857
6858 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006859
6860 // Add static function to initialize the class pointer in the category structure.
6861 Result += "static void OBJC_CATEGORY_SETUP_$_";
6862 Result += ClassDecl->getNameAsString();
6863 Result += "_$_";
6864 Result += CatName;
6865 Result += "(void ) {\n";
6866 Result += "\t_OBJC_$_CATEGORY_";
6867 Result += ClassDecl->getNameAsString();
6868 Result += "_$_";
6869 Result += CatName;
6870 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6871 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006872}
6873
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006874static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6875 ASTContext *Context, std::string &Result,
6876 ArrayRef<ObjCMethodDecl *> Methods,
6877 StringRef VarName,
6878 StringRef ProtocolName) {
6879 if (Methods.size() == 0)
6880 return;
6881
6882 Result += "\nstatic const char *";
6883 Result += VarName; Result += ProtocolName;
6884 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6885 Result += "{\n";
6886 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6887 ObjCMethodDecl *MD = Methods[i];
6888 std::string MethodTypeString, QuoteMethodTypeString;
6889 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6890 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6891 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6892 if (i == e-1)
6893 Result += "\n};\n";
6894 else {
6895 Result += ",\n";
6896 }
6897 }
6898}
6899
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006900static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6901 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006902 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006903 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006904 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006905 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6906 // this is what happens:
6907 /**
6908 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6909 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6910 Class->getVisibility() == HiddenVisibility)
6911 Visibility shoud be: HiddenVisibility;
6912 else
6913 Visibility shoud be: DefaultVisibility;
6914 */
6915
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006916 Result += "\n";
6917 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6918 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006919 if (Context->getLangOpts().MicrosoftExt)
6920 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6921
6922 if (!Context->getLangOpts().MicrosoftExt ||
6923 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006924 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006925 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006926 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006927 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006928 if (Ivars[i]->isBitField())
6929 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6930 else
6931 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006932 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6933 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006934 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6935 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006936 if (Ivars[i]->isBitField()) {
6937 // skip over rest of the ivar bitfields.
6938 SKIP_BITFIELDS(i , e, Ivars);
6939 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006940 }
6941}
6942
Fariborz Jahanianae932952012-02-10 20:47:10 +00006943static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6944 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006945 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006946 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006947 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006948 if (OriginalIvars.size() > 0) {
6949 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6950 SmallVector<ObjCIvarDecl *, 8> Ivars;
6951 // strip off all but the first ivar bitfield from each group of ivars.
6952 // Such ivars in the ivar list table will be replaced by their grouping struct
6953 // 'ivar'.
6954 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6955 if (OriginalIvars[i]->isBitField()) {
6956 Ivars.push_back(OriginalIvars[i]);
6957 // skip over rest of the ivar bitfields.
6958 SKIP_BITFIELDS(i , e, OriginalIvars);
6959 }
6960 else
6961 Ivars.push_back(OriginalIvars[i]);
6962 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006963
Fariborz Jahanianae932952012-02-10 20:47:10 +00006964 Result += "\nstatic ";
6965 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6966 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006967 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006968 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6969 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6970 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6971 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6972 ObjCIvarDecl *IvarDecl = Ivars[i];
6973 if (i == 0)
6974 Result += "\t{{";
6975 else
6976 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006977 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006978 if (Ivars[i]->isBitField())
6979 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6980 else
6981 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006982 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006983
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006984 Result += "\"";
6985 if (Ivars[i]->isBitField())
6986 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6987 else
6988 Result += IvarDecl->getName();
6989 Result += "\", ";
6990
6991 QualType IVQT = IvarDecl->getType();
6992 if (IvarDecl->isBitField())
6993 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6994
Fariborz Jahanianae932952012-02-10 20:47:10 +00006995 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006996 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006997 IvarDecl);
6998 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6999 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7000
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007001 // FIXME. this alignment represents the host alignment and need be changed to
7002 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007003 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007004 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007005 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007006 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007007 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007008 if (i == e-1)
7009 Result += "}}\n";
7010 else
7011 Result += "},\n";
7012 }
7013 Result += "};\n";
7014 }
7015}
7016
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007017/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007018void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7019 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007020
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007021 // Do not synthesize the protocol more than once.
7022 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7023 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007024 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007025
7026 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7027 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007028 // Must write out all protocol definitions in current qualifier list,
7029 // and in their nested qualifiers before writing out current definition.
7030 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7031 E = PDecl->protocol_end(); I != E; ++I)
7032 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007033
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007034 // Construct method lists.
7035 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7036 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7037 for (ObjCProtocolDecl::instmeth_iterator
7038 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7039 I != E; ++I) {
7040 ObjCMethodDecl *MD = *I;
7041 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7042 OptInstanceMethods.push_back(MD);
7043 } else {
7044 InstanceMethods.push_back(MD);
7045 }
7046 }
7047
7048 for (ObjCProtocolDecl::classmeth_iterator
7049 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7050 I != E; ++I) {
7051 ObjCMethodDecl *MD = *I;
7052 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7053 OptClassMethods.push_back(MD);
7054 } else {
7055 ClassMethods.push_back(MD);
7056 }
7057 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007058 std::vector<ObjCMethodDecl *> AllMethods;
7059 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7060 AllMethods.push_back(InstanceMethods[i]);
7061 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7062 AllMethods.push_back(ClassMethods[i]);
7063 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7064 AllMethods.push_back(OptInstanceMethods[i]);
7065 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7066 AllMethods.push_back(OptClassMethods[i]);
7067
7068 Write__extendedMethodTypes_initializer(*this, Context, Result,
7069 AllMethods,
7070 "_OBJC_PROTOCOL_METHOD_TYPES_",
7071 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007072 // Protocol's super protocol list
7073 std::vector<ObjCProtocolDecl *> SuperProtocols;
7074 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7075 E = PDecl->protocol_end(); I != E; ++I)
7076 SuperProtocols.push_back(*I);
7077
7078 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7079 "_OBJC_PROTOCOL_REFS_",
7080 PDecl->getNameAsString());
7081
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007082 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007083 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007084 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007085
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007086 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007087 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007088 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007089
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007090 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007091 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007092 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007093
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007094 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007095 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007096 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007097
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007098 // Protocol's property metadata.
7099 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7100 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7101 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007102 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007103
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007104 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007105 /* Container */0,
7106 "_OBJC_PROTOCOL_PROPERTIES_",
7107 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007108
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007109 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007110 Result += "\n";
7111 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007112 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007113 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007114 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007115 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7116 Result += "\t0,\n"; // id is; is null
7117 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007118 if (SuperProtocols.size() > 0) {
7119 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7120 Result += PDecl->getNameAsString(); Result += ",\n";
7121 }
7122 else
7123 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007124 if (InstanceMethods.size() > 0) {
7125 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7126 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007127 }
7128 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007129 Result += "\t0,\n";
7130
7131 if (ClassMethods.size() > 0) {
7132 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7133 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007134 }
7135 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007136 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007137
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007138 if (OptInstanceMethods.size() > 0) {
7139 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7140 Result += PDecl->getNameAsString(); Result += ",\n";
7141 }
7142 else
7143 Result += "\t0,\n";
7144
7145 if (OptClassMethods.size() > 0) {
7146 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7147 Result += PDecl->getNameAsString(); Result += ",\n";
7148 }
7149 else
7150 Result += "\t0,\n";
7151
7152 if (ProtocolProperties.size() > 0) {
7153 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7154 Result += PDecl->getNameAsString(); Result += ",\n";
7155 }
7156 else
7157 Result += "\t0,\n";
7158
7159 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7160 Result += "\t0,\n";
7161
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007162 if (AllMethods.size() > 0) {
7163 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7164 Result += PDecl->getNameAsString();
7165 Result += "\n};\n";
7166 }
7167 else
7168 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007169
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007170 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007171 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007172 Result += "struct _protocol_t *";
7173 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7174 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7175 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007176
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007177 // Mark this protocol as having been generated.
7178 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7179 llvm_unreachable("protocol already synthesized");
7180
7181}
7182
7183void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7184 const ObjCList<ObjCProtocolDecl> &Protocols,
7185 StringRef prefix, StringRef ClassName,
7186 std::string &Result) {
7187 if (Protocols.empty()) return;
7188
7189 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007190 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007191
7192 // Output the top lovel protocol meta-data for the class.
7193 /* struct _objc_protocol_list {
7194 struct _objc_protocol_list *next;
7195 int protocol_count;
7196 struct _objc_protocol *class_protocols[];
7197 }
7198 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007199 Result += "\n";
7200 if (LangOpts.MicrosoftExt)
7201 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7202 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007203 Result += "\tstruct _objc_protocol_list *next;\n";
7204 Result += "\tint protocol_count;\n";
7205 Result += "\tstruct _objc_protocol *class_protocols[";
7206 Result += utostr(Protocols.size());
7207 Result += "];\n} _OBJC_";
7208 Result += prefix;
7209 Result += "_PROTOCOLS_";
7210 Result += ClassName;
7211 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7212 "{\n\t0, ";
7213 Result += utostr(Protocols.size());
7214 Result += "\n";
7215
7216 Result += "\t,{&_OBJC_PROTOCOL_";
7217 Result += Protocols[0]->getNameAsString();
7218 Result += " \n";
7219
7220 for (unsigned i = 1; i != Protocols.size(); i++) {
7221 Result += "\t ,&_OBJC_PROTOCOL_";
7222 Result += Protocols[i]->getNameAsString();
7223 Result += "\n";
7224 }
7225 Result += "\t }\n};\n";
7226}
7227
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007228/// hasObjCExceptionAttribute - Return true if this class or any super
7229/// class has the __objc_exception__ attribute.
7230/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7231static bool hasObjCExceptionAttribute(ASTContext &Context,
7232 const ObjCInterfaceDecl *OID) {
7233 if (OID->hasAttr<ObjCExceptionAttr>())
7234 return true;
7235 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7236 return hasObjCExceptionAttribute(Context, Super);
7237 return false;
7238}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007239
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007240void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7241 std::string &Result) {
7242 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7243
7244 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007245 if (CDecl->isImplicitInterfaceDecl())
7246 assert(false &&
7247 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007248
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007249 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007250 SmallVector<ObjCIvarDecl *, 8> IVars;
7251
7252 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7253 IVD; IVD = IVD->getNextIvar()) {
7254 // Ignore unnamed bit-fields.
7255 if (!IVD->getDeclName())
7256 continue;
7257 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007258 }
7259
Fariborz Jahanianae932952012-02-10 20:47:10 +00007260 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007261 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007262 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007263
7264 // Build _objc_method_list for class's instance methods if needed
7265 SmallVector<ObjCMethodDecl *, 32>
7266 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7267
7268 // If any of our property implementations have associated getters or
7269 // setters, produce metadata for them as well.
7270 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7271 PropEnd = IDecl->propimpl_end();
7272 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007273 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007274 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007275 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007276 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007277 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007278 if (!PD)
7279 continue;
7280 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007281 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007282 InstanceMethods.push_back(Getter);
7283 if (PD->isReadOnly())
7284 continue;
7285 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007286 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007287 InstanceMethods.push_back(Setter);
7288 }
7289
7290 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7291 "_OBJC_$_INSTANCE_METHODS_",
7292 IDecl->getNameAsString(), true);
7293
7294 SmallVector<ObjCMethodDecl *, 32>
7295 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7296
7297 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7298 "_OBJC_$_CLASS_METHODS_",
7299 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007300
7301 // Protocols referenced in class declaration?
7302 // Protocol's super protocol list
7303 std::vector<ObjCProtocolDecl *> RefedProtocols;
7304 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7305 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7306 E = Protocols.end();
7307 I != E; ++I) {
7308 RefedProtocols.push_back(*I);
7309 // Must write out all protocol definitions in current qualifier list,
7310 // and in their nested qualifiers before writing out current definition.
7311 RewriteObjCProtocolMetaData(*I, Result);
7312 }
7313
7314 Write_protocol_list_initializer(Context, Result,
7315 RefedProtocols,
7316 "_OBJC_CLASS_PROTOCOLS_$_",
7317 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007318
7319 // Protocol's property metadata.
7320 std::vector<ObjCPropertyDecl *> ClassProperties;
7321 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7322 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007323 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007324
7325 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007326 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007327 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007328 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007329
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007330
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007331 // Data for initializing _class_ro_t metaclass meta-data
7332 uint32_t flags = CLS_META;
7333 std::string InstanceSize;
7334 std::string InstanceStart;
7335
7336
7337 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7338 if (classIsHidden)
7339 flags |= OBJC2_CLS_HIDDEN;
7340
7341 if (!CDecl->getSuperClass())
7342 // class is root
7343 flags |= CLS_ROOT;
7344 InstanceSize = "sizeof(struct _class_t)";
7345 InstanceStart = InstanceSize;
7346 Write__class_ro_t_initializer(Context, Result, flags,
7347 InstanceStart, InstanceSize,
7348 ClassMethods,
7349 0,
7350 0,
7351 0,
7352 "_OBJC_METACLASS_RO_$_",
7353 CDecl->getNameAsString());
7354
7355
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007356 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007357 flags = CLS;
7358 if (classIsHidden)
7359 flags |= OBJC2_CLS_HIDDEN;
7360
7361 if (hasObjCExceptionAttribute(*Context, CDecl))
7362 flags |= CLS_EXCEPTION;
7363
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007364 if (!CDecl->getSuperClass())
7365 // class is root
7366 flags |= CLS_ROOT;
7367
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007368 InstanceSize.clear();
7369 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007370 if (!ObjCSynthesizedStructs.count(CDecl)) {
7371 InstanceSize = "0";
7372 InstanceStart = "0";
7373 }
7374 else {
7375 InstanceSize = "sizeof(struct ";
7376 InstanceSize += CDecl->getNameAsString();
7377 InstanceSize += "_IMPL)";
7378
7379 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7380 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007381 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007382 }
7383 else
7384 InstanceStart = InstanceSize;
7385 }
7386 Write__class_ro_t_initializer(Context, Result, flags,
7387 InstanceStart, InstanceSize,
7388 InstanceMethods,
7389 RefedProtocols,
7390 IVars,
7391 ClassProperties,
7392 "_OBJC_CLASS_RO_$_",
7393 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007394
7395 Write_class_t(Context, Result,
7396 "OBJC_METACLASS_$_",
7397 CDecl, /*metaclass*/true);
7398
7399 Write_class_t(Context, Result,
7400 "OBJC_CLASS_$_",
7401 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007402
7403 if (ImplementationIsNonLazy(IDecl))
7404 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007405
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007406}
7407
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007408void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7409 int ClsDefCount = ClassImplementation.size();
7410 if (!ClsDefCount)
7411 return;
7412 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7413 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7414 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7415 for (int i = 0; i < ClsDefCount; i++) {
7416 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7417 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7418 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7419 Result += CDecl->getName(); Result += ",\n";
7420 }
7421 Result += "};\n";
7422}
7423
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007424void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7425 int ClsDefCount = ClassImplementation.size();
7426 int CatDefCount = CategoryImplementation.size();
7427
7428 // For each implemented class, write out all its meta data.
7429 for (int i = 0; i < ClsDefCount; i++)
7430 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7431
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007432 RewriteClassSetupInitHook(Result);
7433
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007434 // For each implemented category, write out all its meta data.
7435 for (int i = 0; i < CatDefCount; i++)
7436 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7437
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007438 RewriteCategorySetupInitHook(Result);
7439
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007440 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007441 if (LangOpts.MicrosoftExt)
7442 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007443 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7444 Result += llvm::utostr(ClsDefCount); Result += "]";
7445 Result +=
7446 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7447 "regular,no_dead_strip\")))= {\n";
7448 for (int i = 0; i < ClsDefCount; i++) {
7449 Result += "\t&OBJC_CLASS_$_";
7450 Result += ClassImplementation[i]->getNameAsString();
7451 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007452 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007453 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007454
7455 if (!DefinedNonLazyClasses.empty()) {
7456 if (LangOpts.MicrosoftExt)
7457 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7458 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7459 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7460 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7461 Result += ",\n";
7462 }
7463 Result += "};\n";
7464 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007465 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007466
7467 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007468 if (LangOpts.MicrosoftExt)
7469 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007470 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7471 Result += llvm::utostr(CatDefCount); Result += "]";
7472 Result +=
7473 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7474 "regular,no_dead_strip\")))= {\n";
7475 for (int i = 0; i < CatDefCount; i++) {
7476 Result += "\t&_OBJC_$_CATEGORY_";
7477 Result +=
7478 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7479 Result += "_$_";
7480 Result += CategoryImplementation[i]->getNameAsString();
7481 Result += ",\n";
7482 }
7483 Result += "};\n";
7484 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007485
7486 if (!DefinedNonLazyCategories.empty()) {
7487 if (LangOpts.MicrosoftExt)
7488 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7489 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7490 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7491 Result += "\t&_OBJC_$_CATEGORY_";
7492 Result +=
7493 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7494 Result += "_$_";
7495 Result += DefinedNonLazyCategories[i]->getNameAsString();
7496 Result += ",\n";
7497 }
7498 Result += "};\n";
7499 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007500}
7501
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007502void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7503 if (LangOpts.MicrosoftExt)
7504 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7505
7506 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7507 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007508 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007509}
7510
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007511/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7512/// implementation.
7513void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7514 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007515 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007516 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7517 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007518 ObjCCategoryDecl *CDecl
7519 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007520
7521 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007522 FullCategoryName += "_$_";
7523 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007524
7525 // Build _objc_method_list for class's instance methods if needed
7526 SmallVector<ObjCMethodDecl *, 32>
7527 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7528
7529 // If any of our property implementations have associated getters or
7530 // setters, produce metadata for them as well.
7531 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7532 PropEnd = IDecl->propimpl_end();
7533 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007534 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007535 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007536 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007537 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007538 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007539 if (!PD)
7540 continue;
7541 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7542 InstanceMethods.push_back(Getter);
7543 if (PD->isReadOnly())
7544 continue;
7545 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7546 InstanceMethods.push_back(Setter);
7547 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007548
Fariborz Jahanian61186122012-02-17 18:40:41 +00007549 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7550 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7551 FullCategoryName, true);
7552
7553 SmallVector<ObjCMethodDecl *, 32>
7554 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7555
7556 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7557 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7558 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007559
7560 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007561 // Protocol's super protocol list
7562 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007563 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7564 E = CDecl->protocol_end();
7565
7566 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007567 RefedProtocols.push_back(*I);
7568 // Must write out all protocol definitions in current qualifier list,
7569 // and in their nested qualifiers before writing out current definition.
7570 RewriteObjCProtocolMetaData(*I, Result);
7571 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007572
Fariborz Jahanian61186122012-02-17 18:40:41 +00007573 Write_protocol_list_initializer(Context, Result,
7574 RefedProtocols,
7575 "_OBJC_CATEGORY_PROTOCOLS_$_",
7576 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007577
Fariborz Jahanian61186122012-02-17 18:40:41 +00007578 // Protocol's property metadata.
7579 std::vector<ObjCPropertyDecl *> ClassProperties;
7580 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7581 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007582 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007583
Fariborz Jahanian61186122012-02-17 18:40:41 +00007584 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007585 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007586 "_OBJC_$_PROP_LIST_",
7587 FullCategoryName);
7588
7589 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007590 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007591 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007592 InstanceMethods,
7593 ClassMethods,
7594 RefedProtocols,
7595 ClassProperties);
7596
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007597 // Determine if this category is also "non-lazy".
7598 if (ImplementationIsNonLazy(IDecl))
7599 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007600
7601}
7602
7603void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7604 int CatDefCount = CategoryImplementation.size();
7605 if (!CatDefCount)
7606 return;
7607 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7608 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7609 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7610 for (int i = 0; i < CatDefCount; i++) {
7611 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7612 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7613 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7614 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7615 Result += ClassDecl->getName();
7616 Result += "_$_";
7617 Result += CatDecl->getName();
7618 Result += ",\n";
7619 }
7620 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007621}
7622
7623// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7624/// class methods.
7625template<typename MethodIterator>
7626void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7627 MethodIterator MethodEnd,
7628 bool IsInstanceMethod,
7629 StringRef prefix,
7630 StringRef ClassName,
7631 std::string &Result) {
7632 if (MethodBegin == MethodEnd) return;
7633
7634 if (!objc_impl_method) {
7635 /* struct _objc_method {
7636 SEL _cmd;
7637 char *method_types;
7638 void *_imp;
7639 }
7640 */
7641 Result += "\nstruct _objc_method {\n";
7642 Result += "\tSEL _cmd;\n";
7643 Result += "\tchar *method_types;\n";
7644 Result += "\tvoid *_imp;\n";
7645 Result += "};\n";
7646
7647 objc_impl_method = true;
7648 }
7649
7650 // Build _objc_method_list for class's methods if needed
7651
7652 /* struct {
7653 struct _objc_method_list *next_method;
7654 int method_count;
7655 struct _objc_method method_list[];
7656 }
7657 */
7658 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007659 Result += "\n";
7660 if (LangOpts.MicrosoftExt) {
7661 if (IsInstanceMethod)
7662 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7663 else
7664 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7665 }
7666 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007667 Result += "\tstruct _objc_method_list *next_method;\n";
7668 Result += "\tint method_count;\n";
7669 Result += "\tstruct _objc_method method_list[";
7670 Result += utostr(NumMethods);
7671 Result += "];\n} _OBJC_";
7672 Result += prefix;
7673 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7674 Result += "_METHODS_";
7675 Result += ClassName;
7676 Result += " __attribute__ ((used, section (\"__OBJC, __";
7677 Result += IsInstanceMethod ? "inst" : "cls";
7678 Result += "_meth\")))= ";
7679 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7680
7681 Result += "\t,{{(SEL)\"";
7682 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7683 std::string MethodTypeString;
7684 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7685 Result += "\", \"";
7686 Result += MethodTypeString;
7687 Result += "\", (void *)";
7688 Result += MethodInternalNames[*MethodBegin];
7689 Result += "}\n";
7690 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7691 Result += "\t ,{(SEL)\"";
7692 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7693 std::string MethodTypeString;
7694 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7695 Result += "\", \"";
7696 Result += MethodTypeString;
7697 Result += "\", (void *)";
7698 Result += MethodInternalNames[*MethodBegin];
7699 Result += "}\n";
7700 }
7701 Result += "\t }\n};\n";
7702}
7703
7704Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7705 SourceRange OldRange = IV->getSourceRange();
7706 Expr *BaseExpr = IV->getBase();
7707
7708 // Rewrite the base, but without actually doing replaces.
7709 {
7710 DisableReplaceStmtScope S(*this);
7711 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7712 IV->setBase(BaseExpr);
7713 }
7714
7715 ObjCIvarDecl *D = IV->getDecl();
7716
7717 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007718
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007719 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7720 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007721 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007722 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7723 // lookup which class implements the instance variable.
7724 ObjCInterfaceDecl *clsDeclared = 0;
7725 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7726 clsDeclared);
7727 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7728
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007729 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007730 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007731 if (D->isBitField())
7732 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7733 else
7734 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007735
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007736 ReferencedIvars[clsDeclared].insert(D);
7737
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007738 // cast offset to "char *".
7739 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7740 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007741 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007742 BaseExpr);
7743 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7744 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7745 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007746 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7747 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007748 SourceLocation());
7749 BinaryOperator *addExpr =
7750 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7751 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007752 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007753 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007754 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7755 SourceLocation(),
7756 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007757 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007758 if (D->isBitField())
7759 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007760
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007761 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007762 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007763 RD = RD->getDefinition();
7764 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007765 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007766 ObjCContainerDecl *CDecl =
7767 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7768 // ivar in class extensions requires special treatment.
7769 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7770 CDecl = CatDecl->getClassInterface();
7771 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007772 RecName += "_IMPL";
7773 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7774 SourceLocation(), SourceLocation(),
7775 &Context->Idents.get(RecName.c_str()));
7776 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7777 unsigned UnsignedIntSize =
7778 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7779 Expr *Zero = IntegerLiteral::Create(*Context,
7780 llvm::APInt(UnsignedIntSize, 0),
7781 Context->UnsignedIntTy, SourceLocation());
7782 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7783 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7784 Zero);
7785 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7786 SourceLocation(),
7787 &Context->Idents.get(D->getNameAsString()),
7788 IvarT, 0,
7789 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007790 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007791 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7792 FD->getType(), VK_LValue,
7793 OK_Ordinary);
7794 IvarT = Context->getDecltypeType(ME, ME->getType());
7795 }
7796 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007797 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007798 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007799
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007800 castExpr = NoTypeInfoCStyleCastExpr(Context,
7801 castT,
7802 CK_BitCast,
7803 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007804
7805
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007806 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007807 VK_LValue, OK_Ordinary,
7808 SourceLocation());
7809 PE = new (Context) ParenExpr(OldRange.getBegin(),
7810 OldRange.getEnd(),
7811 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007812
7813 if (D->isBitField()) {
7814 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7815 SourceLocation(),
7816 &Context->Idents.get(D->getNameAsString()),
7817 D->getType(), 0,
7818 /*BitWidth=*/D->getBitWidth(),
7819 /*Mutable=*/true,
7820 ICIS_NoInit);
7821 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7822 FD->getType(), VK_LValue,
7823 OK_Ordinary);
7824 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007825
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007826 }
7827 else
7828 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007829 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007830
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007831 ReplaceStmtWithRange(IV, Replacement, OldRange);
7832 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007833}