blob: a3a4afc6bbb3404d7ab6ac866d62a13d9521f466 [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;
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000157
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
166 bool objc_impl_method;
167
168 bool DisableReplaceStmt;
169 class DisableReplaceStmtScope {
170 RewriteModernObjC &R;
171 bool SavedValue;
172
173 public:
174 DisableReplaceStmtScope(RewriteModernObjC &R)
175 : R(R), SavedValue(R.DisableReplaceStmt) {
176 R.DisableReplaceStmt = true;
177 }
178 ~DisableReplaceStmtScope() {
179 R.DisableReplaceStmt = SavedValue;
180 }
181 };
182 void InitializeCommon(ASTContext &context);
183
184 public:
Fariborz Jahanian90af4e22012-02-14 17:19:02 +0000185 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000186 // Top Level Driver code.
187 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
188 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
189 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
190 if (!Class->isThisDeclarationADefinition()) {
191 RewriteForwardClassDecl(D);
192 break;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000193 } else {
194 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000195 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000196 break;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000197 }
198 }
199
200 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
201 if (!Proto->isThisDeclarationADefinition()) {
202 RewriteForwardProtocolDecl(D);
203 break;
204 }
205 }
206
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +0000207 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
208 // Under modern abi, we cannot translate body of the function
209 // yet until all class extensions and its implementation is seen.
210 // This is because they may introduce new bitfields which must go
211 // into their grouping struct.
212 if (FDecl->isThisDeclarationADefinition() &&
213 // Not c functions defined inside an objc container.
214 !FDecl->isTopLevelDeclInObjCContainer()) {
215 FunctionDefinitionsSeen.push_back(FDecl);
216 break;
217 }
218 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000219 HandleTopLevelSingleDecl(*I);
220 }
221 return true;
222 }
223 void HandleTopLevelSingleDecl(Decl *D);
224 void HandleDeclInMainFile(Decl *D);
225 RewriteModernObjC(std::string inFile, raw_ostream *OS,
226 DiagnosticsEngine &D, const LangOptions &LOpts,
227 bool silenceMacroWarn);
228
229 ~RewriteModernObjC() {}
230
231 virtual void HandleTranslationUnit(ASTContext &C);
232
233 void ReplaceStmt(Stmt *Old, Stmt *New) {
234 Stmt *ReplacingStmt = ReplacedNodes[Old];
235
236 if (ReplacingStmt)
237 return; // We can't rewrite the same node twice.
238
239 if (DisableReplaceStmt)
240 return;
241
242 // If replacement succeeded or warning disabled return with no warning.
243 if (!Rewrite.ReplaceStmt(Old, New)) {
244 ReplacedNodes[Old] = New;
245 return;
246 }
247 if (SilenceRewriteMacroWarning)
248 return;
249 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
250 << Old->getSourceRange();
251 }
252
253 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
254 if (DisableReplaceStmt)
255 return;
256
257 // Measure the old text.
258 int Size = Rewrite.getRangeSize(SrcRange);
259 if (Size == -1) {
260 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
261 << Old->getSourceRange();
262 return;
263 }
264 // Get the new text.
265 std::string SStr;
266 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000267 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000268 const std::string &Str = S.str();
269
270 // If replacement succeeded or warning disabled return with no warning.
271 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
272 ReplacedNodes[Old] = New;
273 return;
274 }
275 if (SilenceRewriteMacroWarning)
276 return;
277 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
278 << Old->getSourceRange();
279 }
280
281 void InsertText(SourceLocation Loc, StringRef Str,
282 bool InsertAfter = true) {
283 // If insertion succeeded or warning disabled return with no warning.
284 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
285 SilenceRewriteMacroWarning)
286 return;
287
288 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
289 }
290
291 void ReplaceText(SourceLocation Start, unsigned OrigLength,
292 StringRef Str) {
293 // If removal succeeded or warning disabled return with no warning.
294 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
295 SilenceRewriteMacroWarning)
296 return;
297
298 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
299 }
300
301 // Syntactic Rewriting.
302 void RewriteRecordBody(RecordDecl *RD);
303 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000304 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000305 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
306 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000307 void RewriteForwardClassDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000308 void RewriteForwardClassDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000309 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
310 const std::string &typedefString);
311 void RewriteImplementations();
312 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
313 ObjCImplementationDecl *IMD,
314 ObjCCategoryImplDecl *CID);
315 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
316 void RewriteImplementationDecl(Decl *Dcl);
317 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
318 ObjCMethodDecl *MDecl, std::string &ResultStr);
319 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
320 const FunctionType *&FPRetType);
321 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
322 ValueDecl *VD, bool def=false);
323 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
324 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
325 void RewriteForwardProtocolDecl(DeclGroupRef D);
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000326 void RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000327 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
328 void RewriteProperty(ObjCPropertyDecl *prop);
329 void RewriteFunctionDecl(FunctionDecl *FD);
330 void RewriteBlockPointerType(std::string& Str, QualType Type);
331 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000332 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000333 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
334 void RewriteTypeOfDecl(VarDecl *VD);
335 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000336
337 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000338
339 // Expression Rewriting.
340 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
341 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
342 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
343 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
344 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
345 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
346 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000347 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000348 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000349 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000350 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000351 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000352 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000353 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000354 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
355 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
356 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
357 SourceLocation OrigEnd);
358 Stmt *RewriteBreakStmt(BreakStmt *S);
359 Stmt *RewriteContinueStmt(ContinueStmt *S);
360 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000361 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000362 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000363
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000364 // Computes ivar bitfield group no.
365 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
366 // Names field decl. for ivar bitfield group.
367 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
368 // Names struct type for ivar bitfield group.
369 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
370 // Names symbol for ivar bitfield group field offset.
371 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
372 // Given an ivar bitfield, it builds (or finds) its group record type.
373 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
374 QualType SynthesizeBitfieldGroupStructType(
375 ObjCIvarDecl *IV,
376 SmallVectorImpl<ObjCIvarDecl *> &IVars);
377
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000378 // Block rewriting.
379 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
380
381 // Block specific rewrite rules.
382 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000383 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000384 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000385 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
386 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
387
388 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
389 std::string &Result);
390
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000391 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000392 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000393 bool &IsNamedDefinition);
394 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
395 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000396
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000397 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
398
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000399 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
400 std::string &Result);
401
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000402 virtual void Initialize(ASTContext &context);
403
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000404 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000405 // rewriting routines on the new ASTs.
406 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
407 Expr **args, unsigned nargs,
408 SourceLocation StartLoc=SourceLocation(),
409 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000410
411 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
412 QualType msgSendType,
413 QualType returnType,
414 SmallVectorImpl<QualType> &ArgTypes,
415 SmallVectorImpl<Expr*> &MsgExprs,
416 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000417
418 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
419 SourceLocation StartLoc=SourceLocation(),
420 SourceLocation EndLoc=SourceLocation());
421
422 void SynthCountByEnumWithState(std::string &buf);
423 void SynthMsgSendFunctionDecl();
424 void SynthMsgSendSuperFunctionDecl();
425 void SynthMsgSendStretFunctionDecl();
426 void SynthMsgSendFpretFunctionDecl();
427 void SynthMsgSendSuperStretFunctionDecl();
428 void SynthGetClassFunctionDecl();
429 void SynthGetMetaClassFunctionDecl();
430 void SynthGetSuperClassFunctionDecl();
431 void SynthSelGetUidFunctionDecl();
432 void SynthSuperContructorFunctionDecl();
433
434 // Rewriting metadata
435 template<typename MethodIterator>
436 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
437 MethodIterator MethodEnd,
438 bool IsInstanceMethod,
439 StringRef prefix,
440 StringRef ClassName,
441 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000442 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
443 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000444 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445 const ObjCList<ObjCProtocolDecl> &Prots,
446 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000447 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000448 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000449 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000450
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000451 void RewriteMetaDataIntoBuffer(std::string &Result);
452 void WriteImageInfo(std::string &Result);
453 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000454 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000455 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000456
457 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000458 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000459 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000460 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461
462
463 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
464 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
465 StringRef funcName, std::string Tag);
466 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockImpl(BlockExpr *CE,
469 std::string Tag, std::string Desc);
470 std::string SynthesizeBlockDescriptor(std::string DescTag,
471 std::string ImplTag,
472 int i, StringRef funcName,
473 unsigned hasCopy);
474 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
475 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
476 StringRef FunName);
477 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
478 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +0000479 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480
481 // Misc. helper routines.
482 QualType getProtocolType();
483 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000484 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
485 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
486 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
487
488 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
489 void CollectBlockDeclRefInfo(BlockExpr *Exp);
490 void GetBlockDeclRefExprs(Stmt *S);
491 void GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +0000492 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000493 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
494
495 // We avoid calling Type::isBlockPointerType(), since it operates on the
496 // canonical type. We only care if the top-level type is a closure pointer.
497 bool isTopLevelBlockPointerType(QualType T) {
498 return isa<BlockPointerType>(T);
499 }
500
501 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
502 /// to a function pointer type and upon success, returns true; false
503 /// otherwise.
504 bool convertBlockPointerToFunctionPointer(QualType &T) {
505 if (isTopLevelBlockPointerType(T)) {
506 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
507 T = Context->getPointerType(BPT->getPointeeType());
508 return true;
509 }
510 return false;
511 }
512
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000513 bool convertObjCTypeToCStyleType(QualType &T);
514
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000515 bool needToScanForQualifiers(QualType T);
516 QualType getSuperStructType();
517 QualType getConstantStringStructType();
518 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
519 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
520
521 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000522 if (T->isObjCQualifiedIdType()) {
523 bool isConst = T.isConstQualified();
524 T = isConst ? Context->getObjCIdType().withConst()
525 : Context->getObjCIdType();
526 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000527 else if (T->isObjCQualifiedClassType())
528 T = Context->getObjCClassType();
529 else if (T->isObjCObjectPointerType() &&
530 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
531 if (const ObjCObjectPointerType * OBJPT =
532 T->getAsObjCInterfacePointerType()) {
533 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
534 T = QualType(IFaceT, 0);
535 T = Context->getPointerType(T);
536 }
537 }
538 }
539
540 // FIXME: This predicate seems like it would be useful to add to ASTContext.
541 bool isObjCType(QualType T) {
542 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
543 return false;
544
545 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
546
547 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
548 OCT == Context->getCanonicalType(Context->getObjCClassType()))
549 return true;
550
551 if (const PointerType *PT = OCT->getAs<PointerType>()) {
552 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
553 PT->getPointeeType()->isObjCQualifiedIdType())
554 return true;
555 }
556 return false;
557 }
558 bool PointerTypeTakesAnyBlockArguments(QualType QT);
559 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
560 void GetExtentOfArgList(const char *Name, const char *&LParen,
561 const char *&RParen);
562
563 void QuoteDoublequotes(std::string &From, std::string &To) {
564 for (unsigned i = 0; i < From.length(); i++) {
565 if (From[i] == '"')
566 To += "\\\"";
567 else
568 To += From[i];
569 }
570 }
571
572 QualType getSimpleFunctionType(QualType result,
573 const QualType *args,
574 unsigned numArgs,
575 bool variadic = false) {
576 if (result == Context->getObjCInstanceType())
577 result = Context->getObjCIdType();
578 FunctionProtoType::ExtProtoInfo fpi;
579 fpi.Variadic = variadic;
580 return Context->getFunctionType(result, args, numArgs, fpi);
581 }
582
583 // Helper function: create a CStyleCastExpr with trivial type source info.
584 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
585 CastKind Kind, Expr *E) {
586 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
587 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
588 SourceLocation(), SourceLocation());
589 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000590
591 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
592 IdentifierInfo* II = &Context->Idents.get("load");
593 Selector LoadSel = Context->Selectors.getSelector(0, &II);
594 return OD->getClassMethod(LoadSel) != 0;
595 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000596 };
597
598}
599
600void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
601 NamedDecl *D) {
602 if (const FunctionProtoType *fproto
603 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
604 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
605 E = fproto->arg_type_end(); I && (I != E); ++I)
606 if (isTopLevelBlockPointerType(*I)) {
607 // All the args are checked/rewritten. Don't call twice!
608 RewriteBlockPointerDecl(D);
609 break;
610 }
611 }
612}
613
614void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
615 const PointerType *PT = funcType->getAs<PointerType>();
616 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
617 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
618}
619
620static bool IsHeaderFile(const std::string &Filename) {
621 std::string::size_type DotPos = Filename.rfind('.');
622
623 if (DotPos == std::string::npos) {
624 // no file extension
625 return false;
626 }
627
628 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
629 // C header: .h
630 // C++ header: .hh or .H;
631 return Ext == "h" || Ext == "hh" || Ext == "H";
632}
633
634RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
635 DiagnosticsEngine &D, const LangOptions &LOpts,
636 bool silenceMacroWarn)
637 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
638 SilenceRewriteMacroWarning(silenceMacroWarn) {
639 IsHeader = IsHeaderFile(inFile);
640 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
641 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000642 // FIXME. This should be an error. But if block is not called, it is OK. And it
643 // may break including some headers.
644 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
645 "rewriting block literal declared in global scope is not implemented");
646
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000647 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
648 DiagnosticsEngine::Warning,
649 "rewriter doesn't support user-specified control flow semantics "
650 "for @try/@finally (code may not execute properly)");
651}
652
653ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
654 raw_ostream* OS,
655 DiagnosticsEngine &Diags,
656 const LangOptions &LOpts,
657 bool SilenceRewriteMacroWarning) {
658 return new RewriteModernObjC(InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning);
659}
660
661void RewriteModernObjC::InitializeCommon(ASTContext &context) {
662 Context = &context;
663 SM = &Context->getSourceManager();
664 TUDecl = Context->getTranslationUnitDecl();
665 MsgSendFunctionDecl = 0;
666 MsgSendSuperFunctionDecl = 0;
667 MsgSendStretFunctionDecl = 0;
668 MsgSendSuperStretFunctionDecl = 0;
669 MsgSendFpretFunctionDecl = 0;
670 GetClassFunctionDecl = 0;
671 GetMetaClassFunctionDecl = 0;
672 GetSuperClassFunctionDecl = 0;
673 SelGetUidFunctionDecl = 0;
674 CFStringFunctionDecl = 0;
675 ConstantStringClassReference = 0;
676 NSStringRecord = 0;
677 CurMethodDef = 0;
678 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000679 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000680 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000681 SuperStructDecl = 0;
682 ProtocolTypeDecl = 0;
683 ConstantStringDecl = 0;
684 BcLabelCount = 0;
685 SuperContructorFunctionDecl = 0;
686 NumObjCStringLiterals = 0;
687 PropParentMap = 0;
688 CurrentBody = 0;
689 DisableReplaceStmt = false;
690 objc_impl_method = false;
691
692 // Get the ID and start/end of the main file.
693 MainFileID = SM->getMainFileID();
694 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
695 MainFileStart = MainBuf->getBufferStart();
696 MainFileEnd = MainBuf->getBufferEnd();
697
David Blaikie4e4d0842012-03-11 07:00:24 +0000698 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000699}
700
701//===----------------------------------------------------------------------===//
702// Top Level Driver Code
703//===----------------------------------------------------------------------===//
704
705void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
706 if (Diags.hasErrorOccurred())
707 return;
708
709 // Two cases: either the decl could be in the main file, or it could be in a
710 // #included file. If the former, rewrite it now. If the later, check to see
711 // if we rewrote the #include/#import.
712 SourceLocation Loc = D->getLocation();
713 Loc = SM->getExpansionLoc(Loc);
714
715 // If this is for a builtin, ignore it.
716 if (Loc.isInvalid()) return;
717
718 // Look for built-in declarations that we need to refer during the rewrite.
719 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
720 RewriteFunctionDecl(FD);
721 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
722 // declared in <Foundation/NSString.h>
723 if (FVD->getName() == "_NSConstantStringClassReference") {
724 ConstantStringClassReference = FVD;
725 return;
726 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000727 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
728 RewriteCategoryDecl(CD);
729 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
730 if (PD->isThisDeclarationADefinition())
731 RewriteProtocolDecl(PD);
732 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000733 // FIXME. This will not work in all situations and leaving it out
734 // is harmless.
735 // RewriteLinkageSpec(LSD);
736
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000737 // Recurse into linkage specifications
738 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
739 DIEnd = LSD->decls_end();
740 DI != DIEnd; ) {
741 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
742 if (!IFace->isThisDeclarationADefinition()) {
743 SmallVector<Decl *, 8> DG;
744 SourceLocation StartLoc = IFace->getLocStart();
745 do {
746 if (isa<ObjCInterfaceDecl>(*DI) &&
747 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
748 StartLoc == (*DI)->getLocStart())
749 DG.push_back(*DI);
750 else
751 break;
752
753 ++DI;
754 } while (DI != DIEnd);
755 RewriteForwardClassDecl(DG);
756 continue;
757 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000758 else {
759 // Keep track of all interface declarations seen.
760 ObjCInterfacesSeen.push_back(IFace);
761 ++DI;
762 continue;
763 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000764 }
765
766 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
767 if (!Proto->isThisDeclarationADefinition()) {
768 SmallVector<Decl *, 8> DG;
769 SourceLocation StartLoc = Proto->getLocStart();
770 do {
771 if (isa<ObjCProtocolDecl>(*DI) &&
772 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
773 StartLoc == (*DI)->getLocStart())
774 DG.push_back(*DI);
775 else
776 break;
777
778 ++DI;
779 } while (DI != DIEnd);
780 RewriteForwardProtocolDecl(DG);
781 continue;
782 }
783 }
784
785 HandleTopLevelSingleDecl(*DI);
786 ++DI;
787 }
788 }
789 // If we have a decl in the main file, see if we should rewrite it.
790 if (SM->isFromMainFile(Loc))
791 return HandleDeclInMainFile(D);
792}
793
794//===----------------------------------------------------------------------===//
795// Syntactic (non-AST) Rewriting Code
796//===----------------------------------------------------------------------===//
797
798void RewriteModernObjC::RewriteInclude() {
799 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
800 StringRef MainBuf = SM->getBufferData(MainFileID);
801 const char *MainBufStart = MainBuf.begin();
802 const char *MainBufEnd = MainBuf.end();
803 size_t ImportLen = strlen("import");
804
805 // Loop over the whole file, looking for includes.
806 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
807 if (*BufPtr == '#') {
808 if (++BufPtr == MainBufEnd)
809 return;
810 while (*BufPtr == ' ' || *BufPtr == '\t')
811 if (++BufPtr == MainBufEnd)
812 return;
813 if (!strncmp(BufPtr, "import", ImportLen)) {
814 // replace import with include
815 SourceLocation ImportLoc =
816 LocStart.getLocWithOffset(BufPtr-MainBufStart);
817 ReplaceText(ImportLoc, ImportLen, "include");
818 BufPtr += ImportLen;
819 }
820 }
821 }
822}
823
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000824static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
825 ObjCIvarDecl *IvarDecl, std::string &Result) {
826 Result += "OBJC_IVAR_$_";
827 Result += IDecl->getName();
828 Result += "$";
829 Result += IvarDecl->getName();
830}
831
832std::string
833RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
834 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
835
836 // Build name of symbol holding ivar offset.
837 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000838 if (D->isBitField())
839 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
840 else
841 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000842
843
844 std::string S = "(*(";
845 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000846 if (D->isBitField())
847 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000848
849 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
850 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
851 RD = RD->getDefinition();
852 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
853 // decltype(((Foo_IMPL*)0)->bar) *
854 ObjCContainerDecl *CDecl =
855 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
856 // ivar in class extensions requires special treatment.
857 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
858 CDecl = CatDecl->getClassInterface();
859 std::string RecName = CDecl->getName();
860 RecName += "_IMPL";
861 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
862 SourceLocation(), SourceLocation(),
863 &Context->Idents.get(RecName.c_str()));
864 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
865 unsigned UnsignedIntSize =
866 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
867 Expr *Zero = IntegerLiteral::Create(*Context,
868 llvm::APInt(UnsignedIntSize, 0),
869 Context->UnsignedIntTy, SourceLocation());
870 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
871 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
872 Zero);
873 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
874 SourceLocation(),
875 &Context->Idents.get(D->getNameAsString()),
876 IvarT, 0,
877 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000878 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000879 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
880 FD->getType(), VK_LValue,
881 OK_Ordinary);
882 IvarT = Context->getDecltypeType(ME, ME->getType());
883 }
884 }
885 convertObjCTypeToCStyleType(IvarT);
886 QualType castT = Context->getPointerType(IvarT);
887 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
888 S += TypeString;
889 S += ")";
890
891 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
892 S += "((char *)self + ";
893 S += IvarOffsetName;
894 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000895 if (D->isBitField()) {
896 S += ".";
897 S += D->getNameAsString();
898 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000899 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000900 return S;
901}
902
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000903/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
904/// been found in the class implementation. In this case, it must be synthesized.
905static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
906 ObjCPropertyDecl *PD,
907 bool getter) {
908 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
909 : !IMP->getInstanceMethod(PD->getSetterName());
910
911}
912
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000913void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
914 ObjCImplementationDecl *IMD,
915 ObjCCategoryImplDecl *CID) {
916 static bool objcGetPropertyDefined = false;
917 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000918 SourceLocation startGetterSetterLoc;
919
920 if (PID->getLocStart().isValid()) {
921 SourceLocation startLoc = PID->getLocStart();
922 InsertText(startLoc, "// ");
923 const char *startBuf = SM->getCharacterData(startLoc);
924 assert((*startBuf == '@') && "bogus @synthesize location");
925 const char *semiBuf = strchr(startBuf, ';');
926 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
927 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
928 }
929 else
930 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000931
932 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
933 return; // FIXME: is this correct?
934
935 // Generate the 'getter' function.
936 ObjCPropertyDecl *PD = PID->getPropertyDecl();
937 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
938
939 if (!OID)
940 return;
Bill Wendlingad017fa2012-12-20 19:22:21 +0000941 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000942 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000943 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
944 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000945 ObjCPropertyDecl::OBJC_PR_copy));
946 std::string Getr;
947 if (GenGetProperty && !objcGetPropertyDefined) {
948 objcGetPropertyDefined = true;
949 // FIXME. Is this attribute correct in all cases?
950 Getr = "\nextern \"C\" __declspec(dllimport) "
951 "id objc_getProperty(id, SEL, long, bool);\n";
952 }
953 RewriteObjCMethodDecl(OID->getContainingInterface(),
954 PD->getGetterMethodDecl(), Getr);
955 Getr += "{ ";
956 // Synthesize an explicit cast to gain access to the ivar.
957 // See objc-act.c:objc_synthesize_new_getter() for details.
958 if (GenGetProperty) {
959 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
960 Getr += "typedef ";
961 const FunctionType *FPRetType = 0;
962 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
963 FPRetType);
964 Getr += " _TYPE";
965 if (FPRetType) {
966 Getr += ")"; // close the precedence "scope" for "*".
967
968 // Now, emit the argument types (if any).
969 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
970 Getr += "(";
971 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
972 if (i) Getr += ", ";
973 std::string ParamStr = FT->getArgType(i).getAsString(
974 Context->getPrintingPolicy());
975 Getr += ParamStr;
976 }
977 if (FT->isVariadic()) {
978 if (FT->getNumArgs()) Getr += ", ";
979 Getr += "...";
980 }
981 Getr += ")";
982 } else
983 Getr += "()";
984 }
985 Getr += ";\n";
986 Getr += "return (_TYPE)";
987 Getr += "objc_getProperty(self, _cmd, ";
988 RewriteIvarOffsetComputation(OID, Getr);
989 Getr += ", 1)";
990 }
991 else
992 Getr += "return " + getIvarAccessString(OID);
993 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000994 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000995 }
996
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000997 if (PD->isReadOnly() ||
998 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000999 return;
1000
1001 // Generate the 'setter' function.
1002 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001003 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001004 ObjCPropertyDecl::OBJC_PR_copy);
1005 if (GenSetProperty && !objcSetPropertyDefined) {
1006 objcSetPropertyDefined = true;
1007 // FIXME. Is this attribute correct in all cases?
1008 Setr = "\nextern \"C\" __declspec(dllimport) "
1009 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1010 }
1011
1012 RewriteObjCMethodDecl(OID->getContainingInterface(),
1013 PD->getSetterMethodDecl(), Setr);
1014 Setr += "{ ";
1015 // Synthesize an explicit cast to initialize the ivar.
1016 // See objc-act.c:objc_synthesize_new_setter() for details.
1017 if (GenSetProperty) {
1018 Setr += "objc_setProperty (self, _cmd, ";
1019 RewriteIvarOffsetComputation(OID, Setr);
1020 Setr += ", (id)";
1021 Setr += PD->getName();
1022 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001023 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001024 Setr += "0, ";
1025 else
1026 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001027 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001028 Setr += "1)";
1029 else
1030 Setr += "0)";
1031 }
1032 else {
1033 Setr += getIvarAccessString(OID) + " = ";
1034 Setr += PD->getName();
1035 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001036 Setr += "; }\n";
1037 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001038}
1039
1040static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1041 std::string &typedefString) {
1042 typedefString += "#ifndef _REWRITER_typedef_";
1043 typedefString += ForwardDecl->getNameAsString();
1044 typedefString += "\n";
1045 typedefString += "#define _REWRITER_typedef_";
1046 typedefString += ForwardDecl->getNameAsString();
1047 typedefString += "\n";
1048 typedefString += "typedef struct objc_object ";
1049 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001050 // typedef struct { } _objc_exc_Classname;
1051 typedefString += ";\ntypedef struct {} _objc_exc_";
1052 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001053 typedefString += ";\n#endif\n";
1054}
1055
1056void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1057 const std::string &typedefString) {
1058 SourceLocation startLoc = ClassDecl->getLocStart();
1059 const char *startBuf = SM->getCharacterData(startLoc);
1060 const char *semiPtr = strchr(startBuf, ';');
1061 // Replace the @class with typedefs corresponding to the classes.
1062 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1063}
1064
1065void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1066 std::string typedefString;
1067 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1068 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1069 if (I == D.begin()) {
1070 // Translate to typedef's that forward reference structs with the same name
1071 // as the class. As a convenience, we include the original declaration
1072 // as a comment.
1073 typedefString += "// @class ";
1074 typedefString += ForwardDecl->getNameAsString();
1075 typedefString += ";\n";
1076 }
1077 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1078 }
1079 DeclGroupRef::iterator I = D.begin();
1080 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1081}
1082
1083void RewriteModernObjC::RewriteForwardClassDecl(
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001084 const SmallVector<Decl *, 8> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001085 std::string typedefString;
1086 for (unsigned i = 0; i < D.size(); i++) {
1087 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1088 if (i == 0) {
1089 typedefString += "// @class ";
1090 typedefString += ForwardDecl->getNameAsString();
1091 typedefString += ";\n";
1092 }
1093 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1094 }
1095 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1096}
1097
1098void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1099 // When method is a synthesized one, such as a getter/setter there is
1100 // nothing to rewrite.
1101 if (Method->isImplicit())
1102 return;
1103 SourceLocation LocStart = Method->getLocStart();
1104 SourceLocation LocEnd = Method->getLocEnd();
1105
1106 if (SM->getExpansionLineNumber(LocEnd) >
1107 SM->getExpansionLineNumber(LocStart)) {
1108 InsertText(LocStart, "#if 0\n");
1109 ReplaceText(LocEnd, 1, ";\n#endif\n");
1110 } else {
1111 InsertText(LocStart, "// ");
1112 }
1113}
1114
1115void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1116 SourceLocation Loc = prop->getAtLoc();
1117
1118 ReplaceText(Loc, 0, "// ");
1119 // FIXME: handle properties that are declared across multiple lines.
1120}
1121
1122void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1123 SourceLocation LocStart = CatDecl->getLocStart();
1124
1125 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001126 if (CatDecl->getIvarRBraceLoc().isValid()) {
1127 ReplaceText(LocStart, 1, "/** ");
1128 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1129 }
1130 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001131 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001132 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001133
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001134 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1135 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001136 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001137
1138 for (ObjCCategoryDecl::instmeth_iterator
1139 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1140 I != E; ++I)
1141 RewriteMethodDeclaration(*I);
1142 for (ObjCCategoryDecl::classmeth_iterator
1143 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1144 I != E; ++I)
1145 RewriteMethodDeclaration(*I);
1146
1147 // Lastly, comment out the @end.
1148 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1149 strlen("@end"), "/* @end */");
1150}
1151
1152void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1153 SourceLocation LocStart = PDecl->getLocStart();
1154 assert(PDecl->isThisDeclarationADefinition());
1155
1156 // FIXME: handle protocol headers that are declared across multiple lines.
1157 ReplaceText(LocStart, 0, "// ");
1158
1159 for (ObjCProtocolDecl::instmeth_iterator
1160 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1161 I != E; ++I)
1162 RewriteMethodDeclaration(*I);
1163 for (ObjCProtocolDecl::classmeth_iterator
1164 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1165 I != E; ++I)
1166 RewriteMethodDeclaration(*I);
1167
1168 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1169 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001170 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001171
1172 // Lastly, comment out the @end.
1173 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1174 ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1175
1176 // Must comment out @optional/@required
1177 const char *startBuf = SM->getCharacterData(LocStart);
1178 const char *endBuf = SM->getCharacterData(LocEnd);
1179 for (const char *p = startBuf; p < endBuf; p++) {
1180 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1181 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1182 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1183
1184 }
1185 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1186 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1187 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1188
1189 }
1190 }
1191}
1192
1193void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1194 SourceLocation LocStart = (*D.begin())->getLocStart();
1195 if (LocStart.isInvalid())
1196 llvm_unreachable("Invalid SourceLocation");
1197 // FIXME: handle forward protocol that are declared across multiple lines.
1198 ReplaceText(LocStart, 0, "// ");
1199}
1200
1201void
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001202RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVector<Decl *, 8> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001203 SourceLocation LocStart = DG[0]->getLocStart();
1204 if (LocStart.isInvalid())
1205 llvm_unreachable("Invalid SourceLocation");
1206 // FIXME: handle forward protocol that are declared across multiple lines.
1207 ReplaceText(LocStart, 0, "// ");
1208}
1209
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001210void
1211RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1212 SourceLocation LocStart = LSD->getExternLoc();
1213 if (LocStart.isInvalid())
1214 llvm_unreachable("Invalid extern SourceLocation");
1215
1216 ReplaceText(LocStart, 0, "// ");
1217 if (!LSD->hasBraces())
1218 return;
1219 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1220 SourceLocation LocRBrace = LSD->getRBraceLoc();
1221 if (LocRBrace.isInvalid())
1222 llvm_unreachable("Invalid rbrace SourceLocation");
1223 ReplaceText(LocRBrace, 0, "// ");
1224}
1225
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001226void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1227 const FunctionType *&FPRetType) {
1228 if (T->isObjCQualifiedIdType())
1229 ResultStr += "id";
1230 else if (T->isFunctionPointerType() ||
1231 T->isBlockPointerType()) {
1232 // needs special handling, since pointer-to-functions have special
1233 // syntax (where a decaration models use).
1234 QualType retType = T;
1235 QualType PointeeTy;
1236 if (const PointerType* PT = retType->getAs<PointerType>())
1237 PointeeTy = PT->getPointeeType();
1238 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1239 PointeeTy = BPT->getPointeeType();
1240 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1241 ResultStr += FPRetType->getResultType().getAsString(
1242 Context->getPrintingPolicy());
1243 ResultStr += "(*";
1244 }
1245 } else
1246 ResultStr += T.getAsString(Context->getPrintingPolicy());
1247}
1248
1249void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1250 ObjCMethodDecl *OMD,
1251 std::string &ResultStr) {
1252 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1253 const FunctionType *FPRetType = 0;
1254 ResultStr += "\nstatic ";
1255 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1256 ResultStr += " ";
1257
1258 // Unique method name
1259 std::string NameStr;
1260
1261 if (OMD->isInstanceMethod())
1262 NameStr += "_I_";
1263 else
1264 NameStr += "_C_";
1265
1266 NameStr += IDecl->getNameAsString();
1267 NameStr += "_";
1268
1269 if (ObjCCategoryImplDecl *CID =
1270 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1271 NameStr += CID->getNameAsString();
1272 NameStr += "_";
1273 }
1274 // Append selector names, replacing ':' with '_'
1275 {
1276 std::string selString = OMD->getSelector().getAsString();
1277 int len = selString.size();
1278 for (int i = 0; i < len; i++)
1279 if (selString[i] == ':')
1280 selString[i] = '_';
1281 NameStr += selString;
1282 }
1283 // Remember this name for metadata emission
1284 MethodInternalNames[OMD] = NameStr;
1285 ResultStr += NameStr;
1286
1287 // Rewrite arguments
1288 ResultStr += "(";
1289
1290 // invisible arguments
1291 if (OMD->isInstanceMethod()) {
1292 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1293 selfTy = Context->getPointerType(selfTy);
1294 if (!LangOpts.MicrosoftExt) {
1295 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1296 ResultStr += "struct ";
1297 }
1298 // When rewriting for Microsoft, explicitly omit the structure name.
1299 ResultStr += IDecl->getNameAsString();
1300 ResultStr += " *";
1301 }
1302 else
1303 ResultStr += Context->getObjCClassType().getAsString(
1304 Context->getPrintingPolicy());
1305
1306 ResultStr += " self, ";
1307 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1308 ResultStr += " _cmd";
1309
1310 // Method arguments.
1311 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1312 E = OMD->param_end(); PI != E; ++PI) {
1313 ParmVarDecl *PDecl = *PI;
1314 ResultStr += ", ";
1315 if (PDecl->getType()->isObjCQualifiedIdType()) {
1316 ResultStr += "id ";
1317 ResultStr += PDecl->getNameAsString();
1318 } else {
1319 std::string Name = PDecl->getNameAsString();
1320 QualType QT = PDecl->getType();
1321 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001322 (void)convertBlockPointerToFunctionPointer(QT);
1323 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001324 ResultStr += Name;
1325 }
1326 }
1327 if (OMD->isVariadic())
1328 ResultStr += ", ...";
1329 ResultStr += ") ";
1330
1331 if (FPRetType) {
1332 ResultStr += ")"; // close the precedence "scope" for "*".
1333
1334 // Now, emit the argument types (if any).
1335 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1336 ResultStr += "(";
1337 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1338 if (i) ResultStr += ", ";
1339 std::string ParamStr = FT->getArgType(i).getAsString(
1340 Context->getPrintingPolicy());
1341 ResultStr += ParamStr;
1342 }
1343 if (FT->isVariadic()) {
1344 if (FT->getNumArgs()) ResultStr += ", ";
1345 ResultStr += "...";
1346 }
1347 ResultStr += ")";
1348 } else {
1349 ResultStr += "()";
1350 }
1351 }
1352}
1353void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1354 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1355 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1356
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001357 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001358 if (IMD->getIvarRBraceLoc().isValid()) {
1359 ReplaceText(IMD->getLocStart(), 1, "/** ");
1360 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001361 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001362 else {
1363 InsertText(IMD->getLocStart(), "// ");
1364 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001365 }
1366 else
1367 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001368
1369 for (ObjCCategoryImplDecl::instmeth_iterator
1370 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1371 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1372 I != E; ++I) {
1373 std::string ResultStr;
1374 ObjCMethodDecl *OMD = *I;
1375 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1376 SourceLocation LocStart = OMD->getLocStart();
1377 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1378
1379 const char *startBuf = SM->getCharacterData(LocStart);
1380 const char *endBuf = SM->getCharacterData(LocEnd);
1381 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1382 }
1383
1384 for (ObjCCategoryImplDecl::classmeth_iterator
1385 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1386 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1387 I != E; ++I) {
1388 std::string ResultStr;
1389 ObjCMethodDecl *OMD = *I;
1390 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1391 SourceLocation LocStart = OMD->getLocStart();
1392 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1393
1394 const char *startBuf = SM->getCharacterData(LocStart);
1395 const char *endBuf = SM->getCharacterData(LocEnd);
1396 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1397 }
1398 for (ObjCCategoryImplDecl::propimpl_iterator
1399 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1400 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1401 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001402 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001403 }
1404
1405 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1406}
1407
1408void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001409 // Do not synthesize more than once.
1410 if (ObjCSynthesizedStructs.count(ClassDecl))
1411 return;
1412 // Make sure super class's are written before current class is written.
1413 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1414 while (SuperClass) {
1415 RewriteInterfaceDecl(SuperClass);
1416 SuperClass = SuperClass->getSuperClass();
1417 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001418 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001419 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001420 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001421 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001422 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1423
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001424 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001425 // Mark this typedef as having been written into its c++ equivalent.
1426 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001427
1428 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001429 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001430 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001431 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001432 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001433 I != E; ++I)
1434 RewriteMethodDeclaration(*I);
1435 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001436 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001437 I != E; ++I)
1438 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001439
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001440 // Lastly, comment out the @end.
1441 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1442 "/* @end */");
1443 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001444}
1445
1446Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1447 SourceRange OldRange = PseudoOp->getSourceRange();
1448
1449 // We just magically know some things about the structure of this
1450 // expression.
1451 ObjCMessageExpr *OldMsg =
1452 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1453 PseudoOp->getNumSemanticExprs() - 1));
1454
1455 // Because the rewriter doesn't allow us to rewrite rewritten code,
1456 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001457 Expr *Base;
1458 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001459 {
1460 DisableReplaceStmtScope S(*this);
1461
1462 // Rebuild the base expression if we have one.
1463 Base = 0;
1464 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1465 Base = OldMsg->getInstanceReceiver();
1466 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1467 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1468 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001469
1470 unsigned numArgs = OldMsg->getNumArgs();
1471 for (unsigned i = 0; i < numArgs; i++) {
1472 Expr *Arg = OldMsg->getArg(i);
1473 if (isa<OpaqueValueExpr>(Arg))
1474 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1475 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1476 Args.push_back(Arg);
1477 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001478 }
1479
1480 // TODO: avoid this copy.
1481 SmallVector<SourceLocation, 1> SelLocs;
1482 OldMsg->getSelectorLocs(SelLocs);
1483
1484 ObjCMessageExpr *NewMsg = 0;
1485 switch (OldMsg->getReceiverKind()) {
1486 case ObjCMessageExpr::Class:
1487 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1488 OldMsg->getValueKind(),
1489 OldMsg->getLeftLoc(),
1490 OldMsg->getClassReceiverTypeInfo(),
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::Instance:
1500 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1501 OldMsg->getValueKind(),
1502 OldMsg->getLeftLoc(),
1503 Base,
1504 OldMsg->getSelector(),
1505 SelLocs,
1506 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001507 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001508 OldMsg->getRightLoc(),
1509 OldMsg->isImplicit());
1510 break;
1511
1512 case ObjCMessageExpr::SuperClass:
1513 case ObjCMessageExpr::SuperInstance:
1514 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1515 OldMsg->getValueKind(),
1516 OldMsg->getLeftLoc(),
1517 OldMsg->getSuperLoc(),
1518 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1519 OldMsg->getSuperType(),
1520 OldMsg->getSelector(),
1521 SelLocs,
1522 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001523 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001524 OldMsg->getRightLoc(),
1525 OldMsg->isImplicit());
1526 break;
1527 }
1528
1529 Stmt *Replacement = SynthMessageExpr(NewMsg);
1530 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1531 return Replacement;
1532}
1533
1534Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1535 SourceRange OldRange = PseudoOp->getSourceRange();
1536
1537 // We just magically know some things about the structure of this
1538 // expression.
1539 ObjCMessageExpr *OldMsg =
1540 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1541
1542 // Because the rewriter doesn't allow us to rewrite rewritten code,
1543 // we need to suppress rewriting the sub-statements.
1544 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001545 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001546 {
1547 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001548 // Rebuild the base expression if we have one.
1549 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1550 Base = OldMsg->getInstanceReceiver();
1551 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1552 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1553 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001554 unsigned numArgs = OldMsg->getNumArgs();
1555 for (unsigned i = 0; i < numArgs; i++) {
1556 Expr *Arg = OldMsg->getArg(i);
1557 if (isa<OpaqueValueExpr>(Arg))
1558 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1559 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1560 Args.push_back(Arg);
1561 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001562 }
1563
1564 // Intentionally empty.
1565 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001566
1567 ObjCMessageExpr *NewMsg = 0;
1568 switch (OldMsg->getReceiverKind()) {
1569 case ObjCMessageExpr::Class:
1570 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1571 OldMsg->getValueKind(),
1572 OldMsg->getLeftLoc(),
1573 OldMsg->getClassReceiverTypeInfo(),
1574 OldMsg->getSelector(),
1575 SelLocs,
1576 OldMsg->getMethodDecl(),
1577 Args,
1578 OldMsg->getRightLoc(),
1579 OldMsg->isImplicit());
1580 break;
1581
1582 case ObjCMessageExpr::Instance:
1583 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1584 OldMsg->getValueKind(),
1585 OldMsg->getLeftLoc(),
1586 Base,
1587 OldMsg->getSelector(),
1588 SelLocs,
1589 OldMsg->getMethodDecl(),
1590 Args,
1591 OldMsg->getRightLoc(),
1592 OldMsg->isImplicit());
1593 break;
1594
1595 case ObjCMessageExpr::SuperClass:
1596 case ObjCMessageExpr::SuperInstance:
1597 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1598 OldMsg->getValueKind(),
1599 OldMsg->getLeftLoc(),
1600 OldMsg->getSuperLoc(),
1601 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1602 OldMsg->getSuperType(),
1603 OldMsg->getSelector(),
1604 SelLocs,
1605 OldMsg->getMethodDecl(),
1606 Args,
1607 OldMsg->getRightLoc(),
1608 OldMsg->isImplicit());
1609 break;
1610 }
1611
1612 Stmt *Replacement = SynthMessageExpr(NewMsg);
1613 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1614 return Replacement;
1615}
1616
1617/// SynthCountByEnumWithState - To print:
1618/// ((unsigned int (*)
1619/// (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1620/// (void *)objc_msgSend)((id)l_collection,
1621/// sel_registerName(
1622/// "countByEnumeratingWithState:objects:count:"),
1623/// &enumState,
1624/// (id *)__rw_items, (unsigned int)16)
1625///
1626void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1627 buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1628 "id *, unsigned int))(void *)objc_msgSend)";
1629 buf += "\n\t\t";
1630 buf += "((id)l_collection,\n\t\t";
1631 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1632 buf += "\n\t\t";
1633 buf += "&enumState, "
1634 "(id *)__rw_items, (unsigned int)16)";
1635}
1636
1637/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1638/// statement to exit to its outer synthesized loop.
1639///
1640Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1641 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1642 return S;
1643 // replace break with goto __break_label
1644 std::string buf;
1645
1646 SourceLocation startLoc = S->getLocStart();
1647 buf = "goto __break_label_";
1648 buf += utostr(ObjCBcLabelNo.back());
1649 ReplaceText(startLoc, strlen("break"), buf);
1650
1651 return 0;
1652}
1653
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001654void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1655 SourceLocation Loc,
1656 std::string &LineString) {
1657 if (Loc.isFileID()) {
1658 LineString += "\n#line ";
1659 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1660 LineString += utostr(PLoc.getLine());
1661 LineString += " \"";
1662 LineString += Lexer::Stringify(PLoc.getFilename());
1663 LineString += "\"\n";
1664 }
1665}
1666
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001667/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1668/// statement to continue with its inner synthesized loop.
1669///
1670Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1671 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1672 return S;
1673 // replace continue with goto __continue_label
1674 std::string buf;
1675
1676 SourceLocation startLoc = S->getLocStart();
1677 buf = "goto __continue_label_";
1678 buf += utostr(ObjCBcLabelNo.back());
1679 ReplaceText(startLoc, strlen("continue"), buf);
1680
1681 return 0;
1682}
1683
1684/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1685/// It rewrites:
1686/// for ( type elem in collection) { stmts; }
1687
1688/// Into:
1689/// {
1690/// type elem;
1691/// struct __objcFastEnumerationState enumState = { 0 };
1692/// id __rw_items[16];
1693/// id l_collection = (id)collection;
1694/// unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1695/// objects:__rw_items count:16];
1696/// if (limit) {
1697/// unsigned long startMutations = *enumState.mutationsPtr;
1698/// do {
1699/// unsigned long counter = 0;
1700/// do {
1701/// if (startMutations != *enumState.mutationsPtr)
1702/// objc_enumerationMutation(l_collection);
1703/// elem = (type)enumState.itemsPtr[counter++];
1704/// stmts;
1705/// __continue_label: ;
1706/// } while (counter < limit);
1707/// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1708/// objects:__rw_items count:16]);
1709/// elem = nil;
1710/// __break_label: ;
1711/// }
1712/// else
1713/// elem = nil;
1714/// }
1715///
1716Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1717 SourceLocation OrigEnd) {
1718 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1719 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1720 "ObjCForCollectionStmt Statement stack mismatch");
1721 assert(!ObjCBcLabelNo.empty() &&
1722 "ObjCForCollectionStmt - Label No stack empty");
1723
1724 SourceLocation startLoc = S->getLocStart();
1725 const char *startBuf = SM->getCharacterData(startLoc);
1726 StringRef elementName;
1727 std::string elementTypeAsString;
1728 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001729 // line directive first.
1730 SourceLocation ForEachLoc = S->getForLoc();
1731 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1732 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001733 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1734 // type elem;
1735 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1736 QualType ElementType = cast<ValueDecl>(D)->getType();
1737 if (ElementType->isObjCQualifiedIdType() ||
1738 ElementType->isObjCQualifiedInterfaceType())
1739 // Simply use 'id' for all qualified types.
1740 elementTypeAsString = "id";
1741 else
1742 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1743 buf += elementTypeAsString;
1744 buf += " ";
1745 elementName = D->getName();
1746 buf += elementName;
1747 buf += ";\n\t";
1748 }
1749 else {
1750 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1751 elementName = DR->getDecl()->getName();
1752 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1753 if (VD->getType()->isObjCQualifiedIdType() ||
1754 VD->getType()->isObjCQualifiedInterfaceType())
1755 // Simply use 'id' for all qualified types.
1756 elementTypeAsString = "id";
1757 else
1758 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1759 }
1760
1761 // struct __objcFastEnumerationState enumState = { 0 };
1762 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1763 // id __rw_items[16];
1764 buf += "id __rw_items[16];\n\t";
1765 // id l_collection = (id)
1766 buf += "id l_collection = (id)";
1767 // Find start location of 'collection' the hard way!
1768 const char *startCollectionBuf = startBuf;
1769 startCollectionBuf += 3; // skip 'for'
1770 startCollectionBuf = strchr(startCollectionBuf, '(');
1771 startCollectionBuf++; // skip '('
1772 // find 'in' and skip it.
1773 while (*startCollectionBuf != ' ' ||
1774 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1775 (*(startCollectionBuf+3) != ' ' &&
1776 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1777 startCollectionBuf++;
1778 startCollectionBuf += 3;
1779
1780 // Replace: "for (type element in" with string constructed thus far.
1781 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1782 // Replace ')' in for '(' type elem in collection ')' with ';'
1783 SourceLocation rightParenLoc = S->getRParenLoc();
1784 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1785 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1786 buf = ";\n\t";
1787
1788 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1789 // objects:__rw_items count:16];
1790 // which is synthesized into:
1791 // unsigned int limit =
1792 // ((unsigned int (*)
1793 // (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1794 // (void *)objc_msgSend)((id)l_collection,
1795 // sel_registerName(
1796 // "countByEnumeratingWithState:objects:count:"),
1797 // (struct __objcFastEnumerationState *)&state,
1798 // (id *)__rw_items, (unsigned int)16);
1799 buf += "unsigned long limit =\n\t\t";
1800 SynthCountByEnumWithState(buf);
1801 buf += ";\n\t";
1802 /// if (limit) {
1803 /// unsigned long startMutations = *enumState.mutationsPtr;
1804 /// do {
1805 /// unsigned long counter = 0;
1806 /// do {
1807 /// if (startMutations != *enumState.mutationsPtr)
1808 /// objc_enumerationMutation(l_collection);
1809 /// elem = (type)enumState.itemsPtr[counter++];
1810 buf += "if (limit) {\n\t";
1811 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1812 buf += "do {\n\t\t";
1813 buf += "unsigned long counter = 0;\n\t\t";
1814 buf += "do {\n\t\t\t";
1815 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1816 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1817 buf += elementName;
1818 buf += " = (";
1819 buf += elementTypeAsString;
1820 buf += ")enumState.itemsPtr[counter++];";
1821 // Replace ')' in for '(' type elem in collection ')' with all of these.
1822 ReplaceText(lparenLoc, 1, buf);
1823
1824 /// __continue_label: ;
1825 /// } while (counter < limit);
1826 /// } while (limit = [l_collection countByEnumeratingWithState:&enumState
1827 /// objects:__rw_items count:16]);
1828 /// elem = nil;
1829 /// __break_label: ;
1830 /// }
1831 /// else
1832 /// elem = nil;
1833 /// }
1834 ///
1835 buf = ";\n\t";
1836 buf += "__continue_label_";
1837 buf += utostr(ObjCBcLabelNo.back());
1838 buf += ": ;";
1839 buf += "\n\t\t";
1840 buf += "} while (counter < limit);\n\t";
1841 buf += "} while (limit = ";
1842 SynthCountByEnumWithState(buf);
1843 buf += ");\n\t";
1844 buf += elementName;
1845 buf += " = ((";
1846 buf += elementTypeAsString;
1847 buf += ")0);\n\t";
1848 buf += "__break_label_";
1849 buf += utostr(ObjCBcLabelNo.back());
1850 buf += ": ;\n\t";
1851 buf += "}\n\t";
1852 buf += "else\n\t\t";
1853 buf += elementName;
1854 buf += " = ((";
1855 buf += elementTypeAsString;
1856 buf += ")0);\n\t";
1857 buf += "}\n";
1858
1859 // Insert all these *after* the statement body.
1860 // FIXME: If this should support Obj-C++, support CXXTryStmt
1861 if (isa<CompoundStmt>(S->getBody())) {
1862 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1863 InsertText(endBodyLoc, buf);
1864 } else {
1865 /* Need to treat single statements specially. For example:
1866 *
1867 * for (A *a in b) if (stuff()) break;
1868 * for (A *a in b) xxxyy;
1869 *
1870 * The following code simply scans ahead to the semi to find the actual end.
1871 */
1872 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1873 const char *semiBuf = strchr(stmtBuf, ';');
1874 assert(semiBuf && "Can't find ';'");
1875 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1876 InsertText(endBodyLoc, buf);
1877 }
1878 Stmts.pop_back();
1879 ObjCBcLabelNo.pop_back();
1880 return 0;
1881}
1882
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001883static void Write_RethrowObject(std::string &buf) {
1884 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1885 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1886 buf += "\tid rethrow;\n";
1887 buf += "\t} _fin_force_rethow(_rethrow);";
1888}
1889
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001890/// RewriteObjCSynchronizedStmt -
1891/// This routine rewrites @synchronized(expr) stmt;
1892/// into:
1893/// objc_sync_enter(expr);
1894/// @try stmt @finally { objc_sync_exit(expr); }
1895///
1896Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1897 // Get the start location and compute the semi location.
1898 SourceLocation startLoc = S->getLocStart();
1899 const char *startBuf = SM->getCharacterData(startLoc);
1900
1901 assert((*startBuf == '@') && "bogus @synchronized location");
1902
1903 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001904 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1905 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1906 buf += "{ id _rethrow = 0; id _sync_obj = ";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001907
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001908 const char *lparenBuf = startBuf;
1909 while (*lparenBuf != '(') lparenBuf++;
1910 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001911
1912 buf = "; objc_sync_enter(_sync_obj);\n";
1913 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1914 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1915 buf += "\n\tid sync_exit;";
1916 buf += "\n\t} _sync_exit(_sync_obj);\n";
1917
1918 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1919 // the sync expression is typically a message expression that's already
1920 // been rewritten! (which implies the SourceLocation's are invalid).
1921 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1922 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1923 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1924 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1925
1926 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1927 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1928 assert (*LBraceLocBuf == '{');
1929 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001930
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001931 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001932 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1933 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001934
1935 buf = "} catch (id e) {_rethrow = e;}\n";
1936 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001937 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001938 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001939
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001940 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001941
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001942 return 0;
1943}
1944
1945void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1946{
1947 // Perform a bottom up traversal of all children.
1948 for (Stmt::child_range CI = S->children(); CI; ++CI)
1949 if (*CI)
1950 WarnAboutReturnGotoStmts(*CI);
1951
1952 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1953 Diags.Report(Context->getFullLoc(S->getLocStart()),
1954 TryFinallyContainsReturnDiag);
1955 }
1956 return;
1957}
1958
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001959Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1960 SourceLocation startLoc = S->getAtLoc();
1961 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001962 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1963 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001964
1965 return 0;
1966}
1967
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001968Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001969 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001970 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001971 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001972 SourceLocation TryLocation = S->getAtTryLoc();
1973 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001974
1975 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001976 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001977 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001978 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001979 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001980 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001981 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001982 // Get the start location and compute the semi location.
1983 SourceLocation startLoc = S->getLocStart();
1984 const char *startBuf = SM->getCharacterData(startLoc);
1985
1986 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001987 if (finalStmt)
1988 ReplaceText(startLoc, 1, buf);
1989 else
1990 // @try -> try
1991 ReplaceText(startLoc, 1, "");
1992
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001993 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1994 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001995 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001996
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001997 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001998 bool AtRemoved = false;
1999 if (catchDecl) {
2000 QualType t = catchDecl->getType();
2001 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2002 // Should be a pointer to a class.
2003 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2004 if (IDecl) {
2005 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002006 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2007
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002008 startBuf = SM->getCharacterData(startLoc);
2009 assert((*startBuf == '@') && "bogus @catch location");
2010 SourceLocation rParenLoc = Catch->getRParenLoc();
2011 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2012
2013 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002014 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002015 Result += " *_"; Result += catchDecl->getNameAsString();
2016 Result += ")";
2017 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2018 // Foo *e = (Foo *)_e;
2019 Result.clear();
2020 Result = "{ ";
2021 Result += IDecl->getNameAsString();
2022 Result += " *"; Result += catchDecl->getNameAsString();
2023 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2024 Result += "_"; Result += catchDecl->getNameAsString();
2025
2026 Result += "; ";
2027 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2028 ReplaceText(lBraceLoc, 1, Result);
2029 AtRemoved = true;
2030 }
2031 }
2032 }
2033 if (!AtRemoved)
2034 // @catch -> catch
2035 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002036
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002037 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002038 if (finalStmt) {
2039 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002040 SourceLocation FinallyLoc = finalStmt->getLocStart();
2041
2042 if (noCatch) {
2043 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2044 buf += "catch (id e) {_rethrow = e;}\n";
2045 }
2046 else {
2047 buf += "}\n";
2048 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2049 buf += "catch (id e) {_rethrow = e;}\n";
2050 }
2051
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002052 SourceLocation startFinalLoc = finalStmt->getLocStart();
2053 ReplaceText(startFinalLoc, 8, buf);
2054 Stmt *body = finalStmt->getFinallyBody();
2055 SourceLocation startFinalBodyLoc = body->getLocStart();
2056 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002057 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002058 ReplaceText(startFinalBodyLoc, 1, buf);
2059
2060 SourceLocation endFinalBodyLoc = body->getLocEnd();
2061 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002062 // Now check for any return/continue/go statements within the @try.
2063 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002064 }
2065
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002066 return 0;
2067}
2068
2069// This can't be done with ReplaceStmt(S, ThrowExpr), since
2070// the throw expression is typically a message expression that's already
2071// been rewritten! (which implies the SourceLocation's are invalid).
2072Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2073 // Get the start location and compute the semi location.
2074 SourceLocation startLoc = S->getLocStart();
2075 const char *startBuf = SM->getCharacterData(startLoc);
2076
2077 assert((*startBuf == '@') && "bogus @throw location");
2078
2079 std::string buf;
2080 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2081 if (S->getThrowExpr())
2082 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002083 else
2084 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002085
2086 // handle "@ throw" correctly.
2087 const char *wBuf = strchr(startBuf, 'w');
2088 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2089 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2090
2091 const char *semiBuf = strchr(startBuf, ';');
2092 assert((*semiBuf == ';') && "@throw: can't find ';'");
2093 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002094 if (S->getThrowExpr())
2095 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002096 return 0;
2097}
2098
2099Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2100 // Create a new string expression.
2101 QualType StrType = Context->getPointerType(Context->CharTy);
2102 std::string StrEncoding;
2103 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2104 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2105 StringLiteral::Ascii, false,
2106 StrType, SourceLocation());
2107 ReplaceStmt(Exp, Replacement);
2108
2109 // Replace this subexpr in the parent.
2110 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2111 return Replacement;
2112}
2113
2114Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2115 if (!SelGetUidFunctionDecl)
2116 SynthSelGetUidFunctionDecl();
2117 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2118 // Create a call to sel_registerName("selName").
2119 SmallVector<Expr*, 8> SelExprs;
2120 QualType argType = Context->getPointerType(Context->CharTy);
2121 SelExprs.push_back(StringLiteral::Create(*Context,
2122 Exp->getSelector().getAsString(),
2123 StringLiteral::Ascii, false,
2124 argType, SourceLocation()));
2125 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2126 &SelExprs[0], SelExprs.size());
2127 ReplaceStmt(Exp, SelExp);
2128 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2129 return SelExp;
2130}
2131
2132CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2133 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2134 SourceLocation EndLoc) {
2135 // Get the type, we will need to reference it in a couple spots.
2136 QualType msgSendType = FD->getType();
2137
2138 // Create a reference to the objc_msgSend() declaration.
2139 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002140 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002141
2142 // Now, we cast the reference to a pointer to the objc_msgSend type.
2143 QualType pToFunc = Context->getPointerType(msgSendType);
2144 ImplicitCastExpr *ICE =
2145 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2146 DRE, 0, VK_RValue);
2147
2148 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2149
2150 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002151 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002152 FT->getCallResultType(*Context),
2153 VK_RValue, EndLoc);
2154 return Exp;
2155}
2156
2157static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2158 const char *&startRef, const char *&endRef) {
2159 while (startBuf < endBuf) {
2160 if (*startBuf == '<')
2161 startRef = startBuf; // mark the start.
2162 if (*startBuf == '>') {
2163 if (startRef && *startRef == '<') {
2164 endRef = startBuf; // mark the end.
2165 return true;
2166 }
2167 return false;
2168 }
2169 startBuf++;
2170 }
2171 return false;
2172}
2173
2174static void scanToNextArgument(const char *&argRef) {
2175 int angle = 0;
2176 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2177 if (*argRef == '<')
2178 angle++;
2179 else if (*argRef == '>')
2180 angle--;
2181 argRef++;
2182 }
2183 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2184}
2185
2186bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2187 if (T->isObjCQualifiedIdType())
2188 return true;
2189 if (const PointerType *PT = T->getAs<PointerType>()) {
2190 if (PT->getPointeeType()->isObjCQualifiedIdType())
2191 return true;
2192 }
2193 if (T->isObjCObjectPointerType()) {
2194 T = T->getPointeeType();
2195 return T->isObjCQualifiedInterfaceType();
2196 }
2197 if (T->isArrayType()) {
2198 QualType ElemTy = Context->getBaseElementType(T);
2199 return needToScanForQualifiers(ElemTy);
2200 }
2201 return false;
2202}
2203
2204void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2205 QualType Type = E->getType();
2206 if (needToScanForQualifiers(Type)) {
2207 SourceLocation Loc, EndLoc;
2208
2209 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2210 Loc = ECE->getLParenLoc();
2211 EndLoc = ECE->getRParenLoc();
2212 } else {
2213 Loc = E->getLocStart();
2214 EndLoc = E->getLocEnd();
2215 }
2216 // This will defend against trying to rewrite synthesized expressions.
2217 if (Loc.isInvalid() || EndLoc.isInvalid())
2218 return;
2219
2220 const char *startBuf = SM->getCharacterData(Loc);
2221 const char *endBuf = SM->getCharacterData(EndLoc);
2222 const char *startRef = 0, *endRef = 0;
2223 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2224 // Get the locations of the startRef, endRef.
2225 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2226 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2227 // Comment out the protocol references.
2228 InsertText(LessLoc, "/*");
2229 InsertText(GreaterLoc, "*/");
2230 }
2231 }
2232}
2233
2234void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2235 SourceLocation Loc;
2236 QualType Type;
2237 const FunctionProtoType *proto = 0;
2238 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2239 Loc = VD->getLocation();
2240 Type = VD->getType();
2241 }
2242 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2243 Loc = FD->getLocation();
2244 // Check for ObjC 'id' and class types that have been adorned with protocol
2245 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2246 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2247 assert(funcType && "missing function type");
2248 proto = dyn_cast<FunctionProtoType>(funcType);
2249 if (!proto)
2250 return;
2251 Type = proto->getResultType();
2252 }
2253 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2254 Loc = FD->getLocation();
2255 Type = FD->getType();
2256 }
2257 else
2258 return;
2259
2260 if (needToScanForQualifiers(Type)) {
2261 // Since types are unique, we need to scan the buffer.
2262
2263 const char *endBuf = SM->getCharacterData(Loc);
2264 const char *startBuf = endBuf;
2265 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2266 startBuf--; // scan backward (from the decl location) for return type.
2267 const char *startRef = 0, *endRef = 0;
2268 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2269 // Get the locations of the startRef, endRef.
2270 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2271 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2272 // Comment out the protocol references.
2273 InsertText(LessLoc, "/*");
2274 InsertText(GreaterLoc, "*/");
2275 }
2276 }
2277 if (!proto)
2278 return; // most likely, was a variable
2279 // Now check arguments.
2280 const char *startBuf = SM->getCharacterData(Loc);
2281 const char *startFuncBuf = startBuf;
2282 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2283 if (needToScanForQualifiers(proto->getArgType(i))) {
2284 // Since types are unique, we need to scan the buffer.
2285
2286 const char *endBuf = startBuf;
2287 // scan forward (from the decl location) for argument types.
2288 scanToNextArgument(endBuf);
2289 const char *startRef = 0, *endRef = 0;
2290 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2291 // Get the locations of the startRef, endRef.
2292 SourceLocation LessLoc =
2293 Loc.getLocWithOffset(startRef-startFuncBuf);
2294 SourceLocation GreaterLoc =
2295 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2296 // Comment out the protocol references.
2297 InsertText(LessLoc, "/*");
2298 InsertText(GreaterLoc, "*/");
2299 }
2300 startBuf = ++endBuf;
2301 }
2302 else {
2303 // If the function name is derived from a macro expansion, then the
2304 // argument buffer will not follow the name. Need to speak with Chris.
2305 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2306 startBuf++; // scan forward (from the decl location) for argument types.
2307 startBuf++;
2308 }
2309 }
2310}
2311
2312void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2313 QualType QT = ND->getType();
2314 const Type* TypePtr = QT->getAs<Type>();
2315 if (!isa<TypeOfExprType>(TypePtr))
2316 return;
2317 while (isa<TypeOfExprType>(TypePtr)) {
2318 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2319 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2320 TypePtr = QT->getAs<Type>();
2321 }
2322 // FIXME. This will not work for multiple declarators; as in:
2323 // __typeof__(a) b,c,d;
2324 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2325 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2326 const char *startBuf = SM->getCharacterData(DeclLoc);
2327 if (ND->getInit()) {
2328 std::string Name(ND->getNameAsString());
2329 TypeAsString += " " + Name + " = ";
2330 Expr *E = ND->getInit();
2331 SourceLocation startLoc;
2332 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2333 startLoc = ECE->getLParenLoc();
2334 else
2335 startLoc = E->getLocStart();
2336 startLoc = SM->getExpansionLoc(startLoc);
2337 const char *endBuf = SM->getCharacterData(startLoc);
2338 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2339 }
2340 else {
2341 SourceLocation X = ND->getLocEnd();
2342 X = SM->getExpansionLoc(X);
2343 const char *endBuf = SM->getCharacterData(X);
2344 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2345 }
2346}
2347
2348// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2349void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2350 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2351 SmallVector<QualType, 16> ArgTys;
2352 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2353 QualType getFuncType =
2354 getSimpleFunctionType(Context->getObjCSelType(), &ArgTys[0], ArgTys.size());
2355 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002356 SourceLocation(),
2357 SourceLocation(),
2358 SelGetUidIdent, getFuncType, 0,
2359 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002360}
2361
2362void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2363 // declared in <objc/objc.h>
2364 if (FD->getIdentifier() &&
2365 FD->getName() == "sel_registerName") {
2366 SelGetUidFunctionDecl = FD;
2367 return;
2368 }
2369 RewriteObjCQualifiedInterfaceTypes(FD);
2370}
2371
2372void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2373 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2374 const char *argPtr = TypeString.c_str();
2375 if (!strchr(argPtr, '^')) {
2376 Str += TypeString;
2377 return;
2378 }
2379 while (*argPtr) {
2380 Str += (*argPtr == '^' ? '*' : *argPtr);
2381 argPtr++;
2382 }
2383}
2384
2385// FIXME. Consolidate this routine with RewriteBlockPointerType.
2386void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2387 ValueDecl *VD) {
2388 QualType Type = VD->getType();
2389 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2390 const char *argPtr = TypeString.c_str();
2391 int paren = 0;
2392 while (*argPtr) {
2393 switch (*argPtr) {
2394 case '(':
2395 Str += *argPtr;
2396 paren++;
2397 break;
2398 case ')':
2399 Str += *argPtr;
2400 paren--;
2401 break;
2402 case '^':
2403 Str += '*';
2404 if (paren == 1)
2405 Str += VD->getNameAsString();
2406 break;
2407 default:
2408 Str += *argPtr;
2409 break;
2410 }
2411 argPtr++;
2412 }
2413}
2414
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002415void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2416 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2417 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2418 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2419 if (!proto)
2420 return;
2421 QualType Type = proto->getResultType();
2422 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2423 FdStr += " ";
2424 FdStr += FD->getName();
2425 FdStr += "(";
2426 unsigned numArgs = proto->getNumArgs();
2427 for (unsigned i = 0; i < numArgs; i++) {
2428 QualType ArgType = proto->getArgType(i);
2429 RewriteBlockPointerType(FdStr, ArgType);
2430 if (i+1 < numArgs)
2431 FdStr += ", ";
2432 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002433 if (FD->isVariadic()) {
2434 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2435 }
2436 else
2437 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002438 InsertText(FunLocStart, FdStr);
2439}
2440
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002441// SynthSuperContructorFunctionDecl - id __rw_objc_super(id obj, id super);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002442void RewriteModernObjC::SynthSuperContructorFunctionDecl() {
2443 if (SuperContructorFunctionDecl)
2444 return;
2445 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2446 SmallVector<QualType, 16> ArgTys;
2447 QualType argT = Context->getObjCIdType();
2448 assert(!argT.isNull() && "Can't find 'id' type");
2449 ArgTys.push_back(argT);
2450 ArgTys.push_back(argT);
2451 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2452 &ArgTys[0], ArgTys.size());
2453 SuperContructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002454 SourceLocation(),
2455 SourceLocation(),
2456 msgSendIdent, msgSendType,
2457 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002458}
2459
2460// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2461void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2462 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2463 SmallVector<QualType, 16> ArgTys;
2464 QualType argT = Context->getObjCIdType();
2465 assert(!argT.isNull() && "Can't find 'id' type");
2466 ArgTys.push_back(argT);
2467 argT = Context->getObjCSelType();
2468 assert(!argT.isNull() && "Can't find 'SEL' type");
2469 ArgTys.push_back(argT);
2470 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2471 &ArgTys[0], ArgTys.size(),
2472 true /*isVariadic*/);
2473 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002474 SourceLocation(),
2475 SourceLocation(),
2476 msgSendIdent, msgSendType, 0,
2477 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002478}
2479
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002480// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002481void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2482 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002483 SmallVector<QualType, 2> ArgTys;
2484 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002485 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002486 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002487 true /*isVariadic*/);
2488 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002489 SourceLocation(),
2490 SourceLocation(),
2491 msgSendIdent, msgSendType, 0,
2492 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002493}
2494
2495// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2496void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2497 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2498 SmallVector<QualType, 16> ArgTys;
2499 QualType argT = Context->getObjCIdType();
2500 assert(!argT.isNull() && "Can't find 'id' type");
2501 ArgTys.push_back(argT);
2502 argT = Context->getObjCSelType();
2503 assert(!argT.isNull() && "Can't find 'SEL' type");
2504 ArgTys.push_back(argT);
2505 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2506 &ArgTys[0], ArgTys.size(),
2507 true /*isVariadic*/);
2508 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002509 SourceLocation(),
2510 SourceLocation(),
2511 msgSendIdent, msgSendType, 0,
2512 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002513}
2514
2515// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002516// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002517void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2518 IdentifierInfo *msgSendIdent =
2519 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002520 SmallVector<QualType, 2> ArgTys;
2521 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002522 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002523 &ArgTys[0], 1,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002524 true /*isVariadic*/);
2525 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2526 SourceLocation(),
2527 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002528 msgSendIdent,
2529 msgSendType, 0,
2530 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002531}
2532
2533// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2534void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2535 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2536 SmallVector<QualType, 16> ArgTys;
2537 QualType argT = Context->getObjCIdType();
2538 assert(!argT.isNull() && "Can't find 'id' type");
2539 ArgTys.push_back(argT);
2540 argT = Context->getObjCSelType();
2541 assert(!argT.isNull() && "Can't find 'SEL' type");
2542 ArgTys.push_back(argT);
2543 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2544 &ArgTys[0], ArgTys.size(),
2545 true /*isVariadic*/);
2546 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002547 SourceLocation(),
2548 SourceLocation(),
2549 msgSendIdent, msgSendType, 0,
2550 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002551}
2552
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002553// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002554void RewriteModernObjC::SynthGetClassFunctionDecl() {
2555 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2556 SmallVector<QualType, 16> ArgTys;
2557 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002558 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002559 &ArgTys[0], ArgTys.size());
2560 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002561 SourceLocation(),
2562 SourceLocation(),
2563 getClassIdent, getClassType, 0,
2564 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002565}
2566
2567// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2568void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2569 IdentifierInfo *getSuperClassIdent =
2570 &Context->Idents.get("class_getSuperclass");
2571 SmallVector<QualType, 16> ArgTys;
2572 ArgTys.push_back(Context->getObjCClassType());
2573 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2574 &ArgTys[0], ArgTys.size());
2575 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2576 SourceLocation(),
2577 SourceLocation(),
2578 getSuperClassIdent,
2579 getClassType, 0,
Chad Rosiere3b29882013-01-04 22:40:33 +00002580 SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002581}
2582
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002583// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002584void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2585 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2586 SmallVector<QualType, 16> ArgTys;
2587 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002588 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002589 &ArgTys[0], ArgTys.size());
2590 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002591 SourceLocation(),
2592 SourceLocation(),
2593 getClassIdent, getClassType,
2594 0, SC_Extern, SC_None);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002595}
2596
2597Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2598 QualType strType = getConstantStringStructType();
2599
2600 std::string S = "__NSConstantStringImpl_";
2601
2602 std::string tmpName = InFileName;
2603 unsigned i;
2604 for (i=0; i < tmpName.length(); i++) {
2605 char c = tmpName.at(i);
2606 // replace any non alphanumeric characters with '_'.
2607 if (!isalpha(c) && (c < '0' || c > '9'))
2608 tmpName[i] = '_';
2609 }
2610 S += tmpName;
2611 S += "_";
2612 S += utostr(NumObjCStringLiterals++);
2613
2614 Preamble += "static __NSConstantStringImpl " + S;
2615 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2616 Preamble += "0x000007c8,"; // utf8_str
2617 // The pretty printer for StringLiteral handles escape characters properly.
2618 std::string prettyBufS;
2619 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002620 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002621 Preamble += prettyBuf.str();
2622 Preamble += ",";
2623 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2624
2625 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2626 SourceLocation(), &Context->Idents.get(S),
2627 strType, 0, SC_Static, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00002628 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002629 SourceLocation());
2630 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2631 Context->getPointerType(DRE->getType()),
2632 VK_RValue, OK_Ordinary,
2633 SourceLocation());
2634 // cast to NSConstantString *
2635 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2636 CK_CPointerToObjCPointerCast, Unop);
2637 ReplaceStmt(Exp, cast);
2638 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2639 return cast;
2640}
2641
Fariborz Jahanian55947042012-03-27 20:17:30 +00002642Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2643 unsigned IntSize =
2644 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2645
2646 Expr *FlagExp = IntegerLiteral::Create(*Context,
2647 llvm::APInt(IntSize, Exp->getValue()),
2648 Context->IntTy, Exp->getLocation());
2649 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2650 CK_BitCast, FlagExp);
2651 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2652 cast);
2653 ReplaceStmt(Exp, PE);
2654 return PE;
2655}
2656
Patrick Beardeb382ec2012-04-19 00:25:12 +00002657Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002658 // synthesize declaration of helper functions needed in this routine.
2659 if (!SelGetUidFunctionDecl)
2660 SynthSelGetUidFunctionDecl();
2661 // use objc_msgSend() for all.
2662 if (!MsgSendFunctionDecl)
2663 SynthMsgSendFunctionDecl();
2664 if (!GetClassFunctionDecl)
2665 SynthGetClassFunctionDecl();
2666
2667 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2668 SourceLocation StartLoc = Exp->getLocStart();
2669 SourceLocation EndLoc = Exp->getLocEnd();
2670
2671 // Synthesize a call to objc_msgSend().
2672 SmallVector<Expr*, 4> MsgExprs;
2673 SmallVector<Expr*, 4> ClsExprs;
2674 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002675
Patrick Beardeb382ec2012-04-19 00:25:12 +00002676 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2677 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2678 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002679
Patrick Beardeb382ec2012-04-19 00:25:12 +00002680 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002681 ClsExprs.push_back(StringLiteral::Create(*Context,
2682 clsName->getName(),
2683 StringLiteral::Ascii, false,
2684 argType, SourceLocation()));
2685 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2686 &ClsExprs[0],
2687 ClsExprs.size(),
2688 StartLoc, EndLoc);
2689 MsgExprs.push_back(Cls);
2690
Patrick Beardeb382ec2012-04-19 00:25:12 +00002691 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002692 // it will be the 2nd argument.
2693 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002694 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002695 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002696 StringLiteral::Ascii, false,
2697 argType, SourceLocation()));
2698 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2699 &SelExprs[0], SelExprs.size(),
2700 StartLoc, EndLoc);
2701 MsgExprs.push_back(SelExp);
2702
Patrick Beardeb382ec2012-04-19 00:25:12 +00002703 // User provided sub-expression is the 3rd, and last, argument.
2704 Expr *subExpr = Exp->getSubExpr();
2705 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002706 QualType type = ICE->getType();
2707 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2708 CastKind CK = CK_BitCast;
2709 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2710 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002711 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002712 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002713 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002714
2715 SmallVector<QualType, 4> ArgTypes;
2716 ArgTypes.push_back(Context->getObjCIdType());
2717 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002718 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2719 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002720 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002721
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002722 QualType returnType = Exp->getType();
2723 // Get the type, we will need to reference it in a couple spots.
2724 QualType msgSendType = MsgSendFlavor->getType();
2725
2726 // Create a reference to the objc_msgSend() declaration.
2727 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2728 VK_LValue, SourceLocation());
2729
2730 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002731 Context->getPointerType(Context->VoidTy),
2732 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002733
2734 // Now do the "normal" pointer to function cast.
2735 QualType castType =
Patrick Beardeb382ec2012-04-19 00:25:12 +00002736 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2737 BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002738 castType = Context->getPointerType(castType);
2739 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2740 cast);
2741
2742 // Don't forget the parens to enforce the proper binding.
2743 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2744
2745 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002746 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002747 FT->getResultType(), VK_RValue,
2748 EndLoc);
2749 ReplaceStmt(Exp, CE);
2750 return CE;
2751}
2752
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002753Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2754 // synthesize declaration of helper functions needed in this routine.
2755 if (!SelGetUidFunctionDecl)
2756 SynthSelGetUidFunctionDecl();
2757 // use objc_msgSend() for all.
2758 if (!MsgSendFunctionDecl)
2759 SynthMsgSendFunctionDecl();
2760 if (!GetClassFunctionDecl)
2761 SynthGetClassFunctionDecl();
2762
2763 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2764 SourceLocation StartLoc = Exp->getLocStart();
2765 SourceLocation EndLoc = Exp->getLocEnd();
2766
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002767 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002768 QualType IntQT = Context->IntTy;
2769 QualType NSArrayFType =
2770 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002771 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002772 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2773 DeclRefExpr *NSArrayDRE =
2774 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2775 SourceLocation());
2776
2777 SmallVector<Expr*, 16> InitExprs;
2778 unsigned NumElements = Exp->getNumElements();
2779 unsigned UnsignedIntSize =
2780 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2781 Expr *count = IntegerLiteral::Create(*Context,
2782 llvm::APInt(UnsignedIntSize, NumElements),
2783 Context->UnsignedIntTy, SourceLocation());
2784 InitExprs.push_back(count);
2785 for (unsigned i = 0; i < NumElements; i++)
2786 InitExprs.push_back(Exp->getElement(i));
2787 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002788 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002789 NSArrayFType, VK_LValue, SourceLocation());
2790
2791 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2792 SourceLocation(),
2793 &Context->Idents.get("arr"),
2794 Context->getPointerType(Context->VoidPtrTy), 0,
2795 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002796 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002797 MemberExpr *ArrayLiteralME =
2798 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2799 SourceLocation(),
2800 ARRFD->getType(), VK_LValue,
2801 OK_Ordinary);
2802 QualType ConstIdT = Context->getObjCIdType().withConst();
2803 CStyleCastExpr * ArrayLiteralObjects =
2804 NoTypeInfoCStyleCastExpr(Context,
2805 Context->getPointerType(ConstIdT),
2806 CK_BitCast,
2807 ArrayLiteralME);
2808
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002809 // Synthesize a call to objc_msgSend().
2810 SmallVector<Expr*, 32> MsgExprs;
2811 SmallVector<Expr*, 4> ClsExprs;
2812 QualType argType = Context->getPointerType(Context->CharTy);
2813 QualType expType = Exp->getType();
2814
2815 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2816 ObjCInterfaceDecl *Class =
2817 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2818
2819 IdentifierInfo *clsName = Class->getIdentifier();
2820 ClsExprs.push_back(StringLiteral::Create(*Context,
2821 clsName->getName(),
2822 StringLiteral::Ascii, false,
2823 argType, SourceLocation()));
2824 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2825 &ClsExprs[0],
2826 ClsExprs.size(),
2827 StartLoc, EndLoc);
2828 MsgExprs.push_back(Cls);
2829
2830 // Create a call to sel_registerName("arrayWithObjects:count:").
2831 // it will be the 2nd argument.
2832 SmallVector<Expr*, 4> SelExprs;
2833 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2834 SelExprs.push_back(StringLiteral::Create(*Context,
2835 ArrayMethod->getSelector().getAsString(),
2836 StringLiteral::Ascii, false,
2837 argType, SourceLocation()));
2838 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2839 &SelExprs[0], SelExprs.size(),
2840 StartLoc, EndLoc);
2841 MsgExprs.push_back(SelExp);
2842
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002843 // (const id [])objects
2844 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002845
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002846 // (NSUInteger)cnt
2847 Expr *cnt = IntegerLiteral::Create(*Context,
2848 llvm::APInt(UnsignedIntSize, NumElements),
2849 Context->UnsignedIntTy, SourceLocation());
2850 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002851
2852
2853 SmallVector<QualType, 4> ArgTypes;
2854 ArgTypes.push_back(Context->getObjCIdType());
2855 ArgTypes.push_back(Context->getObjCSelType());
2856 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2857 E = ArrayMethod->param_end(); PI != E; ++PI)
2858 ArgTypes.push_back((*PI)->getType());
2859
2860 QualType returnType = Exp->getType();
2861 // Get the type, we will need to reference it in a couple spots.
2862 QualType msgSendType = MsgSendFlavor->getType();
2863
2864 // Create a reference to the objc_msgSend() declaration.
2865 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2866 VK_LValue, SourceLocation());
2867
2868 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2869 Context->getPointerType(Context->VoidTy),
2870 CK_BitCast, DRE);
2871
2872 // Now do the "normal" pointer to function cast.
2873 QualType castType =
2874 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
2875 ArrayMethod->isVariadic());
2876 castType = Context->getPointerType(castType);
2877 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2878 cast);
2879
2880 // Don't forget the parens to enforce the proper binding.
2881 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2882
2883 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002884 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002885 FT->getResultType(), VK_RValue,
2886 EndLoc);
2887 ReplaceStmt(Exp, CE);
2888 return CE;
2889}
2890
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002891Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2892 // synthesize declaration of helper functions needed in this routine.
2893 if (!SelGetUidFunctionDecl)
2894 SynthSelGetUidFunctionDecl();
2895 // use objc_msgSend() for all.
2896 if (!MsgSendFunctionDecl)
2897 SynthMsgSendFunctionDecl();
2898 if (!GetClassFunctionDecl)
2899 SynthGetClassFunctionDecl();
2900
2901 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2902 SourceLocation StartLoc = Exp->getLocStart();
2903 SourceLocation EndLoc = Exp->getLocEnd();
2904
2905 // Build the expression: __NSContainer_literal(int, ...).arr
2906 QualType IntQT = Context->IntTy;
2907 QualType NSDictFType =
2908 getSimpleFunctionType(Context->VoidTy, &IntQT, 1, true);
2909 std::string NSDictFName("__NSContainer_literal");
2910 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2911 DeclRefExpr *NSDictDRE =
2912 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2913 SourceLocation());
2914
2915 SmallVector<Expr*, 16> KeyExprs;
2916 SmallVector<Expr*, 16> ValueExprs;
2917
2918 unsigned NumElements = Exp->getNumElements();
2919 unsigned UnsignedIntSize =
2920 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2921 Expr *count = IntegerLiteral::Create(*Context,
2922 llvm::APInt(UnsignedIntSize, NumElements),
2923 Context->UnsignedIntTy, SourceLocation());
2924 KeyExprs.push_back(count);
2925 ValueExprs.push_back(count);
2926 for (unsigned i = 0; i < NumElements; i++) {
2927 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2928 KeyExprs.push_back(Element.Key);
2929 ValueExprs.push_back(Element.Value);
2930 }
2931
2932 // (const id [])objects
2933 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002934 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002935 NSDictFType, VK_LValue, SourceLocation());
2936
2937 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2938 SourceLocation(),
2939 &Context->Idents.get("arr"),
2940 Context->getPointerType(Context->VoidPtrTy), 0,
2941 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002942 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002943 MemberExpr *DictLiteralValueME =
2944 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2945 SourceLocation(),
2946 ARRFD->getType(), VK_LValue,
2947 OK_Ordinary);
2948 QualType ConstIdT = Context->getObjCIdType().withConst();
2949 CStyleCastExpr * DictValueObjects =
2950 NoTypeInfoCStyleCastExpr(Context,
2951 Context->getPointerType(ConstIdT),
2952 CK_BitCast,
2953 DictLiteralValueME);
2954 // (const id <NSCopying> [])keys
2955 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002956 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002957 NSDictFType, VK_LValue, SourceLocation());
2958
2959 MemberExpr *DictLiteralKeyME =
2960 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2961 SourceLocation(),
2962 ARRFD->getType(), VK_LValue,
2963 OK_Ordinary);
2964
2965 CStyleCastExpr * DictKeyObjects =
2966 NoTypeInfoCStyleCastExpr(Context,
2967 Context->getPointerType(ConstIdT),
2968 CK_BitCast,
2969 DictLiteralKeyME);
2970
2971
2972
2973 // Synthesize a call to objc_msgSend().
2974 SmallVector<Expr*, 32> MsgExprs;
2975 SmallVector<Expr*, 4> ClsExprs;
2976 QualType argType = Context->getPointerType(Context->CharTy);
2977 QualType expType = Exp->getType();
2978
2979 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2980 ObjCInterfaceDecl *Class =
2981 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2982
2983 IdentifierInfo *clsName = Class->getIdentifier();
2984 ClsExprs.push_back(StringLiteral::Create(*Context,
2985 clsName->getName(),
2986 StringLiteral::Ascii, false,
2987 argType, SourceLocation()));
2988 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2989 &ClsExprs[0],
2990 ClsExprs.size(),
2991 StartLoc, EndLoc);
2992 MsgExprs.push_back(Cls);
2993
2994 // Create a call to sel_registerName("arrayWithObjects:count:").
2995 // it will be the 2nd argument.
2996 SmallVector<Expr*, 4> SelExprs;
2997 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2998 SelExprs.push_back(StringLiteral::Create(*Context,
2999 DictMethod->getSelector().getAsString(),
3000 StringLiteral::Ascii, false,
3001 argType, SourceLocation()));
3002 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3003 &SelExprs[0], SelExprs.size(),
3004 StartLoc, EndLoc);
3005 MsgExprs.push_back(SelExp);
3006
3007 // (const id [])objects
3008 MsgExprs.push_back(DictValueObjects);
3009
3010 // (const id <NSCopying> [])keys
3011 MsgExprs.push_back(DictKeyObjects);
3012
3013 // (NSUInteger)cnt
3014 Expr *cnt = IntegerLiteral::Create(*Context,
3015 llvm::APInt(UnsignedIntSize, NumElements),
3016 Context->UnsignedIntTy, SourceLocation());
3017 MsgExprs.push_back(cnt);
3018
3019
3020 SmallVector<QualType, 8> ArgTypes;
3021 ArgTypes.push_back(Context->getObjCIdType());
3022 ArgTypes.push_back(Context->getObjCSelType());
3023 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3024 E = DictMethod->param_end(); PI != E; ++PI) {
3025 QualType T = (*PI)->getType();
3026 if (const PointerType* PT = T->getAs<PointerType>()) {
3027 QualType PointeeTy = PT->getPointeeType();
3028 convertToUnqualifiedObjCType(PointeeTy);
3029 T = Context->getPointerType(PointeeTy);
3030 }
3031 ArgTypes.push_back(T);
3032 }
3033
3034 QualType returnType = Exp->getType();
3035 // Get the type, we will need to reference it in a couple spots.
3036 QualType msgSendType = MsgSendFlavor->getType();
3037
3038 // Create a reference to the objc_msgSend() declaration.
3039 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3040 VK_LValue, SourceLocation());
3041
3042 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3043 Context->getPointerType(Context->VoidTy),
3044 CK_BitCast, DRE);
3045
3046 // Now do the "normal" pointer to function cast.
3047 QualType castType =
3048 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3049 DictMethod->isVariadic());
3050 castType = Context->getPointerType(castType);
3051 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3052 cast);
3053
3054 // Don't forget the parens to enforce the proper binding.
3055 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3056
3057 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003058 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003059 FT->getResultType(), VK_RValue,
3060 EndLoc);
3061 ReplaceStmt(Exp, CE);
3062 return CE;
3063}
3064
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003065// struct __rw_objc_super {
3066// struct objc_object *object; struct objc_object *superClass;
3067// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003068QualType RewriteModernObjC::getSuperStructType() {
3069 if (!SuperStructDecl) {
3070 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3071 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003072 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003073 QualType FieldTypes[2];
3074
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003075 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003076 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003077 // struct objc_object *superClass;
3078 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003079
3080 // Create fields
3081 for (unsigned i = 0; i < 2; ++i) {
3082 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3083 SourceLocation(),
3084 SourceLocation(), 0,
3085 FieldTypes[i], 0,
3086 /*BitWidth=*/0,
3087 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003088 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003089 }
3090
3091 SuperStructDecl->completeDefinition();
3092 }
3093 return Context->getTagDeclType(SuperStructDecl);
3094}
3095
3096QualType RewriteModernObjC::getConstantStringStructType() {
3097 if (!ConstantStringDecl) {
3098 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3099 SourceLocation(), SourceLocation(),
3100 &Context->Idents.get("__NSConstantStringImpl"));
3101 QualType FieldTypes[4];
3102
3103 // struct objc_object *receiver;
3104 FieldTypes[0] = Context->getObjCIdType();
3105 // int flags;
3106 FieldTypes[1] = Context->IntTy;
3107 // char *str;
3108 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3109 // long length;
3110 FieldTypes[3] = Context->LongTy;
3111
3112 // Create fields
3113 for (unsigned i = 0; i < 4; ++i) {
3114 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3115 ConstantStringDecl,
3116 SourceLocation(),
3117 SourceLocation(), 0,
3118 FieldTypes[i], 0,
3119 /*BitWidth=*/0,
3120 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003121 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003122 }
3123
3124 ConstantStringDecl->completeDefinition();
3125 }
3126 return Context->getTagDeclType(ConstantStringDecl);
3127}
3128
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003129/// getFunctionSourceLocation - returns start location of a function
3130/// definition. Complication arises when function has declared as
3131/// extern "C" or extern "C" {...}
3132static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3133 FunctionDecl *FD) {
3134 if (FD->isExternC() && !FD->isMain()) {
3135 const DeclContext *DC = FD->getDeclContext();
3136 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3137 // if it is extern "C" {...}, return function decl's own location.
3138 if (!LSD->getRBraceLoc().isValid())
3139 return LSD->getExternLoc();
3140 }
3141 if (FD->getStorageClassAsWritten() != SC_None)
3142 R.RewriteBlockLiteralFunctionDecl(FD);
3143 return FD->getTypeSpecStartLoc();
3144}
3145
Fariborz Jahanian96205962012-11-06 17:30:23 +00003146void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3147
3148 SourceLocation Location = D->getLocation();
3149
3150 if (Location.isFileID()) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003151 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003152 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3153 LineString += utostr(PLoc.getLine());
3154 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003155 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003156 if (isa<ObjCMethodDecl>(D))
3157 LineString += "\"";
3158 else LineString += "\"\n";
3159
3160 Location = D->getLocStart();
3161 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3162 if (FD->isExternC() && !FD->isMain()) {
3163 const DeclContext *DC = FD->getDeclContext();
3164 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3165 // if it is extern "C" {...}, return function decl's own location.
3166 if (!LSD->getRBraceLoc().isValid())
3167 Location = LSD->getExternLoc();
3168 }
3169 }
3170 InsertText(Location, LineString);
3171 }
3172}
3173
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003174/// SynthMsgSendStretCallExpr - This routine translates message expression
3175/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3176/// nil check on receiver must be performed before calling objc_msgSend_stret.
3177/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3178/// msgSendType - function type of objc_msgSend_stret(...)
3179/// returnType - Result type of the method being synthesized.
3180/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3181/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3182/// starting with receiver.
3183/// Method - Method being rewritten.
3184Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3185 QualType msgSendType,
3186 QualType returnType,
3187 SmallVectorImpl<QualType> &ArgTypes,
3188 SmallVectorImpl<Expr*> &MsgExprs,
3189 ObjCMethodDecl *Method) {
3190 // Now do the "normal" pointer to function cast.
3191 QualType castType = getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3192 Method ? Method->isVariadic() : false);
3193 castType = Context->getPointerType(castType);
3194
3195 // build type for containing the objc_msgSend_stret object.
3196 static unsigned stretCount=0;
3197 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003198 std::string str =
3199 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3200 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003201 str += " {\n\t";
3202 str += name;
3203 str += "(id receiver, SEL sel";
3204 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003205 std::string ArgName = "arg"; ArgName += utostr(i);
3206 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3207 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003208 }
3209 // could be vararg.
3210 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003211 std::string ArgName = "arg"; ArgName += utostr(i);
3212 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3213 Context->getPrintingPolicy());
3214 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003215 }
3216
3217 str += ") {\n";
3218 str += "\t if (receiver == 0)\n";
3219 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3220 str += "\t else\n";
3221 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3222 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3223 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3224 str += ", arg"; str += utostr(i);
3225 }
3226 // could be vararg.
3227 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3228 str += ", arg"; str += utostr(i);
3229 }
3230
3231 str += ");\n";
3232 str += "\t}\n";
3233 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3234 str += " s;\n";
3235 str += "};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003236 SourceLocation FunLocStart;
3237 if (CurFunctionDef)
3238 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3239 else {
3240 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3241 FunLocStart = CurMethodDef->getLocStart();
3242 }
3243
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003244 InsertText(FunLocStart, str);
3245 ++stretCount;
3246
3247 // AST for __Stretn(receiver, args).s;
3248 IdentifierInfo *ID = &Context->Idents.get(name);
3249 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003250 SourceLocation(), ID, castType, 0,
3251 SC_Extern, SC_None, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003252 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3253 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003254 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003255 castType, VK_LValue, SourceLocation());
3256
3257 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3258 SourceLocation(),
3259 &Context->Idents.get("s"),
3260 returnType, 0,
3261 /*BitWidth=*/0, /*Mutable=*/true,
3262 ICIS_NoInit);
3263 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3264 FieldD->getType(), VK_LValue,
3265 OK_Ordinary);
3266
3267 return ME;
3268}
3269
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003270Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3271 SourceLocation StartLoc,
3272 SourceLocation EndLoc) {
3273 if (!SelGetUidFunctionDecl)
3274 SynthSelGetUidFunctionDecl();
3275 if (!MsgSendFunctionDecl)
3276 SynthMsgSendFunctionDecl();
3277 if (!MsgSendSuperFunctionDecl)
3278 SynthMsgSendSuperFunctionDecl();
3279 if (!MsgSendStretFunctionDecl)
3280 SynthMsgSendStretFunctionDecl();
3281 if (!MsgSendSuperStretFunctionDecl)
3282 SynthMsgSendSuperStretFunctionDecl();
3283 if (!MsgSendFpretFunctionDecl)
3284 SynthMsgSendFpretFunctionDecl();
3285 if (!GetClassFunctionDecl)
3286 SynthGetClassFunctionDecl();
3287 if (!GetSuperClassFunctionDecl)
3288 SynthGetSuperClassFunctionDecl();
3289 if (!GetMetaClassFunctionDecl)
3290 SynthGetMetaClassFunctionDecl();
3291
3292 // default to objc_msgSend().
3293 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3294 // May need to use objc_msgSend_stret() as well.
3295 FunctionDecl *MsgSendStretFlavor = 0;
3296 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3297 QualType resultType = mDecl->getResultType();
3298 if (resultType->isRecordType())
3299 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3300 else if (resultType->isRealFloatingType())
3301 MsgSendFlavor = MsgSendFpretFunctionDecl;
3302 }
3303
3304 // Synthesize a call to objc_msgSend().
3305 SmallVector<Expr*, 8> MsgExprs;
3306 switch (Exp->getReceiverKind()) {
3307 case ObjCMessageExpr::SuperClass: {
3308 MsgSendFlavor = MsgSendSuperFunctionDecl;
3309 if (MsgSendStretFlavor)
3310 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3311 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3312
3313 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3314
3315 SmallVector<Expr*, 4> InitExprs;
3316
3317 // set the receiver to self, the first argument to all methods.
3318 InitExprs.push_back(
3319 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3320 CK_BitCast,
3321 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003322 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003323 Context->getObjCIdType(),
3324 VK_RValue,
3325 SourceLocation()))
3326 ); // set the 'receiver'.
3327
3328 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3329 SmallVector<Expr*, 8> ClsExprs;
3330 QualType argType = Context->getPointerType(Context->CharTy);
3331 ClsExprs.push_back(StringLiteral::Create(*Context,
3332 ClassDecl->getIdentifier()->getName(),
3333 StringLiteral::Ascii, false,
3334 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003335 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003336 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3337 &ClsExprs[0],
3338 ClsExprs.size(),
3339 StartLoc,
3340 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003341 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003342 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003343 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3344 &ClsExprs[0], ClsExprs.size(),
3345 StartLoc, EndLoc);
3346
3347 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3348 // To turn off a warning, type-cast to 'id'
3349 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3350 NoTypeInfoCStyleCastExpr(Context,
3351 Context->getObjCIdType(),
3352 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003353 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003354 QualType superType = getSuperStructType();
3355 Expr *SuperRep;
3356
3357 if (LangOpts.MicrosoftExt) {
3358 SynthSuperContructorFunctionDecl();
3359 // Simulate a contructor call...
3360 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003361 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003362 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003363 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003364 superType, VK_LValue,
3365 SourceLocation());
3366 // The code for super is a little tricky to prevent collision with
3367 // the structure definition in the header. The rewriter has it's own
3368 // internal definition (__rw_objc_super) that is uses. This is why
3369 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003370 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003371 //
3372 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3373 Context->getPointerType(SuperRep->getType()),
3374 VK_RValue, OK_Ordinary,
3375 SourceLocation());
3376 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3377 Context->getPointerType(superType),
3378 CK_BitCast, SuperRep);
3379 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003380 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003381 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003382 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003383 SourceLocation());
3384 TypeSourceInfo *superTInfo
3385 = Context->getTrivialTypeSourceInfo(superType);
3386 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3387 superType, VK_LValue,
3388 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003389 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003390 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3391 Context->getPointerType(SuperRep->getType()),
3392 VK_RValue, OK_Ordinary,
3393 SourceLocation());
3394 }
3395 MsgExprs.push_back(SuperRep);
3396 break;
3397 }
3398
3399 case ObjCMessageExpr::Class: {
3400 SmallVector<Expr*, 8> ClsExprs;
3401 QualType argType = Context->getPointerType(Context->CharTy);
3402 ObjCInterfaceDecl *Class
3403 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3404 IdentifierInfo *clsName = Class->getIdentifier();
3405 ClsExprs.push_back(StringLiteral::Create(*Context,
3406 clsName->getName(),
3407 StringLiteral::Ascii, false,
3408 argType, SourceLocation()));
3409 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3410 &ClsExprs[0],
3411 ClsExprs.size(),
3412 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003413 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3414 Context->getObjCIdType(),
3415 CK_BitCast, Cls);
3416 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003417 break;
3418 }
3419
3420 case ObjCMessageExpr::SuperInstance:{
3421 MsgSendFlavor = MsgSendSuperFunctionDecl;
3422 if (MsgSendStretFlavor)
3423 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3424 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3425 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3426 SmallVector<Expr*, 4> InitExprs;
3427
3428 InitExprs.push_back(
3429 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3430 CK_BitCast,
3431 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003432 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003433 Context->getObjCIdType(),
3434 VK_RValue, SourceLocation()))
3435 ); // set the 'receiver'.
3436
3437 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3438 SmallVector<Expr*, 8> ClsExprs;
3439 QualType argType = Context->getPointerType(Context->CharTy);
3440 ClsExprs.push_back(StringLiteral::Create(*Context,
3441 ClassDecl->getIdentifier()->getName(),
3442 StringLiteral::Ascii, false, argType,
3443 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003444 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003445 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3446 &ClsExprs[0],
3447 ClsExprs.size(),
3448 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003449 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003450 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003451 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3452 &ClsExprs[0], ClsExprs.size(),
3453 StartLoc, EndLoc);
3454
3455 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3456 // To turn off a warning, type-cast to 'id'
3457 InitExprs.push_back(
3458 // set 'super class', using class_getSuperclass().
3459 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3460 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003461 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003462 QualType superType = getSuperStructType();
3463 Expr *SuperRep;
3464
3465 if (LangOpts.MicrosoftExt) {
3466 SynthSuperContructorFunctionDecl();
3467 // Simulate a contructor call...
3468 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperContructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003469 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003470 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003471 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003472 superType, VK_LValue, SourceLocation());
3473 // The code for super is a little tricky to prevent collision with
3474 // the structure definition in the header. The rewriter has it's own
3475 // internal definition (__rw_objc_super) that is uses. This is why
3476 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003477 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003478 //
3479 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3480 Context->getPointerType(SuperRep->getType()),
3481 VK_RValue, OK_Ordinary,
3482 SourceLocation());
3483 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3484 Context->getPointerType(superType),
3485 CK_BitCast, SuperRep);
3486 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003487 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003488 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003489 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003490 SourceLocation());
3491 TypeSourceInfo *superTInfo
3492 = Context->getTrivialTypeSourceInfo(superType);
3493 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3494 superType, VK_RValue, ILE,
3495 false);
3496 }
3497 MsgExprs.push_back(SuperRep);
3498 break;
3499 }
3500
3501 case ObjCMessageExpr::Instance: {
3502 // Remove all type-casts because it may contain objc-style types; e.g.
3503 // Foo<Proto> *.
3504 Expr *recExpr = Exp->getInstanceReceiver();
3505 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3506 recExpr = CE->getSubExpr();
3507 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3508 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3509 ? CK_BlockPointerToObjCPointerCast
3510 : CK_CPointerToObjCPointerCast;
3511
3512 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3513 CK, recExpr);
3514 MsgExprs.push_back(recExpr);
3515 break;
3516 }
3517 }
3518
3519 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3520 SmallVector<Expr*, 8> SelExprs;
3521 QualType argType = Context->getPointerType(Context->CharTy);
3522 SelExprs.push_back(StringLiteral::Create(*Context,
3523 Exp->getSelector().getAsString(),
3524 StringLiteral::Ascii, false,
3525 argType, SourceLocation()));
3526 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3527 &SelExprs[0], SelExprs.size(),
3528 StartLoc,
3529 EndLoc);
3530 MsgExprs.push_back(SelExp);
3531
3532 // Now push any user supplied arguments.
3533 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3534 Expr *userExpr = Exp->getArg(i);
3535 // Make all implicit casts explicit...ICE comes in handy:-)
3536 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3537 // Reuse the ICE type, it is exactly what the doctor ordered.
3538 QualType type = ICE->getType();
3539 if (needToScanForQualifiers(type))
3540 type = Context->getObjCIdType();
3541 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3542 (void)convertBlockPointerToFunctionPointer(type);
3543 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3544 CastKind CK;
3545 if (SubExpr->getType()->isIntegralType(*Context) &&
3546 type->isBooleanType()) {
3547 CK = CK_IntegralToBoolean;
3548 } else if (type->isObjCObjectPointerType()) {
3549 if (SubExpr->getType()->isBlockPointerType()) {
3550 CK = CK_BlockPointerToObjCPointerCast;
3551 } else if (SubExpr->getType()->isPointerType()) {
3552 CK = CK_CPointerToObjCPointerCast;
3553 } else {
3554 CK = CK_BitCast;
3555 }
3556 } else {
3557 CK = CK_BitCast;
3558 }
3559
3560 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3561 }
3562 // Make id<P...> cast into an 'id' cast.
3563 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3564 if (CE->getType()->isObjCQualifiedIdType()) {
3565 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3566 userExpr = CE->getSubExpr();
3567 CastKind CK;
3568 if (userExpr->getType()->isIntegralType(*Context)) {
3569 CK = CK_IntegralToPointer;
3570 } else if (userExpr->getType()->isBlockPointerType()) {
3571 CK = CK_BlockPointerToObjCPointerCast;
3572 } else if (userExpr->getType()->isPointerType()) {
3573 CK = CK_CPointerToObjCPointerCast;
3574 } else {
3575 CK = CK_BitCast;
3576 }
3577 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3578 CK, userExpr);
3579 }
3580 }
3581 MsgExprs.push_back(userExpr);
3582 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3583 // out the argument in the original expression (since we aren't deleting
3584 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3585 //Exp->setArg(i, 0);
3586 }
3587 // Generate the funky cast.
3588 CastExpr *cast;
3589 SmallVector<QualType, 8> ArgTypes;
3590 QualType returnType;
3591
3592 // Push 'id' and 'SEL', the 2 implicit arguments.
3593 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3594 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3595 else
3596 ArgTypes.push_back(Context->getObjCIdType());
3597 ArgTypes.push_back(Context->getObjCSelType());
3598 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3599 // Push any user argument types.
3600 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3601 E = OMD->param_end(); PI != E; ++PI) {
3602 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3603 ? Context->getObjCIdType()
3604 : (*PI)->getType();
3605 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3606 (void)convertBlockPointerToFunctionPointer(t);
3607 ArgTypes.push_back(t);
3608 }
3609 returnType = Exp->getType();
3610 convertToUnqualifiedObjCType(returnType);
3611 (void)convertBlockPointerToFunctionPointer(returnType);
3612 } else {
3613 returnType = Context->getObjCIdType();
3614 }
3615 // Get the type, we will need to reference it in a couple spots.
3616 QualType msgSendType = MsgSendFlavor->getType();
3617
3618 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003619 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003620 VK_LValue, SourceLocation());
3621
3622 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3623 // If we don't do this cast, we get the following bizarre warning/note:
3624 // xx.m:13: warning: function called through a non-compatible type
3625 // xx.m:13: note: if this code is reached, the program will abort
3626 cast = NoTypeInfoCStyleCastExpr(Context,
3627 Context->getPointerType(Context->VoidTy),
3628 CK_BitCast, DRE);
3629
3630 // Now do the "normal" pointer to function cast.
3631 QualType castType =
3632 getSimpleFunctionType(returnType, &ArgTypes[0], ArgTypes.size(),
3633 // If we don't have a method decl, force a variadic cast.
3634 Exp->getMethodDecl() ? Exp->getMethodDecl()->isVariadic() : true);
3635 castType = Context->getPointerType(castType);
3636 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3637 cast);
3638
3639 // Don't forget the parens to enforce the proper binding.
3640 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3641
3642 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003643 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3644 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003645 Stmt *ReplacingStmt = CE;
3646 if (MsgSendStretFlavor) {
3647 // We have the method which returns a struct/union. Must also generate
3648 // call to objc_msgSend_stret and hang both varieties on a conditional
3649 // expression which dictate which one to envoke depending on size of
3650 // method's return type.
3651
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003652 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3653 msgSendType, returnType,
3654 ArgTypes, MsgExprs,
3655 Exp->getMethodDecl());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003656
3657 // Build sizeof(returnType)
3658 UnaryExprOrTypeTraitExpr *sizeofExpr =
3659 new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
3660 Context->getTrivialTypeSourceInfo(returnType),
3661 Context->getSizeType(), SourceLocation(),
3662 SourceLocation());
3663 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3664 // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
3665 // For X86 it is more complicated and some kind of target specific routine
3666 // is needed to decide what to do.
3667 unsigned IntSize =
3668 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
3669 IntegerLiteral *limit = IntegerLiteral::Create(*Context,
3670 llvm::APInt(IntSize, 8),
3671 Context->IntTy,
3672 SourceLocation());
3673 BinaryOperator *lessThanExpr =
3674 new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
Lang Hamesbe9af122012-10-02 04:45:10 +00003675 VK_RValue, OK_Ordinary, SourceLocation(),
3676 false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003677 // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3678 ConditionalOperator *CondExpr =
3679 new (Context) ConditionalOperator(lessThanExpr,
3680 SourceLocation(), CE,
3681 SourceLocation(), STCE,
3682 returnType, VK_RValue, OK_Ordinary);
3683 ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3684 CondExpr);
3685 }
3686 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3687 return ReplacingStmt;
3688}
3689
3690Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3691 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3692 Exp->getLocEnd());
3693
3694 // Now do the actual rewrite.
3695 ReplaceStmt(Exp, ReplacingStmt);
3696
3697 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3698 return ReplacingStmt;
3699}
3700
3701// typedef struct objc_object Protocol;
3702QualType RewriteModernObjC::getProtocolType() {
3703 if (!ProtocolTypeDecl) {
3704 TypeSourceInfo *TInfo
3705 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3706 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3707 SourceLocation(), SourceLocation(),
3708 &Context->Idents.get("Protocol"),
3709 TInfo);
3710 }
3711 return Context->getTypeDeclType(ProtocolTypeDecl);
3712}
3713
3714/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3715/// a synthesized/forward data reference (to the protocol's metadata).
3716/// The forward references (and metadata) are generated in
3717/// RewriteModernObjC::HandleTranslationUnit().
3718Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003719 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3720 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003721 IdentifierInfo *ID = &Context->Idents.get(Name);
3722 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3723 SourceLocation(), ID, getProtocolType(), 0,
3724 SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00003725 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3726 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003727 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3728 Context->getPointerType(DRE->getType()),
3729 VK_RValue, OK_Ordinary, SourceLocation());
3730 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3731 CK_BitCast,
3732 DerefExpr);
3733 ReplaceStmt(Exp, castExpr);
3734 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3735 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3736 return castExpr;
3737
3738}
3739
3740bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3741 const char *endBuf) {
3742 while (startBuf < endBuf) {
3743 if (*startBuf == '#') {
3744 // Skip whitespace.
3745 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3746 ;
3747 if (!strncmp(startBuf, "if", strlen("if")) ||
3748 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3749 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3750 !strncmp(startBuf, "define", strlen("define")) ||
3751 !strncmp(startBuf, "undef", strlen("undef")) ||
3752 !strncmp(startBuf, "else", strlen("else")) ||
3753 !strncmp(startBuf, "elif", strlen("elif")) ||
3754 !strncmp(startBuf, "endif", strlen("endif")) ||
3755 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3756 !strncmp(startBuf, "include", strlen("include")) ||
3757 !strncmp(startBuf, "import", strlen("import")) ||
3758 !strncmp(startBuf, "include_next", strlen("include_next")))
3759 return true;
3760 }
3761 startBuf++;
3762 }
3763 return false;
3764}
3765
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003766/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3767/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003768bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003769 TagDecl *Tag,
3770 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003771 if (!IDecl)
3772 return false;
3773 SourceLocation TagLocation;
3774 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3775 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003776 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003777 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003778 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003779 TagLocation = RD->getLocation();
3780 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003781 IDecl->getLocation(), TagLocation);
3782 }
3783 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3784 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3785 return false;
3786 IsNamedDefinition = true;
3787 TagLocation = ED->getLocation();
3788 return Context->getSourceManager().isBeforeInTranslationUnit(
3789 IDecl->getLocation(), TagLocation);
3790
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003791 }
3792 return false;
3793}
3794
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003795/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003796/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003797bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3798 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003799 if (isa<TypedefType>(Type)) {
3800 Result += "\t";
3801 return false;
3802 }
3803
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003804 if (Type->isArrayType()) {
3805 QualType ElemTy = Context->getBaseElementType(Type);
3806 return RewriteObjCFieldDeclType(ElemTy, Result);
3807 }
3808 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003809 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3810 if (RD->isCompleteDefinition()) {
3811 if (RD->isStruct())
3812 Result += "\n\tstruct ";
3813 else if (RD->isUnion())
3814 Result += "\n\tunion ";
3815 else
3816 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003817
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003818 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003819 if (GlobalDefinedTags.count(RD)) {
3820 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003821 Result += " ";
3822 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003823 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003824 Result += " {\n";
3825 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003826 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003827 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003828 RewriteObjCFieldDecl(FD, Result);
3829 }
3830 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003831 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003832 }
3833 }
3834 else if (Type->isEnumeralType()) {
3835 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3836 if (ED->isCompleteDefinition()) {
3837 Result += "\n\tenum ";
3838 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003839 if (GlobalDefinedTags.count(ED)) {
3840 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003841 Result += " ";
3842 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003843 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003844
3845 Result += " {\n";
3846 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3847 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3848 Result += "\t"; Result += EC->getName(); Result += " = ";
3849 llvm::APSInt Val = EC->getInitVal();
3850 Result += Val.toString(10);
3851 Result += ",\n";
3852 }
3853 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003854 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003855 }
3856 }
3857
3858 Result += "\t";
3859 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003860 return false;
3861}
3862
3863
3864/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3865/// It handles elaborated types, as well as enum types in the process.
3866void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3867 std::string &Result) {
3868 QualType Type = fieldDecl->getType();
3869 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003870
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003871 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3872 if (!EleboratedType)
3873 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003874 Result += Name;
3875 if (fieldDecl->isBitField()) {
3876 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3877 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003878 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003879 const ArrayType *AT = Context->getAsArrayType(Type);
3880 do {
3881 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003882 Result += "[";
3883 llvm::APInt Dim = CAT->getSize();
3884 Result += utostr(Dim.getZExtValue());
3885 Result += "]";
3886 }
Eli Friedman6febf122012-12-13 01:43:21 +00003887 AT = Context->getAsArrayType(AT->getElementType());
3888 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003889 }
3890
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003891 Result += ";\n";
3892}
3893
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003894/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3895/// named aggregate types into the input buffer.
3896void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3897 std::string &Result) {
3898 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003899 if (isa<TypedefType>(Type))
3900 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003901 if (Type->isArrayType())
3902 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003903 ObjCContainerDecl *IDecl =
3904 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003905
3906 TagDecl *TD = 0;
3907 if (Type->isRecordType()) {
3908 TD = Type->getAs<RecordType>()->getDecl();
3909 }
3910 else if (Type->isEnumeralType()) {
3911 TD = Type->getAs<EnumType>()->getDecl();
3912 }
3913
3914 if (TD) {
3915 if (GlobalDefinedTags.count(TD))
3916 return;
3917
3918 bool IsNamedDefinition = false;
3919 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3920 RewriteObjCFieldDeclType(Type, Result);
3921 Result += ";";
3922 }
3923 if (IsNamedDefinition)
3924 GlobalDefinedTags.insert(TD);
3925 }
3926
3927}
3928
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003929unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3930 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3931 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3932 return IvarGroupNumber[IV];
3933 }
3934 unsigned GroupNo = 0;
3935 SmallVector<const ObjCIvarDecl *, 8> IVars;
3936 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3937 IVD; IVD = IVD->getNextIvar())
3938 IVars.push_back(IVD);
3939
3940 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3941 if (IVars[i]->isBitField()) {
3942 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3943 while (i < e && IVars[i]->isBitField())
3944 IvarGroupNumber[IVars[i++]] = GroupNo;
3945 if (i < e)
3946 --i;
3947 }
3948
3949 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3950 return IvarGroupNumber[IV];
3951}
3952
3953QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3954 ObjCIvarDecl *IV,
3955 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3956 std::string StructTagName;
3957 ObjCIvarBitfieldGroupType(IV, StructTagName);
3958 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3959 Context->getTranslationUnitDecl(),
3960 SourceLocation(), SourceLocation(),
3961 &Context->Idents.get(StructTagName));
3962 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3963 ObjCIvarDecl *Ivar = IVars[i];
3964 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3965 &Context->Idents.get(Ivar->getName()),
3966 Ivar->getType(),
3967 0, /*Expr *BW */Ivar->getBitWidth(), false,
3968 ICIS_NoInit));
3969 }
3970 RD->completeDefinition();
3971 return Context->getTagDeclType(RD);
3972}
3973
3974QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3975 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3976 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3977 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3978 if (GroupRecordType.count(tuple))
3979 return GroupRecordType[tuple];
3980
3981 SmallVector<ObjCIvarDecl *, 8> IVars;
3982 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3983 IVD; IVD = IVD->getNextIvar()) {
3984 if (IVD->isBitField())
3985 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3986 else {
3987 if (!IVars.empty()) {
3988 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3989 // Generate the struct type for this group of bitfield ivars.
3990 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3991 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3992 IVars.clear();
3993 }
3994 }
3995 }
3996 if (!IVars.empty()) {
3997 // Do the last one.
3998 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3999 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
4000 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
4001 }
4002 QualType RetQT = GroupRecordType[tuple];
4003 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
4004
4005 return RetQT;
4006}
4007
4008/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4009/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4010void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4011 std::string &Result) {
4012 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4013 Result += CDecl->getName();
4014 Result += "__GRBF_";
4015 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4016 Result += utostr(GroupNo);
4017 return;
4018}
4019
4020/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4021/// Name of the struct would be: classname__T_n where n is the group number for
4022/// this ivar.
4023void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4024 std::string &Result) {
4025 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4026 Result += CDecl->getName();
4027 Result += "__T_";
4028 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4029 Result += utostr(GroupNo);
4030 return;
4031}
4032
4033/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4034/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4035/// this ivar.
4036void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4037 std::string &Result) {
4038 Result += "OBJC_IVAR_$_";
4039 ObjCIvarBitfieldGroupDecl(IV, Result);
4040}
4041
4042#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4043 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4044 ++IX; \
4045 if (IX < ENDIX) \
4046 --IX; \
4047}
4048
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004049/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4050/// an objective-c class with ivars.
4051void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4052 std::string &Result) {
4053 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4054 assert(CDecl->getName() != "" &&
4055 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004056 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004057 SmallVector<ObjCIvarDecl *, 8> IVars;
4058 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004059 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004060 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004061
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004062 SourceLocation LocStart = CDecl->getLocStart();
4063 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004064
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004065 const char *startBuf = SM->getCharacterData(LocStart);
4066 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004067
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004068 // If no ivars and no root or if its root, directly or indirectly,
4069 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004070 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004071 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4072 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4073 ReplaceText(LocStart, endBuf-startBuf, Result);
4074 return;
4075 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004076
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004077 // Insert named struct/union definitions inside class to
4078 // outer scope. This follows semantics of locally defined
4079 // struct/unions in objective-c classes.
4080 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4081 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004082
4083 // Insert named structs which are syntheized to group ivar bitfields
4084 // to outer scope as well.
4085 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4086 if (IVars[i]->isBitField()) {
4087 ObjCIvarDecl *IV = IVars[i];
4088 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4089 RewriteObjCFieldDeclType(QT, Result);
4090 Result += ";";
4091 // skip over ivar bitfields in this group.
4092 SKIP_BITFIELDS(i , e, IVars);
4093 }
4094
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004095 Result += "\nstruct ";
4096 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004097 Result += "_IMPL {\n";
4098
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004099 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004100 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4101 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4102 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004103 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004104
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004105 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4106 if (IVars[i]->isBitField()) {
4107 ObjCIvarDecl *IV = IVars[i];
4108 Result += "\tstruct ";
4109 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4110 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4111 // skip over ivar bitfields in this group.
4112 SKIP_BITFIELDS(i , e, IVars);
4113 }
4114 else
4115 RewriteObjCFieldDecl(IVars[i], Result);
4116 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004117
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004118 Result += "};\n";
4119 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4120 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004121 // Mark this struct as having been generated.
4122 if (!ObjCSynthesizedStructs.insert(CDecl))
4123 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004124}
4125
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004126/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4127/// have been referenced in an ivar access expression.
4128void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4129 std::string &Result) {
4130 // write out ivar offset symbols which have been referenced in an ivar
4131 // access expression.
4132 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4133 if (Ivars.empty())
4134 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004135
4136 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004137 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4138 e = Ivars.end(); i != e; i++) {
4139 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004140 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4141 unsigned GroupNo = 0;
4142 if (IvarDecl->isBitField()) {
4143 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4144 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4145 continue;
4146 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004147 Result += "\n";
4148 if (LangOpts.MicrosoftExt)
4149 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004150 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004151 if (LangOpts.MicrosoftExt &&
4152 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004153 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4154 Result += "__declspec(dllimport) ";
4155
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004156 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004157 if (IvarDecl->isBitField()) {
4158 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4159 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4160 }
4161 else
4162 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004163 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004164 }
4165}
4166
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004167//===----------------------------------------------------------------------===//
4168// Meta Data Emission
4169//===----------------------------------------------------------------------===//
4170
4171
4172/// RewriteImplementations - This routine rewrites all method implementations
4173/// and emits meta-data.
4174
4175void RewriteModernObjC::RewriteImplementations() {
4176 int ClsDefCount = ClassImplementation.size();
4177 int CatDefCount = CategoryImplementation.size();
4178
4179 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004180 for (int i = 0; i < ClsDefCount; i++) {
4181 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4182 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4183 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004184 assert(false &&
4185 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004186 RewriteImplementationDecl(OIMP);
4187 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004188
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004189 for (int i = 0; i < CatDefCount; i++) {
4190 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4191 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4192 if (CDecl->isImplicitInterfaceDecl())
4193 assert(false &&
4194 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004195 RewriteImplementationDecl(CIMP);
4196 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004197}
4198
4199void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4200 const std::string &Name,
4201 ValueDecl *VD, bool def) {
4202 assert(BlockByRefDeclNo.count(VD) &&
4203 "RewriteByRefString: ByRef decl missing");
4204 if (def)
4205 ResultStr += "struct ";
4206 ResultStr += "__Block_byref_" + Name +
4207 "_" + utostr(BlockByRefDeclNo[VD]) ;
4208}
4209
4210static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4211 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4212 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4213 return false;
4214}
4215
4216std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4217 StringRef funcName,
4218 std::string Tag) {
4219 const FunctionType *AFT = CE->getFunctionType();
4220 QualType RT = AFT->getResultType();
4221 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004222 SourceLocation BlockLoc = CE->getExprLoc();
4223 std::string S;
4224 ConvertSourceLocationToLineDirective(BlockLoc, S);
4225
4226 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4227 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004228
4229 BlockDecl *BD = CE->getBlockDecl();
4230
4231 if (isa<FunctionNoProtoType>(AFT)) {
4232 // No user-supplied arguments. Still need to pass in a pointer to the
4233 // block (to reference imported block decl refs).
4234 S += "(" + StructRef + " *__cself)";
4235 } else if (BD->param_empty()) {
4236 S += "(" + StructRef + " *__cself)";
4237 } else {
4238 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4239 assert(FT && "SynthesizeBlockFunc: No function proto");
4240 S += '(';
4241 // first add the implicit argument.
4242 S += StructRef + " *__cself, ";
4243 std::string ParamStr;
4244 for (BlockDecl::param_iterator AI = BD->param_begin(),
4245 E = BD->param_end(); AI != E; ++AI) {
4246 if (AI != BD->param_begin()) S += ", ";
4247 ParamStr = (*AI)->getNameAsString();
4248 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004249 (void)convertBlockPointerToFunctionPointer(QT);
4250 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004251 S += ParamStr;
4252 }
4253 if (FT->isVariadic()) {
4254 if (!BD->param_empty()) S += ", ";
4255 S += "...";
4256 }
4257 S += ')';
4258 }
4259 S += " {\n";
4260
4261 // Create local declarations to avoid rewriting all closure decl ref exprs.
4262 // First, emit a declaration for all "by ref" decls.
4263 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4264 E = BlockByRefDecls.end(); I != E; ++I) {
4265 S += " ";
4266 std::string Name = (*I)->getNameAsString();
4267 std::string TypeString;
4268 RewriteByRefString(TypeString, Name, (*I));
4269 TypeString += " *";
4270 Name = TypeString + Name;
4271 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4272 }
4273 // Next, emit a declaration for all "by copy" declarations.
4274 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4275 E = BlockByCopyDecls.end(); I != E; ++I) {
4276 S += " ";
4277 // Handle nested closure invocation. For example:
4278 //
4279 // void (^myImportedClosure)(void);
4280 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4281 //
4282 // void (^anotherClosure)(void);
4283 // anotherClosure = ^(void) {
4284 // myImportedClosure(); // import and invoke the closure
4285 // };
4286 //
4287 if (isTopLevelBlockPointerType((*I)->getType())) {
4288 RewriteBlockPointerTypeVariable(S, (*I));
4289 S += " = (";
4290 RewriteBlockPointerType(S, (*I)->getType());
4291 S += ")";
4292 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4293 }
4294 else {
4295 std::string Name = (*I)->getNameAsString();
4296 QualType QT = (*I)->getType();
4297 if (HasLocalVariableExternalStorage(*I))
4298 QT = Context->getPointerType(QT);
4299 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4300 S += Name + " = __cself->" +
4301 (*I)->getNameAsString() + "; // bound by copy\n";
4302 }
4303 }
4304 std::string RewrittenStr = RewrittenBlockExprs[CE];
4305 const char *cstr = RewrittenStr.c_str();
4306 while (*cstr++ != '{') ;
4307 S += cstr;
4308 S += "\n";
4309 return S;
4310}
4311
4312std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4313 StringRef funcName,
4314 std::string Tag) {
4315 std::string StructRef = "struct " + Tag;
4316 std::string S = "static void __";
4317
4318 S += funcName;
4319 S += "_block_copy_" + utostr(i);
4320 S += "(" + StructRef;
4321 S += "*dst, " + StructRef;
4322 S += "*src) {";
4323 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4324 E = ImportedBlockDecls.end(); I != E; ++I) {
4325 ValueDecl *VD = (*I);
4326 S += "_Block_object_assign((void*)&dst->";
4327 S += (*I)->getNameAsString();
4328 S += ", (void*)src->";
4329 S += (*I)->getNameAsString();
4330 if (BlockByRefDeclsPtrSet.count((*I)))
4331 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4332 else if (VD->getType()->isBlockPointerType())
4333 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4334 else
4335 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4336 }
4337 S += "}\n";
4338
4339 S += "\nstatic void __";
4340 S += funcName;
4341 S += "_block_dispose_" + utostr(i);
4342 S += "(" + StructRef;
4343 S += "*src) {";
4344 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4345 E = ImportedBlockDecls.end(); I != E; ++I) {
4346 ValueDecl *VD = (*I);
4347 S += "_Block_object_dispose((void*)src->";
4348 S += (*I)->getNameAsString();
4349 if (BlockByRefDeclsPtrSet.count((*I)))
4350 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4351 else if (VD->getType()->isBlockPointerType())
4352 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4353 else
4354 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4355 }
4356 S += "}\n";
4357 return S;
4358}
4359
4360std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4361 std::string Desc) {
4362 std::string S = "\nstruct " + Tag;
4363 std::string Constructor = " " + Tag;
4364
4365 S += " {\n struct __block_impl impl;\n";
4366 S += " struct " + Desc;
4367 S += "* Desc;\n";
4368
4369 Constructor += "(void *fp, "; // Invoke function pointer.
4370 Constructor += "struct " + Desc; // Descriptor pointer.
4371 Constructor += " *desc";
4372
4373 if (BlockDeclRefs.size()) {
4374 // Output all "by copy" declarations.
4375 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4376 E = BlockByCopyDecls.end(); I != E; ++I) {
4377 S += " ";
4378 std::string FieldName = (*I)->getNameAsString();
4379 std::string ArgName = "_" + FieldName;
4380 // Handle nested closure invocation. For example:
4381 //
4382 // void (^myImportedBlock)(void);
4383 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4384 //
4385 // void (^anotherBlock)(void);
4386 // anotherBlock = ^(void) {
4387 // myImportedBlock(); // import and invoke the closure
4388 // };
4389 //
4390 if (isTopLevelBlockPointerType((*I)->getType())) {
4391 S += "struct __block_impl *";
4392 Constructor += ", void *" + ArgName;
4393 } else {
4394 QualType QT = (*I)->getType();
4395 if (HasLocalVariableExternalStorage(*I))
4396 QT = Context->getPointerType(QT);
4397 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4398 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4399 Constructor += ", " + ArgName;
4400 }
4401 S += FieldName + ";\n";
4402 }
4403 // Output all "by ref" declarations.
4404 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4405 E = BlockByRefDecls.end(); I != E; ++I) {
4406 S += " ";
4407 std::string FieldName = (*I)->getNameAsString();
4408 std::string ArgName = "_" + FieldName;
4409 {
4410 std::string TypeString;
4411 RewriteByRefString(TypeString, FieldName, (*I));
4412 TypeString += " *";
4413 FieldName = TypeString + FieldName;
4414 ArgName = TypeString + ArgName;
4415 Constructor += ", " + ArgName;
4416 }
4417 S += FieldName + "; // by ref\n";
4418 }
4419 // Finish writing the constructor.
4420 Constructor += ", int flags=0)";
4421 // Initialize all "by copy" arguments.
4422 bool firsTime = true;
4423 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
4424 E = BlockByCopyDecls.end(); I != E; ++I) {
4425 std::string Name = (*I)->getNameAsString();
4426 if (firsTime) {
4427 Constructor += " : ";
4428 firsTime = false;
4429 }
4430 else
4431 Constructor += ", ";
4432 if (isTopLevelBlockPointerType((*I)->getType()))
4433 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4434 else
4435 Constructor += Name + "(_" + Name + ")";
4436 }
4437 // Initialize all "by ref" arguments.
4438 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
4439 E = BlockByRefDecls.end(); I != E; ++I) {
4440 std::string Name = (*I)->getNameAsString();
4441 if (firsTime) {
4442 Constructor += " : ";
4443 firsTime = false;
4444 }
4445 else
4446 Constructor += ", ";
4447 Constructor += Name + "(_" + Name + "->__forwarding)";
4448 }
4449
4450 Constructor += " {\n";
4451 if (GlobalVarDecl)
4452 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4453 else
4454 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4455 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4456
4457 Constructor += " Desc = desc;\n";
4458 } else {
4459 // Finish writing the constructor.
4460 Constructor += ", int flags=0) {\n";
4461 if (GlobalVarDecl)
4462 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4463 else
4464 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4465 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4466 Constructor += " Desc = desc;\n";
4467 }
4468 Constructor += " ";
4469 Constructor += "}\n";
4470 S += Constructor;
4471 S += "};\n";
4472 return S;
4473}
4474
4475std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4476 std::string ImplTag, int i,
4477 StringRef FunName,
4478 unsigned hasCopy) {
4479 std::string S = "\nstatic struct " + DescTag;
4480
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004481 S += " {\n size_t reserved;\n";
4482 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004483 if (hasCopy) {
4484 S += " void (*copy)(struct ";
4485 S += ImplTag; S += "*, struct ";
4486 S += ImplTag; S += "*);\n";
4487
4488 S += " void (*dispose)(struct ";
4489 S += ImplTag; S += "*);\n";
4490 }
4491 S += "} ";
4492
4493 S += DescTag + "_DATA = { 0, sizeof(struct ";
4494 S += ImplTag + ")";
4495 if (hasCopy) {
4496 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4497 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4498 }
4499 S += "};\n";
4500 return S;
4501}
4502
4503void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4504 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004505 bool RewriteSC = (GlobalVarDecl &&
4506 !Blocks.empty() &&
4507 GlobalVarDecl->getStorageClass() == SC_Static &&
4508 GlobalVarDecl->getType().getCVRQualifiers());
4509 if (RewriteSC) {
4510 std::string SC(" void __");
4511 SC += GlobalVarDecl->getNameAsString();
4512 SC += "() {}";
4513 InsertText(FunLocStart, SC);
4514 }
4515
4516 // Insert closures that were part of the function.
4517 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4518 CollectBlockDeclRefInfo(Blocks[i]);
4519 // Need to copy-in the inner copied-in variables not actually used in this
4520 // block.
4521 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004522 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004523 ValueDecl *VD = Exp->getDecl();
4524 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004525 if (!VD->hasAttr<BlocksAttr>()) {
4526 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4527 BlockByCopyDeclsPtrSet.insert(VD);
4528 BlockByCopyDecls.push_back(VD);
4529 }
4530 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004531 }
John McCallf4b88a42012-03-10 09:33:50 +00004532
4533 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004534 BlockByRefDeclsPtrSet.insert(VD);
4535 BlockByRefDecls.push_back(VD);
4536 }
John McCallf4b88a42012-03-10 09:33:50 +00004537
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004538 // imported objects in the inner blocks not used in the outer
4539 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004540 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004541 VD->getType()->isBlockPointerType())
4542 ImportedBlockDecls.insert(VD);
4543 }
4544
4545 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4546 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4547
4548 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4549
4550 InsertText(FunLocStart, CI);
4551
4552 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4553
4554 InsertText(FunLocStart, CF);
4555
4556 if (ImportedBlockDecls.size()) {
4557 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4558 InsertText(FunLocStart, HF);
4559 }
4560 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4561 ImportedBlockDecls.size() > 0);
4562 InsertText(FunLocStart, BD);
4563
4564 BlockDeclRefs.clear();
4565 BlockByRefDecls.clear();
4566 BlockByRefDeclsPtrSet.clear();
4567 BlockByCopyDecls.clear();
4568 BlockByCopyDeclsPtrSet.clear();
4569 ImportedBlockDecls.clear();
4570 }
4571 if (RewriteSC) {
4572 // Must insert any 'const/volatile/static here. Since it has been
4573 // removed as result of rewriting of block literals.
4574 std::string SC;
4575 if (GlobalVarDecl->getStorageClass() == SC_Static)
4576 SC = "static ";
4577 if (GlobalVarDecl->getType().isConstQualified())
4578 SC += "const ";
4579 if (GlobalVarDecl->getType().isVolatileQualified())
4580 SC += "volatile ";
4581 if (GlobalVarDecl->getType().isRestrictQualified())
4582 SC += "restrict ";
4583 InsertText(FunLocStart, SC);
4584 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004585 if (GlobalConstructionExp) {
4586 // extra fancy dance for global literal expression.
4587
4588 // Always the latest block expression on the block stack.
4589 std::string Tag = "__";
4590 Tag += FunName;
4591 Tag += "_block_impl_";
4592 Tag += utostr(Blocks.size()-1);
4593 std::string globalBuf = "static ";
4594 globalBuf += Tag; globalBuf += " ";
4595 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004596
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004597 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004598 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004599 PrintingPolicy(LangOpts));
4600 globalBuf += constructorExprBuf.str();
4601 globalBuf += ";\n";
4602 InsertText(FunLocStart, globalBuf);
4603 GlobalConstructionExp = 0;
4604 }
4605
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004606 Blocks.clear();
4607 InnerDeclRefsCount.clear();
4608 InnerDeclRefs.clear();
4609 RewrittenBlockExprs.clear();
4610}
4611
4612void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004613 SourceLocation FunLocStart =
4614 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4615 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004616 StringRef FuncName = FD->getName();
4617
4618 SynthesizeBlockLiterals(FunLocStart, FuncName);
4619}
4620
4621static void BuildUniqueMethodName(std::string &Name,
4622 ObjCMethodDecl *MD) {
4623 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4624 Name = IFace->getName();
4625 Name += "__" + MD->getSelector().getAsString();
4626 // Convert colons to underscores.
4627 std::string::size_type loc = 0;
4628 while ((loc = Name.find(":", loc)) != std::string::npos)
4629 Name.replace(loc, 1, "_");
4630}
4631
4632void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4633 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4634 //SourceLocation FunLocStart = MD->getLocStart();
4635 SourceLocation FunLocStart = MD->getLocStart();
4636 std::string FuncName;
4637 BuildUniqueMethodName(FuncName, MD);
4638 SynthesizeBlockLiterals(FunLocStart, FuncName);
4639}
4640
4641void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4642 for (Stmt::child_range CI = S->children(); CI; ++CI)
4643 if (*CI) {
4644 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4645 GetBlockDeclRefExprs(CBE->getBody());
4646 else
4647 GetBlockDeclRefExprs(*CI);
4648 }
4649 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004650 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4651 if (DRE->refersToEnclosingLocal()) {
4652 // FIXME: Handle enums.
4653 if (!isa<FunctionDecl>(DRE->getDecl()))
4654 BlockDeclRefs.push_back(DRE);
4655 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4656 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004657 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004658 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004659
4660 return;
4661}
4662
4663void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
John McCallf4b88a42012-03-10 09:33:50 +00004664 SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004665 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4666 for (Stmt::child_range CI = S->children(); CI; ++CI)
4667 if (*CI) {
4668 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4669 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4670 GetInnerBlockDeclRefExprs(CBE->getBody(),
4671 InnerBlockDeclRefs,
4672 InnerContexts);
4673 }
4674 else
4675 GetInnerBlockDeclRefExprs(*CI,
4676 InnerBlockDeclRefs,
4677 InnerContexts);
4678
4679 }
4680 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004681 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4682 if (DRE->refersToEnclosingLocal()) {
4683 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4684 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4685 InnerBlockDeclRefs.push_back(DRE);
4686 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4687 if (Var->isFunctionOrMethodVarDecl())
4688 ImportedLocalExternalDecls.insert(Var);
4689 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004690 }
4691
4692 return;
4693}
4694
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004695/// convertObjCTypeToCStyleType - This routine converts such objc types
4696/// as qualified objects, and blocks to their closest c/c++ types that
4697/// it can. It returns true if input type was modified.
4698bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4699 QualType oldT = T;
4700 convertBlockPointerToFunctionPointer(T);
4701 if (T->isFunctionPointerType()) {
4702 QualType PointeeTy;
4703 if (const PointerType* PT = T->getAs<PointerType>()) {
4704 PointeeTy = PT->getPointeeType();
4705 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4706 T = convertFunctionTypeOfBlocks(FT);
4707 T = Context->getPointerType(T);
4708 }
4709 }
4710 }
4711
4712 convertToUnqualifiedObjCType(T);
4713 return T != oldT;
4714}
4715
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004716/// convertFunctionTypeOfBlocks - This routine converts a function type
4717/// whose result type may be a block pointer or whose argument type(s)
4718/// might be block pointers to an equivalent function type replacing
4719/// all block pointers to function pointers.
4720QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4721 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4722 // FTP will be null for closures that don't take arguments.
4723 // Generate a funky cast.
4724 SmallVector<QualType, 8> ArgTypes;
4725 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004726 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004727
4728 if (FTP) {
4729 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4730 E = FTP->arg_type_end(); I && (I != E); ++I) {
4731 QualType t = *I;
4732 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004733 if (convertObjCTypeToCStyleType(t))
4734 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004735 ArgTypes.push_back(t);
4736 }
4737 }
4738 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004739 if (modified)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004740 FuncType = getSimpleFunctionType(Res, &ArgTypes[0], ArgTypes.size());
4741 else FuncType = QualType(FT, 0);
4742 return FuncType;
4743}
4744
4745Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4746 // Navigate to relevant type information.
4747 const BlockPointerType *CPT = 0;
4748
4749 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4750 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004751 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4752 CPT = MExpr->getType()->getAs<BlockPointerType>();
4753 }
4754 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4755 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4756 }
4757 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4758 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4759 else if (const ConditionalOperator *CEXPR =
4760 dyn_cast<ConditionalOperator>(BlockExp)) {
4761 Expr *LHSExp = CEXPR->getLHS();
4762 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4763 Expr *RHSExp = CEXPR->getRHS();
4764 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4765 Expr *CONDExp = CEXPR->getCond();
4766 ConditionalOperator *CondExpr =
4767 new (Context) ConditionalOperator(CONDExp,
4768 SourceLocation(), cast<Expr>(LHSStmt),
4769 SourceLocation(), cast<Expr>(RHSStmt),
4770 Exp->getType(), VK_RValue, OK_Ordinary);
4771 return CondExpr;
4772 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4773 CPT = IRE->getType()->getAs<BlockPointerType>();
4774 } else if (const PseudoObjectExpr *POE
4775 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4776 CPT = POE->getType()->castAs<BlockPointerType>();
4777 } else {
4778 assert(1 && "RewriteBlockClass: Bad type");
4779 }
4780 assert(CPT && "RewriteBlockClass: Bad type");
4781 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4782 assert(FT && "RewriteBlockClass: Bad type");
4783 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4784 // FTP will be null for closures that don't take arguments.
4785
4786 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4787 SourceLocation(), SourceLocation(),
4788 &Context->Idents.get("__block_impl"));
4789 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4790
4791 // Generate a funky cast.
4792 SmallVector<QualType, 8> ArgTypes;
4793
4794 // Push the block argument type.
4795 ArgTypes.push_back(PtrBlock);
4796 if (FTP) {
4797 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4798 E = FTP->arg_type_end(); I && (I != E); ++I) {
4799 QualType t = *I;
4800 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4801 if (!convertBlockPointerToFunctionPointer(t))
4802 convertToUnqualifiedObjCType(t);
4803 ArgTypes.push_back(t);
4804 }
4805 }
4806 // Now do the pointer to function cast.
4807 QualType PtrToFuncCastType
4808 = getSimpleFunctionType(Exp->getType(), &ArgTypes[0], ArgTypes.size());
4809
4810 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4811
4812 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4813 CK_BitCast,
4814 const_cast<Expr*>(BlockExp));
4815 // Don't forget the parens to enforce the proper binding.
4816 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4817 BlkCast);
4818 //PE->dump();
4819
4820 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4821 SourceLocation(),
4822 &Context->Idents.get("FuncPtr"),
4823 Context->VoidPtrTy, 0,
4824 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004825 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004826 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4827 FD->getType(), VK_LValue,
4828 OK_Ordinary);
4829
4830
4831 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4832 CK_BitCast, ME);
4833 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4834
4835 SmallVector<Expr*, 8> BlkExprs;
4836 // Add the implicit argument.
4837 BlkExprs.push_back(BlkCast);
4838 // Add the user arguments.
4839 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4840 E = Exp->arg_end(); I != E; ++I) {
4841 BlkExprs.push_back(*I);
4842 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004843 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004844 Exp->getType(), VK_RValue,
4845 SourceLocation());
4846 return CE;
4847}
4848
4849// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004850// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004851// For example:
4852//
4853// int main() {
4854// __block Foo *f;
4855// __block int i;
4856//
4857// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004858// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004859// i = 77;
4860// };
4861//}
John McCallf4b88a42012-03-10 09:33:50 +00004862Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004863 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4864 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004865 ValueDecl *VD = DeclRefExp->getDecl();
4866 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004867
4868 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4869 SourceLocation(),
4870 &Context->Idents.get("__forwarding"),
4871 Context->VoidPtrTy, 0,
4872 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004873 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004874 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4875 FD, SourceLocation(),
4876 FD->getType(), VK_LValue,
4877 OK_Ordinary);
4878
4879 StringRef Name = VD->getName();
4880 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4881 &Context->Idents.get(Name),
4882 Context->VoidPtrTy, 0,
4883 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004884 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004885 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4886 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4887
4888
4889
4890 // Need parens to enforce precedence.
4891 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4892 DeclRefExp->getExprLoc(),
4893 ME);
4894 ReplaceStmt(DeclRefExp, PE);
4895 return PE;
4896}
4897
4898// Rewrites the imported local variable V with external storage
4899// (static, extern, etc.) as *V
4900//
4901Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4902 ValueDecl *VD = DRE->getDecl();
4903 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4904 if (!ImportedLocalExternalDecls.count(Var))
4905 return DRE;
4906 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4907 VK_LValue, OK_Ordinary,
4908 DRE->getLocation());
4909 // Need parens to enforce precedence.
4910 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4911 Exp);
4912 ReplaceStmt(DRE, PE);
4913 return PE;
4914}
4915
4916void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4917 SourceLocation LocStart = CE->getLParenLoc();
4918 SourceLocation LocEnd = CE->getRParenLoc();
4919
4920 // Need to avoid trying to rewrite synthesized casts.
4921 if (LocStart.isInvalid())
4922 return;
4923 // Need to avoid trying to rewrite casts contained in macros.
4924 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4925 return;
4926
4927 const char *startBuf = SM->getCharacterData(LocStart);
4928 const char *endBuf = SM->getCharacterData(LocEnd);
4929 QualType QT = CE->getType();
4930 const Type* TypePtr = QT->getAs<Type>();
4931 if (isa<TypeOfExprType>(TypePtr)) {
4932 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4933 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4934 std::string TypeAsString = "(";
4935 RewriteBlockPointerType(TypeAsString, QT);
4936 TypeAsString += ")";
4937 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4938 return;
4939 }
4940 // advance the location to startArgList.
4941 const char *argPtr = startBuf;
4942
4943 while (*argPtr++ && (argPtr < endBuf)) {
4944 switch (*argPtr) {
4945 case '^':
4946 // Replace the '^' with '*'.
4947 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4948 ReplaceText(LocStart, 1, "*");
4949 break;
4950 }
4951 }
4952 return;
4953}
4954
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004955void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4956 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004957 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4958 CastKind != CK_AnyPointerToBlockPointerCast)
4959 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004960
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004961 QualType QT = IC->getType();
4962 (void)convertBlockPointerToFunctionPointer(QT);
4963 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4964 std::string Str = "(";
4965 Str += TypeString;
4966 Str += ")";
4967 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4968
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004969 return;
4970}
4971
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004972void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4973 SourceLocation DeclLoc = FD->getLocation();
4974 unsigned parenCount = 0;
4975
4976 // We have 1 or more arguments that have closure pointers.
4977 const char *startBuf = SM->getCharacterData(DeclLoc);
4978 const char *startArgList = strchr(startBuf, '(');
4979
4980 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4981
4982 parenCount++;
4983 // advance the location to startArgList.
4984 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4985 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4986
4987 const char *argPtr = startArgList;
4988
4989 while (*argPtr++ && parenCount) {
4990 switch (*argPtr) {
4991 case '^':
4992 // Replace the '^' with '*'.
4993 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4994 ReplaceText(DeclLoc, 1, "*");
4995 break;
4996 case '(':
4997 parenCount++;
4998 break;
4999 case ')':
5000 parenCount--;
5001 break;
5002 }
5003 }
5004 return;
5005}
5006
5007bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
5008 const FunctionProtoType *FTP;
5009 const PointerType *PT = QT->getAs<PointerType>();
5010 if (PT) {
5011 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5012 } else {
5013 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5014 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5015 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5016 }
5017 if (FTP) {
5018 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5019 E = FTP->arg_type_end(); I != E; ++I)
5020 if (isTopLevelBlockPointerType(*I))
5021 return true;
5022 }
5023 return false;
5024}
5025
5026bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5027 const FunctionProtoType *FTP;
5028 const PointerType *PT = QT->getAs<PointerType>();
5029 if (PT) {
5030 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5031 } else {
5032 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5033 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5034 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5035 }
5036 if (FTP) {
5037 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5038 E = FTP->arg_type_end(); I != E; ++I) {
5039 if ((*I)->isObjCQualifiedIdType())
5040 return true;
5041 if ((*I)->isObjCObjectPointerType() &&
5042 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5043 return true;
5044 }
5045
5046 }
5047 return false;
5048}
5049
5050void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5051 const char *&RParen) {
5052 const char *argPtr = strchr(Name, '(');
5053 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5054
5055 LParen = argPtr; // output the start.
5056 argPtr++; // skip past the left paren.
5057 unsigned parenCount = 1;
5058
5059 while (*argPtr && parenCount) {
5060 switch (*argPtr) {
5061 case '(': parenCount++; break;
5062 case ')': parenCount--; break;
5063 default: break;
5064 }
5065 if (parenCount) argPtr++;
5066 }
5067 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5068 RParen = argPtr; // output the end
5069}
5070
5071void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5072 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5073 RewriteBlockPointerFunctionArgs(FD);
5074 return;
5075 }
5076 // Handle Variables and Typedefs.
5077 SourceLocation DeclLoc = ND->getLocation();
5078 QualType DeclT;
5079 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5080 DeclT = VD->getType();
5081 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5082 DeclT = TDD->getUnderlyingType();
5083 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5084 DeclT = FD->getType();
5085 else
5086 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5087
5088 const char *startBuf = SM->getCharacterData(DeclLoc);
5089 const char *endBuf = startBuf;
5090 // scan backward (from the decl location) for the end of the previous decl.
5091 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5092 startBuf--;
5093 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5094 std::string buf;
5095 unsigned OrigLength=0;
5096 // *startBuf != '^' if we are dealing with a pointer to function that
5097 // may take block argument types (which will be handled below).
5098 if (*startBuf == '^') {
5099 // Replace the '^' with '*', computing a negative offset.
5100 buf = '*';
5101 startBuf++;
5102 OrigLength++;
5103 }
5104 while (*startBuf != ')') {
5105 buf += *startBuf;
5106 startBuf++;
5107 OrigLength++;
5108 }
5109 buf += ')';
5110 OrigLength++;
5111
5112 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5113 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5114 // Replace the '^' with '*' for arguments.
5115 // Replace id<P> with id/*<>*/
5116 DeclLoc = ND->getLocation();
5117 startBuf = SM->getCharacterData(DeclLoc);
5118 const char *argListBegin, *argListEnd;
5119 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5120 while (argListBegin < argListEnd) {
5121 if (*argListBegin == '^')
5122 buf += '*';
5123 else if (*argListBegin == '<') {
5124 buf += "/*";
5125 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005126 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005127 while (*argListBegin != '>') {
5128 buf += *argListBegin++;
5129 OrigLength++;
5130 }
5131 buf += *argListBegin;
5132 buf += "*/";
5133 }
5134 else
5135 buf += *argListBegin;
5136 argListBegin++;
5137 OrigLength++;
5138 }
5139 buf += ')';
5140 OrigLength++;
5141 }
5142 ReplaceText(Start, OrigLength, buf);
5143
5144 return;
5145}
5146
5147
5148/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5149/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5150/// struct Block_byref_id_object *src) {
5151/// _Block_object_assign (&_dest->object, _src->object,
5152/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5153/// [|BLOCK_FIELD_IS_WEAK]) // object
5154/// _Block_object_assign(&_dest->object, _src->object,
5155/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5156/// [|BLOCK_FIELD_IS_WEAK]) // block
5157/// }
5158/// And:
5159/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5160/// _Block_object_dispose(_src->object,
5161/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5162/// [|BLOCK_FIELD_IS_WEAK]) // object
5163/// _Block_object_dispose(_src->object,
5164/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5165/// [|BLOCK_FIELD_IS_WEAK]) // block
5166/// }
5167
5168std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5169 int flag) {
5170 std::string S;
5171 if (CopyDestroyCache.count(flag))
5172 return S;
5173 CopyDestroyCache.insert(flag);
5174 S = "static void __Block_byref_id_object_copy_";
5175 S += utostr(flag);
5176 S += "(void *dst, void *src) {\n";
5177
5178 // offset into the object pointer is computed as:
5179 // void * + void* + int + int + void* + void *
5180 unsigned IntSize =
5181 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5182 unsigned VoidPtrSize =
5183 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5184
5185 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5186 S += " _Block_object_assign((char*)dst + ";
5187 S += utostr(offset);
5188 S += ", *(void * *) ((char*)src + ";
5189 S += utostr(offset);
5190 S += "), ";
5191 S += utostr(flag);
5192 S += ");\n}\n";
5193
5194 S += "static void __Block_byref_id_object_dispose_";
5195 S += utostr(flag);
5196 S += "(void *src) {\n";
5197 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5198 S += utostr(offset);
5199 S += "), ";
5200 S += utostr(flag);
5201 S += ");\n}\n";
5202 return S;
5203}
5204
5205/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5206/// the declaration into:
5207/// struct __Block_byref_ND {
5208/// void *__isa; // NULL for everything except __weak pointers
5209/// struct __Block_byref_ND *__forwarding;
5210/// int32_t __flags;
5211/// int32_t __size;
5212/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5213/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5214/// typex ND;
5215/// };
5216///
5217/// It then replaces declaration of ND variable with:
5218/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5219/// __size=sizeof(struct __Block_byref_ND),
5220/// ND=initializer-if-any};
5221///
5222///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005223void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5224 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005225 int flag = 0;
5226 int isa = 0;
5227 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5228 if (DeclLoc.isInvalid())
5229 // If type location is missing, it is because of missing type (a warning).
5230 // Use variable's location which is good for this case.
5231 DeclLoc = ND->getLocation();
5232 const char *startBuf = SM->getCharacterData(DeclLoc);
5233 SourceLocation X = ND->getLocEnd();
5234 X = SM->getExpansionLoc(X);
5235 const char *endBuf = SM->getCharacterData(X);
5236 std::string Name(ND->getNameAsString());
5237 std::string ByrefType;
5238 RewriteByRefString(ByrefType, Name, ND, true);
5239 ByrefType += " {\n";
5240 ByrefType += " void *__isa;\n";
5241 RewriteByRefString(ByrefType, Name, ND);
5242 ByrefType += " *__forwarding;\n";
5243 ByrefType += " int __flags;\n";
5244 ByrefType += " int __size;\n";
5245 // Add void *__Block_byref_id_object_copy;
5246 // void *__Block_byref_id_object_dispose; if needed.
5247 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005248 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005249 if (HasCopyAndDispose) {
5250 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5251 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5252 }
5253
5254 QualType T = Ty;
5255 (void)convertBlockPointerToFunctionPointer(T);
5256 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5257
5258 ByrefType += " " + Name + ";\n";
5259 ByrefType += "};\n";
5260 // Insert this type in global scope. It is needed by helper function.
5261 SourceLocation FunLocStart;
5262 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005263 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005264 else {
5265 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5266 FunLocStart = CurMethodDef->getLocStart();
5267 }
5268 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005269
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005270 if (Ty.isObjCGCWeak()) {
5271 flag |= BLOCK_FIELD_IS_WEAK;
5272 isa = 1;
5273 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005274 if (HasCopyAndDispose) {
5275 flag = BLOCK_BYREF_CALLER;
5276 QualType Ty = ND->getType();
5277 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5278 if (Ty->isBlockPointerType())
5279 flag |= BLOCK_FIELD_IS_BLOCK;
5280 else
5281 flag |= BLOCK_FIELD_IS_OBJECT;
5282 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5283 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005284 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005285 }
5286
5287 // struct __Block_byref_ND ND =
5288 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5289 // initializer-if-any};
5290 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005291 // FIXME. rewriter does not support __block c++ objects which
5292 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005293 if (hasInit)
5294 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5295 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5296 if (CXXDecl && CXXDecl->isDefaultConstructor())
5297 hasInit = false;
5298 }
5299
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005300 unsigned flags = 0;
5301 if (HasCopyAndDispose)
5302 flags |= BLOCK_HAS_COPY_DISPOSE;
5303 Name = ND->getNameAsString();
5304 ByrefType.clear();
5305 RewriteByRefString(ByrefType, Name, ND);
5306 std::string ForwardingCastType("(");
5307 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005308 ByrefType += " " + Name + " = {(void*)";
5309 ByrefType += utostr(isa);
5310 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5311 ByrefType += utostr(flags);
5312 ByrefType += ", ";
5313 ByrefType += "sizeof(";
5314 RewriteByRefString(ByrefType, Name, ND);
5315 ByrefType += ")";
5316 if (HasCopyAndDispose) {
5317 ByrefType += ", __Block_byref_id_object_copy_";
5318 ByrefType += utostr(flag);
5319 ByrefType += ", __Block_byref_id_object_dispose_";
5320 ByrefType += utostr(flag);
5321 }
5322
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005323 if (!firstDecl) {
5324 // In multiple __block declarations, and for all but 1st declaration,
5325 // find location of the separating comma. This would be start location
5326 // where new text is to be inserted.
5327 DeclLoc = ND->getLocation();
5328 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5329 const char *commaBuf = startDeclBuf;
5330 while (*commaBuf != ',')
5331 commaBuf--;
5332 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5333 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5334 startBuf = commaBuf;
5335 }
5336
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005337 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005338 ByrefType += "};\n";
5339 unsigned nameSize = Name.size();
5340 // for block or function pointer declaration. Name is aleady
5341 // part of the declaration.
5342 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5343 nameSize = 1;
5344 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5345 }
5346 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005347 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005348 SourceLocation startLoc;
5349 Expr *E = ND->getInit();
5350 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5351 startLoc = ECE->getLParenLoc();
5352 else
5353 startLoc = E->getLocStart();
5354 startLoc = SM->getExpansionLoc(startLoc);
5355 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005356 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005357
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005358 const char separator = lastDecl ? ';' : ',';
5359 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5360 const char *separatorBuf = strchr(startInitializerBuf, separator);
5361 assert((*separatorBuf == separator) &&
5362 "RewriteByRefVar: can't find ';' or ','");
5363 SourceLocation separatorLoc =
5364 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5365
5366 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005367 }
5368 return;
5369}
5370
5371void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5372 // Add initializers for any closure decl refs.
5373 GetBlockDeclRefExprs(Exp->getBody());
5374 if (BlockDeclRefs.size()) {
5375 // Unique all "by copy" declarations.
5376 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005377 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005378 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5379 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5380 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5381 }
5382 }
5383 // Unique all "by ref" declarations.
5384 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005385 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005386 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5387 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5388 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5389 }
5390 }
5391 // Find any imported blocks...they will need special attention.
5392 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005393 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005394 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5395 BlockDeclRefs[i]->getType()->isBlockPointerType())
5396 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5397 }
5398}
5399
5400FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5401 IdentifierInfo *ID = &Context->Idents.get(name);
5402 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5403 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5404 SourceLocation(), ID, FType, 0, SC_Extern,
5405 SC_None, false, false);
5406}
5407
5408Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
John McCallf4b88a42012-03-10 09:33:50 +00005409 const SmallVector<DeclRefExpr *, 8> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005410
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005411 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005412
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005413 Blocks.push_back(Exp);
5414
5415 CollectBlockDeclRefInfo(Exp);
5416
5417 // Add inner imported variables now used in current block.
5418 int countOfInnerDecls = 0;
5419 if (!InnerBlockDeclRefs.empty()) {
5420 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005421 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005422 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005423 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005424 // We need to save the copied-in variables in nested
5425 // blocks because it is needed at the end for some of the API generations.
5426 // See SynthesizeBlockLiterals routine.
5427 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5428 BlockDeclRefs.push_back(Exp);
5429 BlockByCopyDeclsPtrSet.insert(VD);
5430 BlockByCopyDecls.push_back(VD);
5431 }
John McCallf4b88a42012-03-10 09:33:50 +00005432 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005433 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5434 BlockDeclRefs.push_back(Exp);
5435 BlockByRefDeclsPtrSet.insert(VD);
5436 BlockByRefDecls.push_back(VD);
5437 }
5438 }
5439 // Find any imported blocks...they will need special attention.
5440 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005441 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005442 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5443 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5444 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5445 }
5446 InnerDeclRefsCount.push_back(countOfInnerDecls);
5447
5448 std::string FuncName;
5449
5450 if (CurFunctionDef)
5451 FuncName = CurFunctionDef->getNameAsString();
5452 else if (CurMethodDef)
5453 BuildUniqueMethodName(FuncName, CurMethodDef);
5454 else if (GlobalVarDecl)
5455 FuncName = std::string(GlobalVarDecl->getNameAsString());
5456
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005457 bool GlobalBlockExpr =
5458 block->getDeclContext()->getRedeclContext()->isFileContext();
5459
5460 if (GlobalBlockExpr && !GlobalVarDecl) {
5461 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5462 GlobalBlockExpr = false;
5463 }
5464
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005465 std::string BlockNumber = utostr(Blocks.size()-1);
5466
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005467 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5468
5469 // Get a pointer to the function type so we can cast appropriately.
5470 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5471 QualType FType = Context->getPointerType(BFT);
5472
5473 FunctionDecl *FD;
5474 Expr *NewRep;
5475
5476 // Simulate a contructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005477 std::string Tag;
5478
5479 if (GlobalBlockExpr)
5480 Tag = "__global_";
5481 else
5482 Tag = "__";
5483 Tag += FuncName + "_block_impl_" + BlockNumber;
5484
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005485 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005486 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005487 SourceLocation());
5488
5489 SmallVector<Expr*, 4> InitExprs;
5490
5491 // Initialize the block function.
5492 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005493 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5494 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005495 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5496 CK_BitCast, Arg);
5497 InitExprs.push_back(castExpr);
5498
5499 // Initialize the block descriptor.
5500 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5501
5502 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5503 SourceLocation(), SourceLocation(),
5504 &Context->Idents.get(DescData.c_str()),
5505 Context->VoidPtrTy, 0,
5506 SC_Static, SC_None);
5507 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005508 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005509 Context->VoidPtrTy,
5510 VK_LValue,
5511 SourceLocation()),
5512 UO_AddrOf,
5513 Context->getPointerType(Context->VoidPtrTy),
5514 VK_RValue, OK_Ordinary,
5515 SourceLocation());
5516 InitExprs.push_back(DescRefExpr);
5517
5518 // Add initializers for any closure decl refs.
5519 if (BlockDeclRefs.size()) {
5520 Expr *Exp;
5521 // Output all "by copy" declarations.
5522 for (SmallVector<ValueDecl*,8>::iterator I = BlockByCopyDecls.begin(),
5523 E = BlockByCopyDecls.end(); I != E; ++I) {
5524 if (isObjCType((*I)->getType())) {
5525 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5526 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005527 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5528 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005529 if (HasLocalVariableExternalStorage(*I)) {
5530 QualType QT = (*I)->getType();
5531 QT = Context->getPointerType(QT);
5532 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5533 OK_Ordinary, SourceLocation());
5534 }
5535 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5536 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005537 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5538 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005539 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5540 CK_BitCast, Arg);
5541 } else {
5542 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005543 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5544 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005545 if (HasLocalVariableExternalStorage(*I)) {
5546 QualType QT = (*I)->getType();
5547 QT = Context->getPointerType(QT);
5548 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5549 OK_Ordinary, SourceLocation());
5550 }
5551
5552 }
5553 InitExprs.push_back(Exp);
5554 }
5555 // Output all "by ref" declarations.
5556 for (SmallVector<ValueDecl*,8>::iterator I = BlockByRefDecls.begin(),
5557 E = BlockByRefDecls.end(); I != E; ++I) {
5558 ValueDecl *ND = (*I);
5559 std::string Name(ND->getNameAsString());
5560 std::string RecName;
5561 RewriteByRefString(RecName, Name, ND, true);
5562 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5563 + sizeof("struct"));
5564 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5565 SourceLocation(), SourceLocation(),
5566 II);
5567 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5568 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5569
5570 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005571 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005572 SourceLocation());
5573 bool isNestedCapturedVar = false;
5574 if (block)
5575 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5576 ce = block->capture_end(); ci != ce; ++ci) {
5577 const VarDecl *variable = ci->getVariable();
5578 if (variable == ND && ci->isNested()) {
5579 assert (ci->isByRef() &&
5580 "SynthBlockInitExpr - captured block variable is not byref");
5581 isNestedCapturedVar = true;
5582 break;
5583 }
5584 }
5585 // captured nested byref variable has its address passed. Do not take
5586 // its address again.
5587 if (!isNestedCapturedVar)
5588 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5589 Context->getPointerType(Exp->getType()),
5590 VK_RValue, OK_Ordinary, SourceLocation());
5591 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5592 InitExprs.push_back(Exp);
5593 }
5594 }
5595 if (ImportedBlockDecls.size()) {
5596 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5597 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5598 unsigned IntSize =
5599 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5600 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5601 Context->IntTy, SourceLocation());
5602 InitExprs.push_back(FlagExp);
5603 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005604 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005605 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005606
5607 if (GlobalBlockExpr) {
5608 assert (GlobalConstructionExp == 0 &&
5609 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5610 GlobalConstructionExp = NewRep;
5611 NewRep = DRE;
5612 }
5613
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005614 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5615 Context->getPointerType(NewRep->getType()),
5616 VK_RValue, OK_Ordinary, SourceLocation());
5617 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5618 NewRep);
5619 BlockDeclRefs.clear();
5620 BlockByRefDecls.clear();
5621 BlockByRefDeclsPtrSet.clear();
5622 BlockByCopyDecls.clear();
5623 BlockByCopyDeclsPtrSet.clear();
5624 ImportedBlockDecls.clear();
5625 return NewRep;
5626}
5627
5628bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5629 if (const ObjCForCollectionStmt * CS =
5630 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5631 return CS->getElement() == DS;
5632 return false;
5633}
5634
5635//===----------------------------------------------------------------------===//
5636// Function Body / Expression rewriting
5637//===----------------------------------------------------------------------===//
5638
5639Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5640 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5641 isa<DoStmt>(S) || isa<ForStmt>(S))
5642 Stmts.push_back(S);
5643 else if (isa<ObjCForCollectionStmt>(S)) {
5644 Stmts.push_back(S);
5645 ObjCBcLabelNo.push_back(++BcLabelCount);
5646 }
5647
5648 // Pseudo-object operations and ivar references need special
5649 // treatment because we're going to recursively rewrite them.
5650 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5651 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5652 return RewritePropertyOrImplicitSetter(PseudoOp);
5653 } else {
5654 return RewritePropertyOrImplicitGetter(PseudoOp);
5655 }
5656 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5657 return RewriteObjCIvarRefExpr(IvarRefExpr);
5658 }
5659
5660 SourceRange OrigStmtRange = S->getSourceRange();
5661
5662 // Perform a bottom up rewrite of all children.
5663 for (Stmt::child_range CI = S->children(); CI; ++CI)
5664 if (*CI) {
5665 Stmt *childStmt = (*CI);
5666 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5667 if (newStmt) {
5668 *CI = newStmt;
5669 }
5670 }
5671
5672 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005673 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005674 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5675 InnerContexts.insert(BE->getBlockDecl());
5676 ImportedLocalExternalDecls.clear();
5677 GetInnerBlockDeclRefExprs(BE->getBody(),
5678 InnerBlockDeclRefs, InnerContexts);
5679 // Rewrite the block body in place.
5680 Stmt *SaveCurrentBody = CurrentBody;
5681 CurrentBody = BE->getBody();
5682 PropParentMap = 0;
5683 // block literal on rhs of a property-dot-sytax assignment
5684 // must be replaced by its synthesize ast so getRewrittenText
5685 // works as expected. In this case, what actually ends up on RHS
5686 // is the blockTranscribed which is the helper function for the
5687 // block literal; as in: self.c = ^() {[ace ARR];};
5688 bool saveDisableReplaceStmt = DisableReplaceStmt;
5689 DisableReplaceStmt = false;
5690 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5691 DisableReplaceStmt = saveDisableReplaceStmt;
5692 CurrentBody = SaveCurrentBody;
5693 PropParentMap = 0;
5694 ImportedLocalExternalDecls.clear();
5695 // Now we snarf the rewritten text and stash it away for later use.
5696 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5697 RewrittenBlockExprs[BE] = Str;
5698
5699 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5700
5701 //blockTranscribed->dump();
5702 ReplaceStmt(S, blockTranscribed);
5703 return blockTranscribed;
5704 }
5705 // Handle specific things.
5706 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5707 return RewriteAtEncode(AtEncode);
5708
5709 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5710 return RewriteAtSelector(AtSelector);
5711
5712 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5713 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005714
5715 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5716 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005717
Patrick Beardeb382ec2012-04-19 00:25:12 +00005718 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5719 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005720
5721 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5722 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005723
5724 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5725 dyn_cast<ObjCDictionaryLiteral>(S))
5726 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005727
5728 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5729#if 0
5730 // Before we rewrite it, put the original message expression in a comment.
5731 SourceLocation startLoc = MessExpr->getLocStart();
5732 SourceLocation endLoc = MessExpr->getLocEnd();
5733
5734 const char *startBuf = SM->getCharacterData(startLoc);
5735 const char *endBuf = SM->getCharacterData(endLoc);
5736
5737 std::string messString;
5738 messString += "// ";
5739 messString.append(startBuf, endBuf-startBuf+1);
5740 messString += "\n";
5741
5742 // FIXME: Missing definition of
5743 // InsertText(clang::SourceLocation, char const*, unsigned int).
5744 // InsertText(startLoc, messString.c_str(), messString.size());
5745 // Tried this, but it didn't work either...
5746 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5747#endif
5748 return RewriteMessageExpr(MessExpr);
5749 }
5750
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005751 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5752 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5753 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5754 }
5755
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005756 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5757 return RewriteObjCTryStmt(StmtTry);
5758
5759 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5760 return RewriteObjCSynchronizedStmt(StmtTry);
5761
5762 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5763 return RewriteObjCThrowStmt(StmtThrow);
5764
5765 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5766 return RewriteObjCProtocolExpr(ProtocolExp);
5767
5768 if (ObjCForCollectionStmt *StmtForCollection =
5769 dyn_cast<ObjCForCollectionStmt>(S))
5770 return RewriteObjCForCollectionStmt(StmtForCollection,
5771 OrigStmtRange.getEnd());
5772 if (BreakStmt *StmtBreakStmt =
5773 dyn_cast<BreakStmt>(S))
5774 return RewriteBreakStmt(StmtBreakStmt);
5775 if (ContinueStmt *StmtContinueStmt =
5776 dyn_cast<ContinueStmt>(S))
5777 return RewriteContinueStmt(StmtContinueStmt);
5778
5779 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5780 // and cast exprs.
5781 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5782 // FIXME: What we're doing here is modifying the type-specifier that
5783 // precedes the first Decl. In the future the DeclGroup should have
5784 // a separate type-specifier that we can rewrite.
5785 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5786 // the context of an ObjCForCollectionStmt. For example:
5787 // NSArray *someArray;
5788 // for (id <FooProtocol> index in someArray) ;
5789 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5790 // and it depends on the original text locations/positions.
5791 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5792 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5793
5794 // Blocks rewrite rules.
5795 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5796 DI != DE; ++DI) {
5797 Decl *SD = *DI;
5798 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5799 if (isTopLevelBlockPointerType(ND->getType()))
5800 RewriteBlockPointerDecl(ND);
5801 else if (ND->getType()->isFunctionPointerType())
5802 CheckFunctionPointerDecl(ND->getType(), ND);
5803 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5804 if (VD->hasAttr<BlocksAttr>()) {
5805 static unsigned uniqueByrefDeclCount = 0;
5806 assert(!BlockByRefDeclNo.count(ND) &&
5807 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5808 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005809 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005810 }
5811 else
5812 RewriteTypeOfDecl(VD);
5813 }
5814 }
5815 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5816 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5817 RewriteBlockPointerDecl(TD);
5818 else if (TD->getUnderlyingType()->isFunctionPointerType())
5819 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5820 }
5821 }
5822 }
5823
5824 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5825 RewriteObjCQualifiedInterfaceTypes(CE);
5826
5827 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5828 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5829 assert(!Stmts.empty() && "Statement stack is empty");
5830 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5831 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5832 && "Statement stack mismatch");
5833 Stmts.pop_back();
5834 }
5835 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005836 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5837 ValueDecl *VD = DRE->getDecl();
5838 if (VD->hasAttr<BlocksAttr>())
5839 return RewriteBlockDeclRefExpr(DRE);
5840 if (HasLocalVariableExternalStorage(VD))
5841 return RewriteLocalVariableExternalStorage(DRE);
5842 }
5843
5844 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5845 if (CE->getCallee()->getType()->isBlockPointerType()) {
5846 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5847 ReplaceStmt(S, BlockCall);
5848 return BlockCall;
5849 }
5850 }
5851 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5852 RewriteCastExpr(CE);
5853 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005854 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5855 RewriteImplicitCastObjCExpr(ICE);
5856 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005857#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005858
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005859 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5860 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5861 ICE->getSubExpr(),
5862 SourceLocation());
5863 // Get the new text.
5864 std::string SStr;
5865 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005866 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005867 const std::string &Str = Buf.str();
5868
5869 printf("CAST = %s\n", &Str[0]);
5870 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5871 delete S;
5872 return Replacement;
5873 }
5874#endif
5875 // Return this stmt unmodified.
5876 return S;
5877}
5878
5879void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5880 for (RecordDecl::field_iterator i = RD->field_begin(),
5881 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005882 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005883 if (isTopLevelBlockPointerType(FD->getType()))
5884 RewriteBlockPointerDecl(FD);
5885 if (FD->getType()->isObjCQualifiedIdType() ||
5886 FD->getType()->isObjCQualifiedInterfaceType())
5887 RewriteObjCQualifiedInterfaceTypes(FD);
5888 }
5889}
5890
5891/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5892/// main file of the input.
5893void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5894 switch (D->getKind()) {
5895 case Decl::Function: {
5896 FunctionDecl *FD = cast<FunctionDecl>(D);
5897 if (FD->isOverloadedOperator())
5898 return;
5899
5900 // Since function prototypes don't have ParmDecl's, we check the function
5901 // prototype. This enables us to rewrite function declarations and
5902 // definitions using the same code.
5903 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5904
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005905 if (!FD->isThisDeclarationADefinition())
5906 break;
5907
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005908 // FIXME: If this should support Obj-C++, support CXXTryStmt
5909 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5910 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005911 CurrentBody = Body;
5912 Body =
5913 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5914 FD->setBody(Body);
5915 CurrentBody = 0;
5916 if (PropParentMap) {
5917 delete PropParentMap;
5918 PropParentMap = 0;
5919 }
5920 // This synthesizes and inserts the block "impl" struct, invoke function,
5921 // and any copy/dispose helper functions.
5922 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005923 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005924 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005925 }
5926 break;
5927 }
5928 case Decl::ObjCMethod: {
5929 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5930 if (CompoundStmt *Body = MD->getCompoundBody()) {
5931 CurMethodDef = MD;
5932 CurrentBody = Body;
5933 Body =
5934 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5935 MD->setBody(Body);
5936 CurrentBody = 0;
5937 if (PropParentMap) {
5938 delete PropParentMap;
5939 PropParentMap = 0;
5940 }
5941 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005942 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005943 CurMethodDef = 0;
5944 }
5945 break;
5946 }
5947 case Decl::ObjCImplementation: {
5948 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5949 ClassImplementation.push_back(CI);
5950 break;
5951 }
5952 case Decl::ObjCCategoryImpl: {
5953 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5954 CategoryImplementation.push_back(CI);
5955 break;
5956 }
5957 case Decl::Var: {
5958 VarDecl *VD = cast<VarDecl>(D);
5959 RewriteObjCQualifiedInterfaceTypes(VD);
5960 if (isTopLevelBlockPointerType(VD->getType()))
5961 RewriteBlockPointerDecl(VD);
5962 else if (VD->getType()->isFunctionPointerType()) {
5963 CheckFunctionPointerDecl(VD->getType(), VD);
5964 if (VD->getInit()) {
5965 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5966 RewriteCastExpr(CE);
5967 }
5968 }
5969 } else if (VD->getType()->isRecordType()) {
5970 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5971 if (RD->isCompleteDefinition())
5972 RewriteRecordBody(RD);
5973 }
5974 if (VD->getInit()) {
5975 GlobalVarDecl = VD;
5976 CurrentBody = VD->getInit();
5977 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5978 CurrentBody = 0;
5979 if (PropParentMap) {
5980 delete PropParentMap;
5981 PropParentMap = 0;
5982 }
5983 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5984 GlobalVarDecl = 0;
5985
5986 // This is needed for blocks.
5987 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5988 RewriteCastExpr(CE);
5989 }
5990 }
5991 break;
5992 }
5993 case Decl::TypeAlias:
5994 case Decl::Typedef: {
5995 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5996 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5997 RewriteBlockPointerDecl(TD);
5998 else if (TD->getUnderlyingType()->isFunctionPointerType())
5999 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
6000 }
6001 break;
6002 }
6003 case Decl::CXXRecord:
6004 case Decl::Record: {
6005 RecordDecl *RD = cast<RecordDecl>(D);
6006 if (RD->isCompleteDefinition())
6007 RewriteRecordBody(RD);
6008 break;
6009 }
6010 default:
6011 break;
6012 }
6013 // Nothing yet.
6014}
6015
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006016/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6017/// protocol reference symbols in the for of:
6018/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6019static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6020 ObjCProtocolDecl *PDecl,
6021 std::string &Result) {
6022 // Also output .objc_protorefs$B section and its meta-data.
6023 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006024 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006025 Result += "struct _protocol_t *";
6026 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6027 Result += PDecl->getNameAsString();
6028 Result += " = &";
6029 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6030 Result += ";\n";
6031}
6032
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006033void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6034 if (Diags.hasErrorOccurred())
6035 return;
6036
6037 RewriteInclude();
6038
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006039 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6040 // translation of function bodies were postponed untill all class and
6041 // their extensions and implementations are seen. This is because, we
6042 // cannot build grouping structs for bitfields untill they are all seen.
6043 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6044 HandleTopLevelSingleDecl(FDecl);
6045 }
6046
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006047 // Here's a great place to add any extra declarations that may be needed.
6048 // Write out meta data for each @protocol(<expr>).
6049 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006050 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006051 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006052 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6053 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006054
6055 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006056
6057 if (ClassImplementation.size() || CategoryImplementation.size())
6058 RewriteImplementations();
6059
Fariborz Jahanian57317782012-02-21 23:58:41 +00006060 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6061 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6062 // Write struct declaration for the class matching its ivar declarations.
6063 // Note that for modern abi, this is postponed until the end of TU
6064 // because class extensions and the implementation might declare their own
6065 // private ivars.
6066 RewriteInterfaceDecl(CDecl);
6067 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006068
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006069 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6070 // we are done.
6071 if (const RewriteBuffer *RewriteBuf =
6072 Rewrite.getRewriteBufferFor(MainFileID)) {
6073 //printf("Changed:\n");
6074 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6075 } else {
6076 llvm::errs() << "No changes\n";
6077 }
6078
6079 if (ClassImplementation.size() || CategoryImplementation.size() ||
6080 ProtocolExprDecls.size()) {
6081 // Rewrite Objective-c meta data*
6082 std::string ResultStr;
6083 RewriteMetaDataIntoBuffer(ResultStr);
6084 // Emit metadata.
6085 *OutFile << ResultStr;
6086 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006087 // Emit ImageInfo;
6088 {
6089 std::string ResultStr;
6090 WriteImageInfo(ResultStr);
6091 *OutFile << ResultStr;
6092 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006093 OutFile->flush();
6094}
6095
6096void RewriteModernObjC::Initialize(ASTContext &context) {
6097 InitializeCommon(context);
6098
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006099 Preamble += "#ifndef __OBJC2__\n";
6100 Preamble += "#define __OBJC2__\n";
6101 Preamble += "#endif\n";
6102
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006103 // declaring objc_selector outside the parameter list removes a silly
6104 // scope related warning...
6105 if (IsHeader)
6106 Preamble = "#pragma once\n";
6107 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006108 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6109 Preamble += "\n\tstruct objc_object *superClass; ";
6110 // Add a constructor for creating temporary objects.
6111 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6112 Preamble += ": object(o), superClass(s) {} ";
6113 Preamble += "\n};\n";
6114
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006115 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006116 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006117 // These are currently generated.
6118 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006119 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006120 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006121 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6122 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006123 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006124 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006125 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6126 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006127 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006128
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006129 // These need be generated for performance. Currently they are not,
6130 // using API calls instead.
6131 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6132 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6133 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6134
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006135 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006136 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6137 Preamble += "typedef struct objc_object Protocol;\n";
6138 Preamble += "#define _REWRITER_typedef_Protocol\n";
6139 Preamble += "#endif\n";
6140 if (LangOpts.MicrosoftExt) {
6141 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6142 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006143 }
6144 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006145 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006146
6147 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6148 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6149 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6150 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6151 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6152
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006153 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006154 Preamble += "(const char *);\n";
6155 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6156 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006157 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006158 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006159 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006160 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006161 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6162 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006163 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
6164 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6165 Preamble += "struct __objcFastEnumerationState {\n\t";
6166 Preamble += "unsigned long state;\n\t";
6167 Preamble += "void **itemsPtr;\n\t";
6168 Preamble += "unsigned long *mutationsPtr;\n\t";
6169 Preamble += "unsigned long extra[5];\n};\n";
6170 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6171 Preamble += "#define __FASTENUMERATIONSTATE\n";
6172 Preamble += "#endif\n";
6173 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6174 Preamble += "struct __NSConstantStringImpl {\n";
6175 Preamble += " int *isa;\n";
6176 Preamble += " int flags;\n";
6177 Preamble += " char *str;\n";
6178 Preamble += " long length;\n";
6179 Preamble += "};\n";
6180 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6181 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6182 Preamble += "#else\n";
6183 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6184 Preamble += "#endif\n";
6185 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6186 Preamble += "#endif\n";
6187 // Blocks preamble.
6188 Preamble += "#ifndef BLOCK_IMPL\n";
6189 Preamble += "#define BLOCK_IMPL\n";
6190 Preamble += "struct __block_impl {\n";
6191 Preamble += " void *isa;\n";
6192 Preamble += " int Flags;\n";
6193 Preamble += " int Reserved;\n";
6194 Preamble += " void *FuncPtr;\n";
6195 Preamble += "};\n";
6196 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6197 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6198 Preamble += "extern \"C\" __declspec(dllexport) "
6199 "void _Block_object_assign(void *, const void *, const int);\n";
6200 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6201 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6202 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6203 Preamble += "#else\n";
6204 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6205 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6206 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6207 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6208 Preamble += "#endif\n";
6209 Preamble += "#endif\n";
6210 if (LangOpts.MicrosoftExt) {
6211 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6212 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6213 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6214 Preamble += "#define __attribute__(X)\n";
6215 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006216 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006217 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006218 Preamble += "#endif\n";
6219 Preamble += "#ifndef __block\n";
6220 Preamble += "#define __block\n";
6221 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006222 }
6223 else {
6224 Preamble += "#define __block\n";
6225 Preamble += "#define __weak\n";
6226 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006227
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006228 // Declarations required for modern objective-c array and dictionary literals.
6229 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006230 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006231 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006232 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006233 Preamble += "\tva_list marker;\n";
6234 Preamble += "\tva_start(marker, count);\n";
6235 Preamble += "\tarr = new void *[count];\n";
6236 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6237 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6238 Preamble += "\tva_end( marker );\n";
6239 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006240 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006241 Preamble += "\tdelete[] arr;\n";
6242 Preamble += " }\n";
6243 Preamble += "};\n";
6244
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006245 // Declaration required for implementation of @autoreleasepool statement.
6246 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6247 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6248 Preamble += "struct __AtAutoreleasePool {\n";
6249 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6250 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6251 Preamble += " void * atautoreleasepoolobj;\n";
6252 Preamble += "};\n";
6253
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006254 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6255 // as this avoids warning in any 64bit/32bit compilation model.
6256 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6257}
6258
6259/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6260/// ivar offset.
6261void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6262 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006263 Result += "__OFFSETOFIVAR__(struct ";
6264 Result += ivar->getContainingInterface()->getNameAsString();
6265 if (LangOpts.MicrosoftExt)
6266 Result += "_IMPL";
6267 Result += ", ";
6268 if (ivar->isBitField())
6269 ObjCIvarBitfieldGroupDecl(ivar, Result);
6270 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006271 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006272 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006273}
6274
6275/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6276/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006277/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006278/// char *attributes;
6279/// }
6280
6281/// struct _prop_list_t {
6282/// uint32_t entsize; // sizeof(struct _prop_t)
6283/// uint32_t count_of_properties;
6284/// struct _prop_t prop_list[count_of_properties];
6285/// }
6286
6287/// struct _protocol_t;
6288
6289/// struct _protocol_list_t {
6290/// long protocol_count; // Note, this is 32/64 bit
6291/// struct _protocol_t * protocol_list[protocol_count];
6292/// }
6293
6294/// struct _objc_method {
6295/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006296/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006297/// char *_imp;
6298/// }
6299
6300/// struct _method_list_t {
6301/// uint32_t entsize; // sizeof(struct _objc_method)
6302/// uint32_t method_count;
6303/// struct _objc_method method_list[method_count];
6304/// }
6305
6306/// struct _protocol_t {
6307/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006308/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006309/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006310/// const struct method_list_t *instance_methods;
6311/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006312/// const struct method_list_t *optionalInstanceMethods;
6313/// const struct method_list_t *optionalClassMethods;
6314/// const struct _prop_list_t * properties;
6315/// const uint32_t size; // sizeof(struct _protocol_t)
6316/// const uint32_t flags; // = 0
6317/// const char ** extendedMethodTypes;
6318/// }
6319
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006320/// struct _ivar_t {
6321/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006322/// const char *name;
6323/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006324/// uint32_t alignment;
6325/// uint32_t size;
6326/// }
6327
6328/// struct _ivar_list_t {
6329/// uint32 entsize; // sizeof(struct _ivar_t)
6330/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006331/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006332/// }
6333
6334/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006335/// uint32_t flags;
6336/// uint32_t instanceStart;
6337/// uint32_t instanceSize;
6338/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006339/// const uint8_t *ivarLayout;
6340/// const char *name;
6341/// const struct _method_list_t *baseMethods;
6342/// const struct _protocol_list_t *baseProtocols;
6343/// const struct _ivar_list_t *ivars;
6344/// const uint8_t *weakIvarLayout;
6345/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006346/// }
6347
6348/// struct _class_t {
6349/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006350/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006351/// void *cache;
6352/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006353/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006354/// }
6355
6356/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006357/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006358/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006359/// const struct _method_list_t *instance_methods;
6360/// const struct _method_list_t *class_methods;
6361/// const struct _protocol_list_t *protocols;
6362/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006363/// }
6364
6365/// MessageRefTy - LLVM for:
6366/// struct _message_ref_t {
6367/// IMP messenger;
6368/// SEL name;
6369/// };
6370
6371/// SuperMessageRefTy - LLVM for:
6372/// struct _super_message_ref_t {
6373/// SUPER_IMP messenger;
6374/// SEL name;
6375/// };
6376
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006377static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006378 static bool meta_data_declared = false;
6379 if (meta_data_declared)
6380 return;
6381
6382 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006383 Result += "\tconst char *name;\n";
6384 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006385 Result += "};\n";
6386
6387 Result += "\nstruct _protocol_t;\n";
6388
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006389 Result += "\nstruct _objc_method {\n";
6390 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006391 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006392 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006393 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006394
6395 Result += "\nstruct _protocol_t {\n";
6396 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006397 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006398 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006399 Result += "\tconst struct method_list_t *instance_methods;\n";
6400 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006401 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6402 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6403 Result += "\tconst struct _prop_list_t * properties;\n";
6404 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6405 Result += "\tconst unsigned int flags; // = 0\n";
6406 Result += "\tconst char ** extendedMethodTypes;\n";
6407 Result += "};\n";
6408
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006409 Result += "\nstruct _ivar_t {\n";
6410 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006411 Result += "\tconst char *name;\n";
6412 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006413 Result += "\tunsigned int alignment;\n";
6414 Result += "\tunsigned int size;\n";
6415 Result += "};\n";
6416
6417 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006418 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006419 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006420 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006421 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6422 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006423 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006424 Result += "\tconst unsigned char *ivarLayout;\n";
6425 Result += "\tconst char *name;\n";
6426 Result += "\tconst struct _method_list_t *baseMethods;\n";
6427 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6428 Result += "\tconst struct _ivar_list_t *ivars;\n";
6429 Result += "\tconst unsigned char *weakIvarLayout;\n";
6430 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006431 Result += "};\n";
6432
6433 Result += "\nstruct _class_t {\n";
6434 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006435 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006436 Result += "\tvoid *cache;\n";
6437 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006438 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006439 Result += "};\n";
6440
6441 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006442 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006443 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006444 Result += "\tconst struct _method_list_t *instance_methods;\n";
6445 Result += "\tconst struct _method_list_t *class_methods;\n";
6446 Result += "\tconst struct _protocol_list_t *protocols;\n";
6447 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006448 Result += "};\n";
6449
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006450 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006451 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006452 meta_data_declared = true;
6453}
6454
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006455static void Write_protocol_list_t_TypeDecl(std::string &Result,
6456 long super_protocol_count) {
6457 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6458 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6459 Result += "\tstruct _protocol_t *super_protocols[";
6460 Result += utostr(super_protocol_count); Result += "];\n";
6461 Result += "}";
6462}
6463
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006464static void Write_method_list_t_TypeDecl(std::string &Result,
6465 unsigned int method_count) {
6466 Result += "struct /*_method_list_t*/"; Result += " {\n";
6467 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6468 Result += "\tunsigned int method_count;\n";
6469 Result += "\tstruct _objc_method method_list[";
6470 Result += utostr(method_count); Result += "];\n";
6471 Result += "}";
6472}
6473
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006474static void Write__prop_list_t_TypeDecl(std::string &Result,
6475 unsigned int property_count) {
6476 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6477 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6478 Result += "\tunsigned int count_of_properties;\n";
6479 Result += "\tstruct _prop_t prop_list[";
6480 Result += utostr(property_count); Result += "];\n";
6481 Result += "}";
6482}
6483
Fariborz Jahanianae932952012-02-10 20:47:10 +00006484static void Write__ivar_list_t_TypeDecl(std::string &Result,
6485 unsigned int ivar_count) {
6486 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6487 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6488 Result += "\tunsigned int count;\n";
6489 Result += "\tstruct _ivar_t ivar_list[";
6490 Result += utostr(ivar_count); Result += "];\n";
6491 Result += "}";
6492}
6493
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006494static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6495 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6496 StringRef VarName,
6497 StringRef ProtocolName) {
6498 if (SuperProtocols.size() > 0) {
6499 Result += "\nstatic ";
6500 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6501 Result += " "; Result += VarName;
6502 Result += ProtocolName;
6503 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6504 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6505 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6506 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6507 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6508 Result += SuperPD->getNameAsString();
6509 if (i == e-1)
6510 Result += "\n};\n";
6511 else
6512 Result += ",\n";
6513 }
6514 }
6515}
6516
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006517static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6518 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006519 ArrayRef<ObjCMethodDecl *> Methods,
6520 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006521 StringRef TopLevelDeclName,
6522 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006523 if (Methods.size() > 0) {
6524 Result += "\nstatic ";
6525 Write_method_list_t_TypeDecl(Result, Methods.size());
6526 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006527 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006528 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6529 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6530 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6531 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6532 ObjCMethodDecl *MD = Methods[i];
6533 if (i == 0)
6534 Result += "\t{{(struct objc_selector *)\"";
6535 else
6536 Result += "\t{(struct objc_selector *)\"";
6537 Result += (MD)->getSelector().getAsString(); Result += "\"";
6538 Result += ", ";
6539 std::string MethodTypeString;
6540 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6541 Result += "\""; Result += MethodTypeString; Result += "\"";
6542 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006543 if (!MethodImpl)
6544 Result += "0";
6545 else {
6546 Result += "(void *)";
6547 Result += RewriteObj.MethodInternalNames[MD];
6548 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006549 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006550 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006551 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006552 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006553 }
6554 Result += "};\n";
6555 }
6556}
6557
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006558static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006559 ASTContext *Context, std::string &Result,
6560 ArrayRef<ObjCPropertyDecl *> Properties,
6561 const Decl *Container,
6562 StringRef VarName,
6563 StringRef ProtocolName) {
6564 if (Properties.size() > 0) {
6565 Result += "\nstatic ";
6566 Write__prop_list_t_TypeDecl(Result, Properties.size());
6567 Result += " "; Result += VarName;
6568 Result += ProtocolName;
6569 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6570 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6571 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6572 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6573 ObjCPropertyDecl *PropDecl = Properties[i];
6574 if (i == 0)
6575 Result += "\t{{\"";
6576 else
6577 Result += "\t{\"";
6578 Result += PropDecl->getName(); Result += "\",";
6579 std::string PropertyTypeString, QuotePropertyTypeString;
6580 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6581 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6582 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6583 if (i == e-1)
6584 Result += "}}\n";
6585 else
6586 Result += "},\n";
6587 }
6588 Result += "};\n";
6589 }
6590}
6591
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006592// Metadata flags
6593enum MetaDataDlags {
6594 CLS = 0x0,
6595 CLS_META = 0x1,
6596 CLS_ROOT = 0x2,
6597 OBJC2_CLS_HIDDEN = 0x10,
6598 CLS_EXCEPTION = 0x20,
6599
6600 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6601 CLS_HAS_IVAR_RELEASER = 0x40,
6602 /// class was compiled with -fobjc-arr
6603 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6604};
6605
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006606static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6607 unsigned int flags,
6608 const std::string &InstanceStart,
6609 const std::string &InstanceSize,
6610 ArrayRef<ObjCMethodDecl *>baseMethods,
6611 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6612 ArrayRef<ObjCIvarDecl *>ivars,
6613 ArrayRef<ObjCPropertyDecl *>Properties,
6614 StringRef VarName,
6615 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006616 Result += "\nstatic struct _class_ro_t ";
6617 Result += VarName; Result += ClassName;
6618 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6619 Result += "\t";
6620 Result += llvm::utostr(flags); Result += ", ";
6621 Result += InstanceStart; Result += ", ";
6622 Result += InstanceSize; Result += ", \n";
6623 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006624 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6625 if (Triple.getArch() == llvm::Triple::x86_64)
6626 // uint32_t const reserved; // only when building for 64bit targets
6627 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006628 // const uint8_t * const ivarLayout;
6629 Result += "0, \n\t";
6630 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006631 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006632 if (baseMethods.size() > 0) {
6633 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006634 if (metaclass)
6635 Result += "_OBJC_$_CLASS_METHODS_";
6636 else
6637 Result += "_OBJC_$_INSTANCE_METHODS_";
6638 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006639 Result += ",\n\t";
6640 }
6641 else
6642 Result += "0, \n\t";
6643
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006644 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006645 Result += "(const struct _objc_protocol_list *)&";
6646 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6647 Result += ",\n\t";
6648 }
6649 else
6650 Result += "0, \n\t";
6651
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006652 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006653 Result += "(const struct _ivar_list_t *)&";
6654 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6655 Result += ",\n\t";
6656 }
6657 else
6658 Result += "0, \n\t";
6659
6660 // weakIvarLayout
6661 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006662 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006663 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006664 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006665 Result += ",\n";
6666 }
6667 else
6668 Result += "0, \n";
6669
6670 Result += "};\n";
6671}
6672
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006673static void Write_class_t(ASTContext *Context, std::string &Result,
6674 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006675 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6676 bool rootClass = (!CDecl->getSuperClass());
6677 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006678
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006679 if (!rootClass) {
6680 // Find the Root class
6681 RootClass = CDecl->getSuperClass();
6682 while (RootClass->getSuperClass()) {
6683 RootClass = RootClass->getSuperClass();
6684 }
6685 }
6686
6687 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006688 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006689 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006690 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006691 if (CDecl->getImplementation())
6692 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006693 else
6694 Result += "__declspec(dllimport) ";
6695
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006696 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006697 Result += CDecl->getNameAsString();
6698 Result += ";\n";
6699 }
6700 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006701 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006702 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006703 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006704 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006705 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006706 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006707 else
6708 Result += "__declspec(dllimport) ";
6709
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006710 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006711 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006712 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006713 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006714
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006715 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006716 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006717 if (RootClass->getImplementation())
6718 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006719 else
6720 Result += "__declspec(dllimport) ";
6721
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006722 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006723 Result += VarName;
6724 Result += RootClass->getNameAsString();
6725 Result += ";\n";
6726 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006727 }
6728
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006729 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6730 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006731 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6732 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006733 if (metaclass) {
6734 if (!rootClass) {
6735 Result += "0, // &"; Result += VarName;
6736 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006737 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006738 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006739 Result += CDecl->getSuperClass()->getNameAsString();
6740 Result += ",\n\t";
6741 }
6742 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006743 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006744 Result += CDecl->getNameAsString();
6745 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006746 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006747 Result += ",\n\t";
6748 }
6749 }
6750 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006751 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006752 Result += CDecl->getNameAsString();
6753 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006754 if (!rootClass) {
6755 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006756 Result += CDecl->getSuperClass()->getNameAsString();
6757 Result += ",\n\t";
6758 }
6759 else
6760 Result += "0,\n\t";
6761 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006762 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6763 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6764 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006765 Result += "&_OBJC_METACLASS_RO_$_";
6766 else
6767 Result += "&_OBJC_CLASS_RO_$_";
6768 Result += CDecl->getNameAsString();
6769 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006770
6771 // Add static function to initialize some of the meta-data fields.
6772 // avoid doing it twice.
6773 if (metaclass)
6774 return;
6775
6776 const ObjCInterfaceDecl *SuperClass =
6777 rootClass ? CDecl : CDecl->getSuperClass();
6778
6779 Result += "static void OBJC_CLASS_SETUP_$_";
6780 Result += CDecl->getNameAsString();
6781 Result += "(void ) {\n";
6782 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6783 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006784 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006785
6786 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006787 Result += ".superclass = ";
6788 if (rootClass)
6789 Result += "&OBJC_CLASS_$_";
6790 else
6791 Result += "&OBJC_METACLASS_$_";
6792
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006793 Result += SuperClass->getNameAsString(); Result += ";\n";
6794
6795 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6796 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6797
6798 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6799 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6800 Result += CDecl->getNameAsString(); Result += ";\n";
6801
6802 if (!rootClass) {
6803 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6804 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6805 Result += SuperClass->getNameAsString(); Result += ";\n";
6806 }
6807
6808 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6809 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6810 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006811}
6812
Fariborz Jahanian61186122012-02-17 18:40:41 +00006813static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6814 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006815 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006816 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006817 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6818 ArrayRef<ObjCMethodDecl *> ClassMethods,
6819 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6820 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006821 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006822 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006823 // must declare an extern class object in case this class is not implemented
6824 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006825 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006826 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006827 if (ClassDecl->getImplementation())
6828 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006829 else
6830 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006831
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006832 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006833 Result += "OBJC_CLASS_$_"; Result += ClassName;
6834 Result += ";\n";
6835
Fariborz Jahanian61186122012-02-17 18:40:41 +00006836 Result += "\nstatic struct _category_t ";
6837 Result += "_OBJC_$_CATEGORY_";
6838 Result += ClassName; Result += "_$_"; Result += CatName;
6839 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6840 Result += "{\n";
6841 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006842 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006843 Result += ",\n";
6844 if (InstanceMethods.size() > 0) {
6845 Result += "\t(const struct _method_list_t *)&";
6846 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6847 Result += ClassName; Result += "_$_"; Result += CatName;
6848 Result += ",\n";
6849 }
6850 else
6851 Result += "\t0,\n";
6852
6853 if (ClassMethods.size() > 0) {
6854 Result += "\t(const struct _method_list_t *)&";
6855 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6856 Result += ClassName; Result += "_$_"; Result += CatName;
6857 Result += ",\n";
6858 }
6859 else
6860 Result += "\t0,\n";
6861
6862 if (RefedProtocols.size() > 0) {
6863 Result += "\t(const struct _protocol_list_t *)&";
6864 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6865 Result += ClassName; Result += "_$_"; Result += CatName;
6866 Result += ",\n";
6867 }
6868 else
6869 Result += "\t0,\n";
6870
6871 if (ClassProperties.size() > 0) {
6872 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6873 Result += ClassName; Result += "_$_"; Result += CatName;
6874 Result += ",\n";
6875 }
6876 else
6877 Result += "\t0,\n";
6878
6879 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006880
6881 // Add static function to initialize the class pointer in the category structure.
6882 Result += "static void OBJC_CATEGORY_SETUP_$_";
6883 Result += ClassDecl->getNameAsString();
6884 Result += "_$_";
6885 Result += CatName;
6886 Result += "(void ) {\n";
6887 Result += "\t_OBJC_$_CATEGORY_";
6888 Result += ClassDecl->getNameAsString();
6889 Result += "_$_";
6890 Result += CatName;
6891 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6892 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006893}
6894
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006895static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6896 ASTContext *Context, std::string &Result,
6897 ArrayRef<ObjCMethodDecl *> Methods,
6898 StringRef VarName,
6899 StringRef ProtocolName) {
6900 if (Methods.size() == 0)
6901 return;
6902
6903 Result += "\nstatic const char *";
6904 Result += VarName; Result += ProtocolName;
6905 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6906 Result += "{\n";
6907 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6908 ObjCMethodDecl *MD = Methods[i];
6909 std::string MethodTypeString, QuoteMethodTypeString;
6910 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6911 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6912 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6913 if (i == e-1)
6914 Result += "\n};\n";
6915 else {
6916 Result += ",\n";
6917 }
6918 }
6919}
6920
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006921static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6922 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006923 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006924 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006925 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006926 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6927 // this is what happens:
6928 /**
6929 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6930 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6931 Class->getVisibility() == HiddenVisibility)
6932 Visibility shoud be: HiddenVisibility;
6933 else
6934 Visibility shoud be: DefaultVisibility;
6935 */
6936
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006937 Result += "\n";
6938 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6939 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006940 if (Context->getLangOpts().MicrosoftExt)
6941 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6942
6943 if (!Context->getLangOpts().MicrosoftExt ||
6944 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006945 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006946 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006947 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006948 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006949 if (Ivars[i]->isBitField())
6950 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6951 else
6952 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006953 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6954 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006955 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6956 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006957 if (Ivars[i]->isBitField()) {
6958 // skip over rest of the ivar bitfields.
6959 SKIP_BITFIELDS(i , e, Ivars);
6960 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006961 }
6962}
6963
Fariborz Jahanianae932952012-02-10 20:47:10 +00006964static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6965 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006966 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006967 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006968 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006969 if (OriginalIvars.size() > 0) {
6970 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6971 SmallVector<ObjCIvarDecl *, 8> Ivars;
6972 // strip off all but the first ivar bitfield from each group of ivars.
6973 // Such ivars in the ivar list table will be replaced by their grouping struct
6974 // 'ivar'.
6975 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6976 if (OriginalIvars[i]->isBitField()) {
6977 Ivars.push_back(OriginalIvars[i]);
6978 // skip over rest of the ivar bitfields.
6979 SKIP_BITFIELDS(i , e, OriginalIvars);
6980 }
6981 else
6982 Ivars.push_back(OriginalIvars[i]);
6983 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006984
Fariborz Jahanianae932952012-02-10 20:47:10 +00006985 Result += "\nstatic ";
6986 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6987 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006988 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006989 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6990 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6991 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6992 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6993 ObjCIvarDecl *IvarDecl = Ivars[i];
6994 if (i == 0)
6995 Result += "\t{{";
6996 else
6997 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006998 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006999 if (Ivars[i]->isBitField())
7000 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7001 else
7002 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00007003 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00007004
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007005 Result += "\"";
7006 if (Ivars[i]->isBitField())
7007 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7008 else
7009 Result += IvarDecl->getName();
7010 Result += "\", ";
7011
7012 QualType IVQT = IvarDecl->getType();
7013 if (IvarDecl->isBitField())
7014 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7015
Fariborz Jahanianae932952012-02-10 20:47:10 +00007016 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007017 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00007018 IvarDecl);
7019 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7020 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7021
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007022 // FIXME. this alignment represents the host alignment and need be changed to
7023 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007024 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007025 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007026 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007027 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007028 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007029 if (i == e-1)
7030 Result += "}}\n";
7031 else
7032 Result += "},\n";
7033 }
7034 Result += "};\n";
7035 }
7036}
7037
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007038/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007039void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7040 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007041
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007042 // Do not synthesize the protocol more than once.
7043 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7044 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007045 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007046
7047 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7048 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007049 // Must write out all protocol definitions in current qualifier list,
7050 // and in their nested qualifiers before writing out current definition.
7051 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7052 E = PDecl->protocol_end(); I != E; ++I)
7053 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007054
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007055 // Construct method lists.
7056 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7057 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7058 for (ObjCProtocolDecl::instmeth_iterator
7059 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7060 I != E; ++I) {
7061 ObjCMethodDecl *MD = *I;
7062 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7063 OptInstanceMethods.push_back(MD);
7064 } else {
7065 InstanceMethods.push_back(MD);
7066 }
7067 }
7068
7069 for (ObjCProtocolDecl::classmeth_iterator
7070 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7071 I != E; ++I) {
7072 ObjCMethodDecl *MD = *I;
7073 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7074 OptClassMethods.push_back(MD);
7075 } else {
7076 ClassMethods.push_back(MD);
7077 }
7078 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007079 std::vector<ObjCMethodDecl *> AllMethods;
7080 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7081 AllMethods.push_back(InstanceMethods[i]);
7082 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7083 AllMethods.push_back(ClassMethods[i]);
7084 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7085 AllMethods.push_back(OptInstanceMethods[i]);
7086 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7087 AllMethods.push_back(OptClassMethods[i]);
7088
7089 Write__extendedMethodTypes_initializer(*this, Context, Result,
7090 AllMethods,
7091 "_OBJC_PROTOCOL_METHOD_TYPES_",
7092 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007093 // Protocol's super protocol list
7094 std::vector<ObjCProtocolDecl *> SuperProtocols;
7095 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7096 E = PDecl->protocol_end(); I != E; ++I)
7097 SuperProtocols.push_back(*I);
7098
7099 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7100 "_OBJC_PROTOCOL_REFS_",
7101 PDecl->getNameAsString());
7102
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007103 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007104 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007105 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007106
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007107 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007108 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007109 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007110
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007111 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007112 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007113 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007114
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007115 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007116 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007117 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007118
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007119 // Protocol's property metadata.
7120 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7121 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7122 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007123 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007124
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007125 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007126 /* Container */0,
7127 "_OBJC_PROTOCOL_PROPERTIES_",
7128 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007129
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007130 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007131 Result += "\n";
7132 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007133 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007134 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007135 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007136 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7137 Result += "\t0,\n"; // id is; is null
7138 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007139 if (SuperProtocols.size() > 0) {
7140 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7141 Result += PDecl->getNameAsString(); Result += ",\n";
7142 }
7143 else
7144 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007145 if (InstanceMethods.size() > 0) {
7146 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7147 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007148 }
7149 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007150 Result += "\t0,\n";
7151
7152 if (ClassMethods.size() > 0) {
7153 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7154 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007155 }
7156 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007157 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007158
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007159 if (OptInstanceMethods.size() > 0) {
7160 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7161 Result += PDecl->getNameAsString(); Result += ",\n";
7162 }
7163 else
7164 Result += "\t0,\n";
7165
7166 if (OptClassMethods.size() > 0) {
7167 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7168 Result += PDecl->getNameAsString(); Result += ",\n";
7169 }
7170 else
7171 Result += "\t0,\n";
7172
7173 if (ProtocolProperties.size() > 0) {
7174 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7175 Result += PDecl->getNameAsString(); Result += ",\n";
7176 }
7177 else
7178 Result += "\t0,\n";
7179
7180 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7181 Result += "\t0,\n";
7182
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007183 if (AllMethods.size() > 0) {
7184 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7185 Result += PDecl->getNameAsString();
7186 Result += "\n};\n";
7187 }
7188 else
7189 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007190
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007191 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007192 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007193 Result += "struct _protocol_t *";
7194 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7195 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7196 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007197
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007198 // Mark this protocol as having been generated.
7199 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7200 llvm_unreachable("protocol already synthesized");
7201
7202}
7203
7204void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7205 const ObjCList<ObjCProtocolDecl> &Protocols,
7206 StringRef prefix, StringRef ClassName,
7207 std::string &Result) {
7208 if (Protocols.empty()) return;
7209
7210 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007211 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007212
7213 // Output the top lovel protocol meta-data for the class.
7214 /* struct _objc_protocol_list {
7215 struct _objc_protocol_list *next;
7216 int protocol_count;
7217 struct _objc_protocol *class_protocols[];
7218 }
7219 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007220 Result += "\n";
7221 if (LangOpts.MicrosoftExt)
7222 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7223 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007224 Result += "\tstruct _objc_protocol_list *next;\n";
7225 Result += "\tint protocol_count;\n";
7226 Result += "\tstruct _objc_protocol *class_protocols[";
7227 Result += utostr(Protocols.size());
7228 Result += "];\n} _OBJC_";
7229 Result += prefix;
7230 Result += "_PROTOCOLS_";
7231 Result += ClassName;
7232 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7233 "{\n\t0, ";
7234 Result += utostr(Protocols.size());
7235 Result += "\n";
7236
7237 Result += "\t,{&_OBJC_PROTOCOL_";
7238 Result += Protocols[0]->getNameAsString();
7239 Result += " \n";
7240
7241 for (unsigned i = 1; i != Protocols.size(); i++) {
7242 Result += "\t ,&_OBJC_PROTOCOL_";
7243 Result += Protocols[i]->getNameAsString();
7244 Result += "\n";
7245 }
7246 Result += "\t }\n};\n";
7247}
7248
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007249/// hasObjCExceptionAttribute - Return true if this class or any super
7250/// class has the __objc_exception__ attribute.
7251/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7252static bool hasObjCExceptionAttribute(ASTContext &Context,
7253 const ObjCInterfaceDecl *OID) {
7254 if (OID->hasAttr<ObjCExceptionAttr>())
7255 return true;
7256 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7257 return hasObjCExceptionAttribute(Context, Super);
7258 return false;
7259}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007260
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007261void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7262 std::string &Result) {
7263 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7264
7265 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007266 if (CDecl->isImplicitInterfaceDecl())
7267 assert(false &&
7268 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007269
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007270 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007271 SmallVector<ObjCIvarDecl *, 8> IVars;
7272
7273 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7274 IVD; IVD = IVD->getNextIvar()) {
7275 // Ignore unnamed bit-fields.
7276 if (!IVD->getDeclName())
7277 continue;
7278 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007279 }
7280
Fariborz Jahanianae932952012-02-10 20:47:10 +00007281 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007282 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007283 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007284
7285 // Build _objc_method_list for class's instance methods if needed
7286 SmallVector<ObjCMethodDecl *, 32>
7287 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7288
7289 // If any of our property implementations have associated getters or
7290 // setters, produce metadata for them as well.
7291 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7292 PropEnd = IDecl->propimpl_end();
7293 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007294 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007295 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007296 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007297 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007298 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007299 if (!PD)
7300 continue;
7301 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007302 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007303 InstanceMethods.push_back(Getter);
7304 if (PD->isReadOnly())
7305 continue;
7306 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007307 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007308 InstanceMethods.push_back(Setter);
7309 }
7310
7311 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7312 "_OBJC_$_INSTANCE_METHODS_",
7313 IDecl->getNameAsString(), true);
7314
7315 SmallVector<ObjCMethodDecl *, 32>
7316 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7317
7318 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7319 "_OBJC_$_CLASS_METHODS_",
7320 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007321
7322 // Protocols referenced in class declaration?
7323 // Protocol's super protocol list
7324 std::vector<ObjCProtocolDecl *> RefedProtocols;
7325 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7326 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7327 E = Protocols.end();
7328 I != E; ++I) {
7329 RefedProtocols.push_back(*I);
7330 // Must write out all protocol definitions in current qualifier list,
7331 // and in their nested qualifiers before writing out current definition.
7332 RewriteObjCProtocolMetaData(*I, Result);
7333 }
7334
7335 Write_protocol_list_initializer(Context, Result,
7336 RefedProtocols,
7337 "_OBJC_CLASS_PROTOCOLS_$_",
7338 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007339
7340 // Protocol's property metadata.
7341 std::vector<ObjCPropertyDecl *> ClassProperties;
7342 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7343 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007344 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007345
7346 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007347 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007348 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007349 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007350
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007351
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007352 // Data for initializing _class_ro_t metaclass meta-data
7353 uint32_t flags = CLS_META;
7354 std::string InstanceSize;
7355 std::string InstanceStart;
7356
7357
7358 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7359 if (classIsHidden)
7360 flags |= OBJC2_CLS_HIDDEN;
7361
7362 if (!CDecl->getSuperClass())
7363 // class is root
7364 flags |= CLS_ROOT;
7365 InstanceSize = "sizeof(struct _class_t)";
7366 InstanceStart = InstanceSize;
7367 Write__class_ro_t_initializer(Context, Result, flags,
7368 InstanceStart, InstanceSize,
7369 ClassMethods,
7370 0,
7371 0,
7372 0,
7373 "_OBJC_METACLASS_RO_$_",
7374 CDecl->getNameAsString());
7375
7376
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007377 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007378 flags = CLS;
7379 if (classIsHidden)
7380 flags |= OBJC2_CLS_HIDDEN;
7381
7382 if (hasObjCExceptionAttribute(*Context, CDecl))
7383 flags |= CLS_EXCEPTION;
7384
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007385 if (!CDecl->getSuperClass())
7386 // class is root
7387 flags |= CLS_ROOT;
7388
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007389 InstanceSize.clear();
7390 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007391 if (!ObjCSynthesizedStructs.count(CDecl)) {
7392 InstanceSize = "0";
7393 InstanceStart = "0";
7394 }
7395 else {
7396 InstanceSize = "sizeof(struct ";
7397 InstanceSize += CDecl->getNameAsString();
7398 InstanceSize += "_IMPL)";
7399
7400 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7401 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007402 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007403 }
7404 else
7405 InstanceStart = InstanceSize;
7406 }
7407 Write__class_ro_t_initializer(Context, Result, flags,
7408 InstanceStart, InstanceSize,
7409 InstanceMethods,
7410 RefedProtocols,
7411 IVars,
7412 ClassProperties,
7413 "_OBJC_CLASS_RO_$_",
7414 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007415
7416 Write_class_t(Context, Result,
7417 "OBJC_METACLASS_$_",
7418 CDecl, /*metaclass*/true);
7419
7420 Write_class_t(Context, Result,
7421 "OBJC_CLASS_$_",
7422 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007423
7424 if (ImplementationIsNonLazy(IDecl))
7425 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007426
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007427}
7428
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007429void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7430 int ClsDefCount = ClassImplementation.size();
7431 if (!ClsDefCount)
7432 return;
7433 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7434 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7435 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7436 for (int i = 0; i < ClsDefCount; i++) {
7437 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7438 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7439 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7440 Result += CDecl->getName(); Result += ",\n";
7441 }
7442 Result += "};\n";
7443}
7444
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007445void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7446 int ClsDefCount = ClassImplementation.size();
7447 int CatDefCount = CategoryImplementation.size();
7448
7449 // For each implemented class, write out all its meta data.
7450 for (int i = 0; i < ClsDefCount; i++)
7451 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7452
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007453 RewriteClassSetupInitHook(Result);
7454
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007455 // For each implemented category, write out all its meta data.
7456 for (int i = 0; i < CatDefCount; i++)
7457 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7458
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007459 RewriteCategorySetupInitHook(Result);
7460
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007461 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007462 if (LangOpts.MicrosoftExt)
7463 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007464 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7465 Result += llvm::utostr(ClsDefCount); Result += "]";
7466 Result +=
7467 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7468 "regular,no_dead_strip\")))= {\n";
7469 for (int i = 0; i < ClsDefCount; i++) {
7470 Result += "\t&OBJC_CLASS_$_";
7471 Result += ClassImplementation[i]->getNameAsString();
7472 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007473 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007474 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007475
7476 if (!DefinedNonLazyClasses.empty()) {
7477 if (LangOpts.MicrosoftExt)
7478 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7479 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7480 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7481 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7482 Result += ",\n";
7483 }
7484 Result += "};\n";
7485 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007486 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007487
7488 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007489 if (LangOpts.MicrosoftExt)
7490 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007491 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7492 Result += llvm::utostr(CatDefCount); Result += "]";
7493 Result +=
7494 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7495 "regular,no_dead_strip\")))= {\n";
7496 for (int i = 0; i < CatDefCount; i++) {
7497 Result += "\t&_OBJC_$_CATEGORY_";
7498 Result +=
7499 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7500 Result += "_$_";
7501 Result += CategoryImplementation[i]->getNameAsString();
7502 Result += ",\n";
7503 }
7504 Result += "};\n";
7505 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007506
7507 if (!DefinedNonLazyCategories.empty()) {
7508 if (LangOpts.MicrosoftExt)
7509 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7510 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7511 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7512 Result += "\t&_OBJC_$_CATEGORY_";
7513 Result +=
7514 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7515 Result += "_$_";
7516 Result += DefinedNonLazyCategories[i]->getNameAsString();
7517 Result += ",\n";
7518 }
7519 Result += "};\n";
7520 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007521}
7522
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007523void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7524 if (LangOpts.MicrosoftExt)
7525 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7526
7527 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7528 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007529 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007530}
7531
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007532/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7533/// implementation.
7534void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7535 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007536 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007537 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7538 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007539 ObjCCategoryDecl *CDecl
7540 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007541
7542 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007543 FullCategoryName += "_$_";
7544 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007545
7546 // Build _objc_method_list for class's instance methods if needed
7547 SmallVector<ObjCMethodDecl *, 32>
7548 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7549
7550 // If any of our property implementations have associated getters or
7551 // setters, produce metadata for them as well.
7552 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7553 PropEnd = IDecl->propimpl_end();
7554 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007555 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007556 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007557 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007558 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007559 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007560 if (!PD)
7561 continue;
7562 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7563 InstanceMethods.push_back(Getter);
7564 if (PD->isReadOnly())
7565 continue;
7566 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7567 InstanceMethods.push_back(Setter);
7568 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007569
Fariborz Jahanian61186122012-02-17 18:40:41 +00007570 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7571 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7572 FullCategoryName, true);
7573
7574 SmallVector<ObjCMethodDecl *, 32>
7575 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7576
7577 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7578 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7579 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007580
7581 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007582 // Protocol's super protocol list
7583 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007584 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7585 E = CDecl->protocol_end();
7586
7587 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007588 RefedProtocols.push_back(*I);
7589 // Must write out all protocol definitions in current qualifier list,
7590 // and in their nested qualifiers before writing out current definition.
7591 RewriteObjCProtocolMetaData(*I, Result);
7592 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007593
Fariborz Jahanian61186122012-02-17 18:40:41 +00007594 Write_protocol_list_initializer(Context, Result,
7595 RefedProtocols,
7596 "_OBJC_CATEGORY_PROTOCOLS_$_",
7597 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007598
Fariborz Jahanian61186122012-02-17 18:40:41 +00007599 // Protocol's property metadata.
7600 std::vector<ObjCPropertyDecl *> ClassProperties;
7601 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7602 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007603 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007604
Fariborz Jahanian61186122012-02-17 18:40:41 +00007605 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007606 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007607 "_OBJC_$_PROP_LIST_",
7608 FullCategoryName);
7609
7610 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007611 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007612 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007613 InstanceMethods,
7614 ClassMethods,
7615 RefedProtocols,
7616 ClassProperties);
7617
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007618 // Determine if this category is also "non-lazy".
7619 if (ImplementationIsNonLazy(IDecl))
7620 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007621
7622}
7623
7624void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7625 int CatDefCount = CategoryImplementation.size();
7626 if (!CatDefCount)
7627 return;
7628 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7629 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7630 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7631 for (int i = 0; i < CatDefCount; i++) {
7632 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7633 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7634 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7635 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7636 Result += ClassDecl->getName();
7637 Result += "_$_";
7638 Result += CatDecl->getName();
7639 Result += ",\n";
7640 }
7641 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007642}
7643
7644// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7645/// class methods.
7646template<typename MethodIterator>
7647void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7648 MethodIterator MethodEnd,
7649 bool IsInstanceMethod,
7650 StringRef prefix,
7651 StringRef ClassName,
7652 std::string &Result) {
7653 if (MethodBegin == MethodEnd) return;
7654
7655 if (!objc_impl_method) {
7656 /* struct _objc_method {
7657 SEL _cmd;
7658 char *method_types;
7659 void *_imp;
7660 }
7661 */
7662 Result += "\nstruct _objc_method {\n";
7663 Result += "\tSEL _cmd;\n";
7664 Result += "\tchar *method_types;\n";
7665 Result += "\tvoid *_imp;\n";
7666 Result += "};\n";
7667
7668 objc_impl_method = true;
7669 }
7670
7671 // Build _objc_method_list for class's methods if needed
7672
7673 /* struct {
7674 struct _objc_method_list *next_method;
7675 int method_count;
7676 struct _objc_method method_list[];
7677 }
7678 */
7679 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007680 Result += "\n";
7681 if (LangOpts.MicrosoftExt) {
7682 if (IsInstanceMethod)
7683 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7684 else
7685 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7686 }
7687 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007688 Result += "\tstruct _objc_method_list *next_method;\n";
7689 Result += "\tint method_count;\n";
7690 Result += "\tstruct _objc_method method_list[";
7691 Result += utostr(NumMethods);
7692 Result += "];\n} _OBJC_";
7693 Result += prefix;
7694 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7695 Result += "_METHODS_";
7696 Result += ClassName;
7697 Result += " __attribute__ ((used, section (\"__OBJC, __";
7698 Result += IsInstanceMethod ? "inst" : "cls";
7699 Result += "_meth\")))= ";
7700 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7701
7702 Result += "\t,{{(SEL)\"";
7703 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7704 std::string MethodTypeString;
7705 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7706 Result += "\", \"";
7707 Result += MethodTypeString;
7708 Result += "\", (void *)";
7709 Result += MethodInternalNames[*MethodBegin];
7710 Result += "}\n";
7711 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7712 Result += "\t ,{(SEL)\"";
7713 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7714 std::string MethodTypeString;
7715 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7716 Result += "\", \"";
7717 Result += MethodTypeString;
7718 Result += "\", (void *)";
7719 Result += MethodInternalNames[*MethodBegin];
7720 Result += "}\n";
7721 }
7722 Result += "\t }\n};\n";
7723}
7724
7725Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7726 SourceRange OldRange = IV->getSourceRange();
7727 Expr *BaseExpr = IV->getBase();
7728
7729 // Rewrite the base, but without actually doing replaces.
7730 {
7731 DisableReplaceStmtScope S(*this);
7732 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7733 IV->setBase(BaseExpr);
7734 }
7735
7736 ObjCIvarDecl *D = IV->getDecl();
7737
7738 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007739
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007740 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7741 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007742 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007743 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7744 // lookup which class implements the instance variable.
7745 ObjCInterfaceDecl *clsDeclared = 0;
7746 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7747 clsDeclared);
7748 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7749
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007750 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007751 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007752 if (D->isBitField())
7753 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7754 else
7755 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007756
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007757 ReferencedIvars[clsDeclared].insert(D);
7758
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007759 // cast offset to "char *".
7760 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7761 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007762 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007763 BaseExpr);
7764 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7765 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7766 Context->UnsignedLongTy, 0, SC_Extern, SC_None);
John McCallf4b88a42012-03-10 09:33:50 +00007767 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7768 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007769 SourceLocation());
7770 BinaryOperator *addExpr =
7771 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7772 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007773 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007774 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007775 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7776 SourceLocation(),
7777 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007778 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007779 if (D->isBitField())
7780 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007781
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007782 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007783 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007784 RD = RD->getDefinition();
7785 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007786 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007787 ObjCContainerDecl *CDecl =
7788 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7789 // ivar in class extensions requires special treatment.
7790 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7791 CDecl = CatDecl->getClassInterface();
7792 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007793 RecName += "_IMPL";
7794 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7795 SourceLocation(), SourceLocation(),
7796 &Context->Idents.get(RecName.c_str()));
7797 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7798 unsigned UnsignedIntSize =
7799 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7800 Expr *Zero = IntegerLiteral::Create(*Context,
7801 llvm::APInt(UnsignedIntSize, 0),
7802 Context->UnsignedIntTy, SourceLocation());
7803 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7804 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7805 Zero);
7806 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7807 SourceLocation(),
7808 &Context->Idents.get(D->getNameAsString()),
7809 IvarT, 0,
7810 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007811 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007812 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7813 FD->getType(), VK_LValue,
7814 OK_Ordinary);
7815 IvarT = Context->getDecltypeType(ME, ME->getType());
7816 }
7817 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007818 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007819 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007820
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007821 castExpr = NoTypeInfoCStyleCastExpr(Context,
7822 castT,
7823 CK_BitCast,
7824 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007825
7826
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007827 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007828 VK_LValue, OK_Ordinary,
7829 SourceLocation());
7830 PE = new (Context) ParenExpr(OldRange.getBegin(),
7831 OldRange.getEnd(),
7832 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007833
7834 if (D->isBitField()) {
7835 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7836 SourceLocation(),
7837 &Context->Idents.get(D->getNameAsString()),
7838 D->getType(), 0,
7839 /*BitWidth=*/D->getBitWidth(),
7840 /*Mutable=*/true,
7841 ICIS_NoInit);
7842 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7843 FD->getType(), VK_LValue,
7844 OK_Ordinary);
7845 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007846
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007847 }
7848 else
7849 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007850 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007851
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007852 ReplaceStmtWithRange(IV, Replacement, OldRange);
7853 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007854}