1 //===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Hacks and fun related to the code rewriter.
12 //===----------------------------------------------------------------------===//
14 #include "clang/Rewrite/Frontend/ASTConsumers.h"
15 #include "clang/AST/AST.h"
16 #include "clang/AST/ASTConsumer.h"
17 #include "clang/AST/Attr.h"
18 #include "clang/AST/ParentMap.h"
19 #include "clang/Basic/CharInfo.h"
20 #include "clang/Basic/Diagnostic.h"
21 #include "clang/Basic/IdentifierTable.h"
22 #include "clang/Basic/SourceManager.h"
23 #include "clang/Basic/TargetInfo.h"
24 #include "clang/Lex/Lexer.h"
25 #include "clang/Rewrite/Core/Rewriter.h"
26 #include "llvm/ADT/DenseSet.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/StringExtras.h"
29 #include "llvm/Support/MemoryBuffer.h"
30 #include "llvm/Support/raw_ostream.h"
33 #ifdef CLANG_ENABLE_OBJC_REWRITER
35 using namespace clang;
39 class RewriteModernObjC : public ASTConsumer {
43 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
45 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
46 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
48 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
50 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
52 BLOCK_BYREF_CURRENT_MAX = 256
56 BLOCK_NEEDS_FREE = (1 << 24),
57 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
58 BLOCK_HAS_CXX_OBJ = (1 << 26),
59 BLOCK_IS_GC = (1 << 27),
60 BLOCK_IS_GLOBAL = (1 << 28),
61 BLOCK_HAS_DESCRIPTOR = (1 << 29)
65 DiagnosticsEngine &Diags;
66 const LangOptions &LangOpts;
69 TranslationUnitDecl *TUDecl;
71 const char *MainFileStart, *MainFileEnd;
73 ParentMap *PropParentMap; // created lazily.
74 std::string InFileName;
78 TypeDecl *ProtocolTypeDecl;
79 VarDecl *GlobalVarDecl;
80 Expr *GlobalConstructionExp;
81 unsigned RewriteFailedDiag;
82 unsigned GlobalBlockRewriteFailedDiag;
83 // ObjC string constant support.
84 unsigned NumObjCStringLiterals;
85 VarDecl *ConstantStringClassReference;
86 RecordDecl *NSStringRecord;
88 // ObjC foreach break/continue generation support.
91 unsigned TryFinallyContainsReturnDiag;
93 ObjCMethodDecl *CurMethodDef;
94 RecordDecl *SuperStructDecl;
95 RecordDecl *ConstantStringDecl;
97 FunctionDecl *MsgSendFunctionDecl;
98 FunctionDecl *MsgSendSuperFunctionDecl;
99 FunctionDecl *MsgSendStretFunctionDecl;
100 FunctionDecl *MsgSendSuperStretFunctionDecl;
101 FunctionDecl *MsgSendFpretFunctionDecl;
102 FunctionDecl *GetClassFunctionDecl;
103 FunctionDecl *GetMetaClassFunctionDecl;
104 FunctionDecl *GetSuperClassFunctionDecl;
105 FunctionDecl *SelGetUidFunctionDecl;
106 FunctionDecl *CFStringFunctionDecl;
107 FunctionDecl *SuperConstructorFunctionDecl;
108 FunctionDecl *CurFunctionDef;
110 /* Misc. containers needed for meta-data rewrite. */
111 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
112 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
114 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
115 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
116 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
117 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
118 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
119 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
121 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
122 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
124 SmallVector<Stmt *, 32> Stmts;
125 SmallVector<int, 8> ObjCBcLabelNo;
126 // Remember all the @protocol(<expr>) expressions.
127 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
129 llvm::DenseSet<uint64_t> CopyDestroyCache;
131 // Block expressions.
132 SmallVector<BlockExpr *, 32> Blocks;
133 SmallVector<int, 32> InnerDeclRefsCount;
134 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
136 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
139 // Block related declarations.
140 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
142 SmallVector<ValueDecl *, 8> BlockByRefDecls;
143 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
144 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
145 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
146 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
148 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
149 llvm::DenseMap<ObjCInterfaceDecl *,
150 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
152 // ivar bitfield grouping containers
153 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
154 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
155 // This container maps an <class, group number for ivar> tuple to the type
156 // of the struct where the bitfield belongs.
157 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
158 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
160 // This maps an original source AST to it's rewritten form. This allows
161 // us to avoid rewriting the same node twice (which is very uncommon).
162 // This is needed to support some of the exotic property rewriting.
163 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
165 // Needed for header files being rewritten
167 bool SilenceRewriteMacroWarning;
168 bool GenerateLineInfo;
169 bool objc_impl_method;
171 bool DisableReplaceStmt;
172 class DisableReplaceStmtScope {
173 RewriteModernObjC &R;
177 DisableReplaceStmtScope(RewriteModernObjC &R)
178 : R(R), SavedValue(R.DisableReplaceStmt) {
179 R.DisableReplaceStmt = true;
181 ~DisableReplaceStmtScope() {
182 R.DisableReplaceStmt = SavedValue;
185 void InitializeCommon(ASTContext &context);
188 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
189 // Top Level Driver code.
190 bool HandleTopLevelDecl(DeclGroupRef D) override {
191 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
192 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
193 if (!Class->isThisDeclarationADefinition()) {
194 RewriteForwardClassDecl(D);
197 // Keep track of all interface declarations seen.
198 ObjCInterfacesSeen.push_back(Class);
203 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
204 if (!Proto->isThisDeclarationADefinition()) {
205 RewriteForwardProtocolDecl(D);
210 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
211 // Under modern abi, we cannot translate body of the function
212 // yet until all class extensions and its implementation is seen.
213 // This is because they may introduce new bitfields which must go
214 // into their grouping struct.
215 if (FDecl->isThisDeclarationADefinition() &&
216 // Not c functions defined inside an objc container.
217 !FDecl->isTopLevelDeclInObjCContainer()) {
218 FunctionDefinitionsSeen.push_back(FDecl);
222 HandleTopLevelSingleDecl(*I);
227 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
228 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
229 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
230 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
231 RewriteBlockPointerDecl(TD);
232 else if (TD->getUnderlyingType()->isFunctionPointerType())
233 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
235 RewriteObjCQualifiedInterfaceTypes(TD);
241 void HandleTopLevelSingleDecl(Decl *D);
242 void HandleDeclInMainFile(Decl *D);
243 RewriteModernObjC(std::string inFile, raw_ostream *OS,
244 DiagnosticsEngine &D, const LangOptions &LOpts,
245 bool silenceMacroWarn, bool LineInfo);
247 ~RewriteModernObjC() override {}
249 void HandleTranslationUnit(ASTContext &C) override;
251 void ReplaceStmt(Stmt *Old, Stmt *New) {
252 ReplaceStmtWithRange(Old, New, Old->getSourceRange());
255 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
256 assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
258 Stmt *ReplacingStmt = ReplacedNodes[Old];
260 return; // We can't rewrite the same node twice.
262 if (DisableReplaceStmt)
265 // Measure the old text.
266 int Size = Rewrite.getRangeSize(SrcRange);
268 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
269 << Old->getSourceRange();
274 llvm::raw_string_ostream S(SStr);
275 New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
276 const std::string &Str = S.str();
278 // If replacement succeeded or warning disabled return with no warning.
279 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
280 ReplacedNodes[Old] = New;
283 if (SilenceRewriteMacroWarning)
285 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
286 << Old->getSourceRange();
289 void InsertText(SourceLocation Loc, StringRef Str,
290 bool InsertAfter = true) {
291 // If insertion succeeded or warning disabled return with no warning.
292 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
293 SilenceRewriteMacroWarning)
296 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
299 void ReplaceText(SourceLocation Start, unsigned OrigLength,
301 // If removal succeeded or warning disabled return with no warning.
302 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
303 SilenceRewriteMacroWarning)
306 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
309 // Syntactic Rewriting.
310 void RewriteRecordBody(RecordDecl *RD);
311 void RewriteInclude();
312 void RewriteLineDirective(const Decl *D);
313 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
314 std::string &LineString);
315 void RewriteForwardClassDecl(DeclGroupRef D);
316 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
317 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
318 const std::string &typedefString);
319 void RewriteImplementations();
320 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
321 ObjCImplementationDecl *IMD,
322 ObjCCategoryImplDecl *CID);
323 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
324 void RewriteImplementationDecl(Decl *Dcl);
325 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
326 ObjCMethodDecl *MDecl, std::string &ResultStr);
327 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
328 const FunctionType *&FPRetType);
329 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
330 ValueDecl *VD, bool def=false);
331 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
332 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
333 void RewriteForwardProtocolDecl(DeclGroupRef D);
334 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
335 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
336 void RewriteProperty(ObjCPropertyDecl *prop);
337 void RewriteFunctionDecl(FunctionDecl *FD);
338 void RewriteBlockPointerType(std::string& Str, QualType Type);
339 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
340 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
341 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
342 void RewriteTypeOfDecl(VarDecl *VD);
343 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
345 std::string getIvarAccessString(ObjCIvarDecl *D);
347 // Expression Rewriting.
348 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
349 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
350 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
351 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
352 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
353 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
354 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
355 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
356 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
357 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
358 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
359 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
360 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
361 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
362 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
363 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
364 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
365 SourceLocation OrigEnd);
366 Stmt *RewriteBreakStmt(BreakStmt *S);
367 Stmt *RewriteContinueStmt(ContinueStmt *S);
368 void RewriteCastExpr(CStyleCastExpr *CE);
369 void RewriteImplicitCastObjCExpr(CastExpr *IE);
370 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
372 // Computes ivar bitfield group no.
373 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
374 // Names field decl. for ivar bitfield group.
375 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
376 // Names struct type for ivar bitfield group.
377 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
378 // Names symbol for ivar bitfield group field offset.
379 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
380 // Given an ivar bitfield, it builds (or finds) its group record type.
381 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
382 QualType SynthesizeBitfieldGroupStructType(
384 SmallVectorImpl<ObjCIvarDecl *> &IVars);
387 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
389 // Block specific rewrite rules.
390 void RewriteBlockPointerDecl(NamedDecl *VD);
391 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
392 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
393 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
394 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
396 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
397 std::string &Result);
399 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
400 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
401 bool &IsNamedDefinition);
402 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
403 std::string &Result);
405 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
407 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
408 std::string &Result);
410 void Initialize(ASTContext &context) override;
412 // Misc. AST transformation routines. Sometimes they end up calling
413 // rewriting routines on the new ASTs.
414 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
415 ArrayRef<Expr *> Args,
416 SourceLocation StartLoc=SourceLocation(),
417 SourceLocation EndLoc=SourceLocation());
419 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
421 SmallVectorImpl<QualType> &ArgTypes,
422 SmallVectorImpl<Expr*> &MsgExprs,
423 ObjCMethodDecl *Method);
425 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
426 SourceLocation StartLoc=SourceLocation(),
427 SourceLocation EndLoc=SourceLocation());
429 void SynthCountByEnumWithState(std::string &buf);
430 void SynthMsgSendFunctionDecl();
431 void SynthMsgSendSuperFunctionDecl();
432 void SynthMsgSendStretFunctionDecl();
433 void SynthMsgSendFpretFunctionDecl();
434 void SynthMsgSendSuperStretFunctionDecl();
435 void SynthGetClassFunctionDecl();
436 void SynthGetMetaClassFunctionDecl();
437 void SynthGetSuperClassFunctionDecl();
438 void SynthSelGetUidFunctionDecl();
439 void SynthSuperConstructorFunctionDecl();
441 // Rewriting metadata
442 template<typename MethodIterator>
443 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
444 MethodIterator MethodEnd,
445 bool IsInstanceMethod,
448 std::string &Result);
449 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
450 std::string &Result);
451 void RewriteObjCProtocolListMetaData(
452 const ObjCList<ObjCProtocolDecl> &Prots,
453 StringRef prefix, StringRef ClassName, std::string &Result);
454 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
455 std::string &Result);
456 void RewriteClassSetupInitHook(std::string &Result);
458 void RewriteMetaDataIntoBuffer(std::string &Result);
459 void WriteImageInfo(std::string &Result);
460 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
461 std::string &Result);
462 void RewriteCategorySetupInitHook(std::string &Result);
465 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
466 std::string &Result);
467 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
470 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
471 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
472 StringRef funcName, std::string Tag);
473 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
474 StringRef funcName, std::string Tag);
475 std::string SynthesizeBlockImpl(BlockExpr *CE,
476 std::string Tag, std::string Desc);
477 std::string SynthesizeBlockDescriptor(std::string DescTag,
479 int i, StringRef funcName,
481 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
482 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
484 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
485 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
486 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
488 // Misc. helper routines.
489 QualType getProtocolType();
490 void WarnAboutReturnGotoStmts(Stmt *S);
491 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
492 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
493 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
495 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
496 void CollectBlockDeclRefInfo(BlockExpr *Exp);
497 void GetBlockDeclRefExprs(Stmt *S);
498 void GetInnerBlockDeclRefExprs(Stmt *S,
499 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
500 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
502 // We avoid calling Type::isBlockPointerType(), since it operates on the
503 // canonical type. We only care if the top-level type is a closure pointer.
504 bool isTopLevelBlockPointerType(QualType T) {
505 return isa<BlockPointerType>(T);
508 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
509 /// to a function pointer type and upon success, returns true; false
511 bool convertBlockPointerToFunctionPointer(QualType &T) {
512 if (isTopLevelBlockPointerType(T)) {
513 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
514 T = Context->getPointerType(BPT->getPointeeType());
520 bool convertObjCTypeToCStyleType(QualType &T);
522 bool needToScanForQualifiers(QualType T);
523 QualType getSuperStructType();
524 QualType getConstantStringStructType();
525 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
526 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
528 void convertToUnqualifiedObjCType(QualType &T) {
529 if (T->isObjCQualifiedIdType()) {
530 bool isConst = T.isConstQualified();
531 T = isConst ? Context->getObjCIdType().withConst()
532 : Context->getObjCIdType();
534 else if (T->isObjCQualifiedClassType())
535 T = Context->getObjCClassType();
536 else if (T->isObjCObjectPointerType() &&
537 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
538 if (const ObjCObjectPointerType * OBJPT =
539 T->getAsObjCInterfacePointerType()) {
540 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
541 T = QualType(IFaceT, 0);
542 T = Context->getPointerType(T);
547 // FIXME: This predicate seems like it would be useful to add to ASTContext.
548 bool isObjCType(QualType T) {
549 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
552 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
554 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
555 OCT == Context->getCanonicalType(Context->getObjCClassType()))
558 if (const PointerType *PT = OCT->getAs<PointerType>()) {
559 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
560 PT->getPointeeType()->isObjCQualifiedIdType())
565 bool PointerTypeTakesAnyBlockArguments(QualType QT);
566 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
567 void GetExtentOfArgList(const char *Name, const char *&LParen,
568 const char *&RParen);
570 void QuoteDoublequotes(std::string &From, std::string &To) {
571 for (unsigned i = 0; i < From.length(); i++) {
579 QualType getSimpleFunctionType(QualType result,
580 ArrayRef<QualType> args,
581 bool variadic = false) {
582 if (result == Context->getObjCInstanceType())
583 result = Context->getObjCIdType();
584 FunctionProtoType::ExtProtoInfo fpi;
585 fpi.Variadic = variadic;
586 return Context->getFunctionType(result, args, fpi);
589 // Helper function: create a CStyleCastExpr with trivial type source info.
590 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
591 CastKind Kind, Expr *E) {
592 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
593 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
594 TInfo, SourceLocation(), SourceLocation());
597 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
598 IdentifierInfo* II = &Context->Idents.get("load");
599 Selector LoadSel = Context->Selectors.getSelector(0, &II);
600 return OD->getClassMethod(LoadSel) != nullptr;
603 StringLiteral *getStringLiteral(StringRef Str) {
604 QualType StrType = Context->getConstantArrayType(
605 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
607 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
608 /*Pascal=*/false, StrType, SourceLocation());
614 void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
616 if (const FunctionProtoType *fproto
617 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
618 for (const auto &I : fproto->param_types())
619 if (isTopLevelBlockPointerType(I)) {
620 // All the args are checked/rewritten. Don't call twice!
621 RewriteBlockPointerDecl(D);
627 void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
628 const PointerType *PT = funcType->getAs<PointerType>();
629 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
630 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
633 static bool IsHeaderFile(const std::string &Filename) {
634 std::string::size_type DotPos = Filename.rfind('.');
636 if (DotPos == std::string::npos) {
641 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
643 // C++ header: .hh or .H;
644 return Ext == "h" || Ext == "hh" || Ext == "H";
647 RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
648 DiagnosticsEngine &D, const LangOptions &LOpts,
649 bool silenceMacroWarn,
651 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
652 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
653 IsHeader = IsHeaderFile(inFile);
654 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
655 "rewriting sub-expression within a macro (may not be correct)");
656 // FIXME. This should be an error. But if block is not called, it is OK. And it
657 // may break including some headers.
658 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
659 "rewriting block literal declared in global scope is not implemented");
661 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
662 DiagnosticsEngine::Warning,
663 "rewriter doesn't support user-specified control flow semantics "
664 "for @try/@finally (code may not execute properly)");
667 std::unique_ptr<ASTConsumer> clang::CreateModernObjCRewriter(
668 const std::string &InFile, raw_ostream *OS, DiagnosticsEngine &Diags,
669 const LangOptions &LOpts, bool SilenceRewriteMacroWarning, bool LineInfo) {
670 return llvm::make_unique<RewriteModernObjC>(
671 InFile, OS, Diags, LOpts, SilenceRewriteMacroWarning, LineInfo);
674 void RewriteModernObjC::InitializeCommon(ASTContext &context) {
676 SM = &Context->getSourceManager();
677 TUDecl = Context->getTranslationUnitDecl();
678 MsgSendFunctionDecl = nullptr;
679 MsgSendSuperFunctionDecl = nullptr;
680 MsgSendStretFunctionDecl = nullptr;
681 MsgSendSuperStretFunctionDecl = nullptr;
682 MsgSendFpretFunctionDecl = nullptr;
683 GetClassFunctionDecl = nullptr;
684 GetMetaClassFunctionDecl = nullptr;
685 GetSuperClassFunctionDecl = nullptr;
686 SelGetUidFunctionDecl = nullptr;
687 CFStringFunctionDecl = nullptr;
688 ConstantStringClassReference = nullptr;
689 NSStringRecord = nullptr;
690 CurMethodDef = nullptr;
691 CurFunctionDef = nullptr;
692 GlobalVarDecl = nullptr;
693 GlobalConstructionExp = nullptr;
694 SuperStructDecl = nullptr;
695 ProtocolTypeDecl = nullptr;
696 ConstantStringDecl = nullptr;
698 SuperConstructorFunctionDecl = nullptr;
699 NumObjCStringLiterals = 0;
700 PropParentMap = nullptr;
701 CurrentBody = nullptr;
702 DisableReplaceStmt = false;
703 objc_impl_method = false;
705 // Get the ID and start/end of the main file.
706 MainFileID = SM->getMainFileID();
707 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
708 MainFileStart = MainBuf->getBufferStart();
709 MainFileEnd = MainBuf->getBufferEnd();
711 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
714 //===----------------------------------------------------------------------===//
715 // Top Level Driver Code
716 //===----------------------------------------------------------------------===//
718 void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
719 if (Diags.hasErrorOccurred())
722 // Two cases: either the decl could be in the main file, or it could be in a
723 // #included file. If the former, rewrite it now. If the later, check to see
724 // if we rewrote the #include/#import.
725 SourceLocation Loc = D->getLocation();
726 Loc = SM->getExpansionLoc(Loc);
728 // If this is for a builtin, ignore it.
729 if (Loc.isInvalid()) return;
731 // Look for built-in declarations that we need to refer during the rewrite.
732 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
733 RewriteFunctionDecl(FD);
734 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
735 // declared in <Foundation/NSString.h>
736 if (FVD->getName() == "_NSConstantStringClassReference") {
737 ConstantStringClassReference = FVD;
740 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
741 RewriteCategoryDecl(CD);
742 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
743 if (PD->isThisDeclarationADefinition())
744 RewriteProtocolDecl(PD);
745 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
746 // FIXME. This will not work in all situations and leaving it out
748 // RewriteLinkageSpec(LSD);
750 // Recurse into linkage specifications
751 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
752 DIEnd = LSD->decls_end();
754 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
755 if (!IFace->isThisDeclarationADefinition()) {
756 SmallVector<Decl *, 8> DG;
757 SourceLocation StartLoc = IFace->getLocStart();
759 if (isa<ObjCInterfaceDecl>(*DI) &&
760 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
761 StartLoc == (*DI)->getLocStart())
767 } while (DI != DIEnd);
768 RewriteForwardClassDecl(DG);
772 // Keep track of all interface declarations seen.
773 ObjCInterfacesSeen.push_back(IFace);
779 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
780 if (!Proto->isThisDeclarationADefinition()) {
781 SmallVector<Decl *, 8> DG;
782 SourceLocation StartLoc = Proto->getLocStart();
784 if (isa<ObjCProtocolDecl>(*DI) &&
785 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
786 StartLoc == (*DI)->getLocStart())
792 } while (DI != DIEnd);
793 RewriteForwardProtocolDecl(DG);
798 HandleTopLevelSingleDecl(*DI);
802 // If we have a decl in the main file, see if we should rewrite it.
803 if (SM->isWrittenInMainFile(Loc))
804 return HandleDeclInMainFile(D);
807 //===----------------------------------------------------------------------===//
808 // Syntactic (non-AST) Rewriting Code
809 //===----------------------------------------------------------------------===//
811 void RewriteModernObjC::RewriteInclude() {
812 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
813 StringRef MainBuf = SM->getBufferData(MainFileID);
814 const char *MainBufStart = MainBuf.begin();
815 const char *MainBufEnd = MainBuf.end();
816 size_t ImportLen = strlen("import");
818 // Loop over the whole file, looking for includes.
819 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
820 if (*BufPtr == '#') {
821 if (++BufPtr == MainBufEnd)
823 while (*BufPtr == ' ' || *BufPtr == '\t')
824 if (++BufPtr == MainBufEnd)
826 if (!strncmp(BufPtr, "import", ImportLen)) {
827 // replace import with include
828 SourceLocation ImportLoc =
829 LocStart.getLocWithOffset(BufPtr-MainBufStart);
830 ReplaceText(ImportLoc, ImportLen, "include");
837 static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
838 ObjCIvarDecl *IvarDecl, std::string &Result) {
839 Result += "OBJC_IVAR_$_";
840 Result += IDecl->getName();
842 Result += IvarDecl->getName();
846 RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
847 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
849 // Build name of symbol holding ivar offset.
850 std::string IvarOffsetName;
852 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
854 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
857 std::string S = "(*(";
858 QualType IvarT = D->getType();
860 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
862 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
863 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
864 RD = RD->getDefinition();
865 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
866 // decltype(((Foo_IMPL*)0)->bar) *
867 ObjCContainerDecl *CDecl =
868 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
869 // ivar in class extensions requires special treatment.
870 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
871 CDecl = CatDecl->getClassInterface();
872 std::string RecName = CDecl->getName();
874 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
875 SourceLocation(), SourceLocation(),
876 &Context->Idents.get(RecName.c_str()));
877 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
878 unsigned UnsignedIntSize =
879 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
880 Expr *Zero = IntegerLiteral::Create(*Context,
881 llvm::APInt(UnsignedIntSize, 0),
882 Context->UnsignedIntTy, SourceLocation());
883 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
884 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
886 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
888 &Context->Idents.get(D->getNameAsString()),
890 /*BitWidth=*/nullptr, /*Mutable=*/true,
892 MemberExpr *ME = new (Context)
893 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
894 FD->getType(), VK_LValue, OK_Ordinary);
895 IvarT = Context->getDecltypeType(ME, ME->getType());
898 convertObjCTypeToCStyleType(IvarT);
899 QualType castT = Context->getPointerType(IvarT);
900 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
904 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
905 S += "((char *)self + ";
908 if (D->isBitField()) {
910 S += D->getNameAsString();
912 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
916 /// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
917 /// been found in the class implementation. In this case, it must be synthesized.
918 static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
919 ObjCPropertyDecl *PD,
921 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
922 : !IMP->getInstanceMethod(PD->getSetterName());
926 void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
927 ObjCImplementationDecl *IMD,
928 ObjCCategoryImplDecl *CID) {
929 static bool objcGetPropertyDefined = false;
930 static bool objcSetPropertyDefined = false;
931 SourceLocation startGetterSetterLoc;
933 if (PID->getLocStart().isValid()) {
934 SourceLocation startLoc = PID->getLocStart();
935 InsertText(startLoc, "// ");
936 const char *startBuf = SM->getCharacterData(startLoc);
937 assert((*startBuf == '@') && "bogus @synthesize location");
938 const char *semiBuf = strchr(startBuf, ';');
939 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
940 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
943 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
945 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
946 return; // FIXME: is this correct?
948 // Generate the 'getter' function.
949 ObjCPropertyDecl *PD = PID->getPropertyDecl();
950 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
951 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
953 unsigned Attributes = PD->getPropertyAttributes();
954 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
955 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
956 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
957 ObjCPropertyDecl::OBJC_PR_copy));
959 if (GenGetProperty && !objcGetPropertyDefined) {
960 objcGetPropertyDefined = true;
961 // FIXME. Is this attribute correct in all cases?
962 Getr = "\nextern \"C\" __declspec(dllimport) "
963 "id objc_getProperty(id, SEL, long, bool);\n";
965 RewriteObjCMethodDecl(OID->getContainingInterface(),
966 PD->getGetterMethodDecl(), Getr);
968 // Synthesize an explicit cast to gain access to the ivar.
969 // See objc-act.c:objc_synthesize_new_getter() for details.
970 if (GenGetProperty) {
971 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
973 const FunctionType *FPRetType = nullptr;
974 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
978 Getr += ")"; // close the precedence "scope" for "*".
980 // Now, emit the argument types (if any).
981 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
983 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
985 std::string ParamStr =
986 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
989 if (FT->isVariadic()) {
990 if (FT->getNumParams())
999 Getr += "return (_TYPE)";
1000 Getr += "objc_getProperty(self, _cmd, ";
1001 RewriteIvarOffsetComputation(OID, Getr);
1005 Getr += "return " + getIvarAccessString(OID);
1007 InsertText(startGetterSetterLoc, Getr);
1010 if (PD->isReadOnly() ||
1011 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
1014 // Generate the 'setter' function.
1016 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
1017 ObjCPropertyDecl::OBJC_PR_copy);
1018 if (GenSetProperty && !objcSetPropertyDefined) {
1019 objcSetPropertyDefined = true;
1020 // FIXME. Is this attribute correct in all cases?
1021 Setr = "\nextern \"C\" __declspec(dllimport) "
1022 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1025 RewriteObjCMethodDecl(OID->getContainingInterface(),
1026 PD->getSetterMethodDecl(), Setr);
1028 // Synthesize an explicit cast to initialize the ivar.
1029 // See objc-act.c:objc_synthesize_new_setter() for details.
1030 if (GenSetProperty) {
1031 Setr += "objc_setProperty (self, _cmd, ";
1032 RewriteIvarOffsetComputation(OID, Setr);
1034 Setr += PD->getName();
1036 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
1040 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
1046 Setr += getIvarAccessString(OID) + " = ";
1047 Setr += PD->getName();
1050 InsertText(startGetterSetterLoc, Setr);
1053 static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1054 std::string &typedefString) {
1055 typedefString += "\n#ifndef _REWRITER_typedef_";
1056 typedefString += ForwardDecl->getNameAsString();
1057 typedefString += "\n";
1058 typedefString += "#define _REWRITER_typedef_";
1059 typedefString += ForwardDecl->getNameAsString();
1060 typedefString += "\n";
1061 typedefString += "typedef struct objc_object ";
1062 typedefString += ForwardDecl->getNameAsString();
1063 // typedef struct { } _objc_exc_Classname;
1064 typedefString += ";\ntypedef struct {} _objc_exc_";
1065 typedefString += ForwardDecl->getNameAsString();
1066 typedefString += ";\n#endif\n";
1069 void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1070 const std::string &typedefString) {
1071 SourceLocation startLoc = ClassDecl->getLocStart();
1072 const char *startBuf = SM->getCharacterData(startLoc);
1073 const char *semiPtr = strchr(startBuf, ';');
1074 // Replace the @class with typedefs corresponding to the classes.
1075 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1078 void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1079 std::string typedefString;
1080 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1081 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1082 if (I == D.begin()) {
1083 // Translate to typedef's that forward reference structs with the same name
1084 // as the class. As a convenience, we include the original declaration
1086 typedefString += "// @class ";
1087 typedefString += ForwardDecl->getNameAsString();
1088 typedefString += ";";
1090 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1093 HandleTopLevelSingleDecl(*I);
1095 DeclGroupRef::iterator I = D.begin();
1096 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1099 void RewriteModernObjC::RewriteForwardClassDecl(
1100 const SmallVectorImpl<Decl *> &D) {
1101 std::string typedefString;
1102 for (unsigned i = 0; i < D.size(); i++) {
1103 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1105 typedefString += "// @class ";
1106 typedefString += ForwardDecl->getNameAsString();
1107 typedefString += ";";
1109 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1111 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1114 void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1115 // When method is a synthesized one, such as a getter/setter there is
1116 // nothing to rewrite.
1117 if (Method->isImplicit())
1119 SourceLocation LocStart = Method->getLocStart();
1120 SourceLocation LocEnd = Method->getLocEnd();
1122 if (SM->getExpansionLineNumber(LocEnd) >
1123 SM->getExpansionLineNumber(LocStart)) {
1124 InsertText(LocStart, "#if 0\n");
1125 ReplaceText(LocEnd, 1, ";\n#endif\n");
1127 InsertText(LocStart, "// ");
1131 void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1132 SourceLocation Loc = prop->getAtLoc();
1134 ReplaceText(Loc, 0, "// ");
1135 // FIXME: handle properties that are declared across multiple lines.
1138 void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1139 SourceLocation LocStart = CatDecl->getLocStart();
1141 // FIXME: handle category headers that are declared across multiple lines.
1142 if (CatDecl->getIvarRBraceLoc().isValid()) {
1143 ReplaceText(LocStart, 1, "/** ");
1144 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1147 ReplaceText(LocStart, 0, "// ");
1150 for (auto *I : CatDecl->properties())
1153 for (auto *I : CatDecl->instance_methods())
1154 RewriteMethodDeclaration(I);
1155 for (auto *I : CatDecl->class_methods())
1156 RewriteMethodDeclaration(I);
1158 // Lastly, comment out the @end.
1159 ReplaceText(CatDecl->getAtEndRange().getBegin(),
1160 strlen("@end"), "/* @end */\n");
1163 void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1164 SourceLocation LocStart = PDecl->getLocStart();
1165 assert(PDecl->isThisDeclarationADefinition());
1167 // FIXME: handle protocol headers that are declared across multiple lines.
1168 ReplaceText(LocStart, 0, "// ");
1170 for (auto *I : PDecl->instance_methods())
1171 RewriteMethodDeclaration(I);
1172 for (auto *I : PDecl->class_methods())
1173 RewriteMethodDeclaration(I);
1174 for (auto *I : PDecl->properties())
1177 // Lastly, comment out the @end.
1178 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1179 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
1181 // Must comment out @optional/@required
1182 const char *startBuf = SM->getCharacterData(LocStart);
1183 const char *endBuf = SM->getCharacterData(LocEnd);
1184 for (const char *p = startBuf; p < endBuf; p++) {
1185 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1186 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1187 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1190 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1191 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1192 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1198 void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1199 SourceLocation LocStart = (*D.begin())->getLocStart();
1200 if (LocStart.isInvalid())
1201 llvm_unreachable("Invalid SourceLocation");
1202 // FIXME: handle forward protocol that are declared across multiple lines.
1203 ReplaceText(LocStart, 0, "// ");
1207 RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1208 SourceLocation LocStart = DG[0]->getLocStart();
1209 if (LocStart.isInvalid())
1210 llvm_unreachable("Invalid SourceLocation");
1211 // FIXME: handle forward protocol that are declared across multiple lines.
1212 ReplaceText(LocStart, 0, "// ");
1216 RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1217 SourceLocation LocStart = LSD->getExternLoc();
1218 if (LocStart.isInvalid())
1219 llvm_unreachable("Invalid extern SourceLocation");
1221 ReplaceText(LocStart, 0, "// ");
1222 if (!LSD->hasBraces())
1224 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1225 SourceLocation LocRBrace = LSD->getRBraceLoc();
1226 if (LocRBrace.isInvalid())
1227 llvm_unreachable("Invalid rbrace SourceLocation");
1228 ReplaceText(LocRBrace, 0, "// ");
1231 void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1232 const FunctionType *&FPRetType) {
1233 if (T->isObjCQualifiedIdType())
1235 else if (T->isFunctionPointerType() ||
1236 T->isBlockPointerType()) {
1237 // needs special handling, since pointer-to-functions have special
1238 // syntax (where a decaration models use).
1239 QualType retType = T;
1241 if (const PointerType* PT = retType->getAs<PointerType>())
1242 PointeeTy = PT->getPointeeType();
1243 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1244 PointeeTy = BPT->getPointeeType();
1245 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1247 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1251 ResultStr += T.getAsString(Context->getPrintingPolicy());
1254 void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1255 ObjCMethodDecl *OMD,
1256 std::string &ResultStr) {
1257 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1258 const FunctionType *FPRetType = nullptr;
1259 ResultStr += "\nstatic ";
1260 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1263 // Unique method name
1264 std::string NameStr;
1266 if (OMD->isInstanceMethod())
1271 NameStr += IDecl->getNameAsString();
1274 if (ObjCCategoryImplDecl *CID =
1275 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1276 NameStr += CID->getNameAsString();
1279 // Append selector names, replacing ':' with '_'
1281 std::string selString = OMD->getSelector().getAsString();
1282 int len = selString.size();
1283 for (int i = 0; i < len; i++)
1284 if (selString[i] == ':')
1286 NameStr += selString;
1288 // Remember this name for metadata emission
1289 MethodInternalNames[OMD] = NameStr;
1290 ResultStr += NameStr;
1292 // Rewrite arguments
1295 // invisible arguments
1296 if (OMD->isInstanceMethod()) {
1297 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1298 selfTy = Context->getPointerType(selfTy);
1299 if (!LangOpts.MicrosoftExt) {
1300 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1301 ResultStr += "struct ";
1303 // When rewriting for Microsoft, explicitly omit the structure name.
1304 ResultStr += IDecl->getNameAsString();
1308 ResultStr += Context->getObjCClassType().getAsString(
1309 Context->getPrintingPolicy());
1311 ResultStr += " self, ";
1312 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1313 ResultStr += " _cmd";
1315 // Method arguments.
1316 for (const auto *PDecl : OMD->params()) {
1318 if (PDecl->getType()->isObjCQualifiedIdType()) {
1320 ResultStr += PDecl->getNameAsString();
1322 std::string Name = PDecl->getNameAsString();
1323 QualType QT = PDecl->getType();
1324 // Make sure we convert "t (^)(...)" to "t (*)(...)".
1325 (void)convertBlockPointerToFunctionPointer(QT);
1326 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1330 if (OMD->isVariadic())
1331 ResultStr += ", ...";
1335 ResultStr += ")"; // close the precedence "scope" for "*".
1337 // Now, emit the argument types (if any).
1338 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1340 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
1341 if (i) ResultStr += ", ";
1342 std::string ParamStr =
1343 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1344 ResultStr += ParamStr;
1346 if (FT->isVariadic()) {
1347 if (FT->getNumParams())
1357 void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1358 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1359 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1362 if (IMD->getIvarRBraceLoc().isValid()) {
1363 ReplaceText(IMD->getLocStart(), 1, "/** ");
1364 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
1367 InsertText(IMD->getLocStart(), "// ");
1371 InsertText(CID->getLocStart(), "// ");
1373 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
1374 std::string ResultStr;
1375 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1376 SourceLocation LocStart = OMD->getLocStart();
1377 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1379 const char *startBuf = SM->getCharacterData(LocStart);
1380 const char *endBuf = SM->getCharacterData(LocEnd);
1381 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1384 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
1385 std::string ResultStr;
1386 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1387 SourceLocation LocStart = OMD->getLocStart();
1388 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1390 const char *startBuf = SM->getCharacterData(LocStart);
1391 const char *endBuf = SM->getCharacterData(LocEnd);
1392 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1394 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1395 RewritePropertyImplDecl(I, IMD, CID);
1397 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1400 void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1401 // Do not synthesize more than once.
1402 if (ObjCSynthesizedStructs.count(ClassDecl))
1404 // Make sure super class's are written before current class is written.
1405 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1406 while (SuperClass) {
1407 RewriteInterfaceDecl(SuperClass);
1408 SuperClass = SuperClass->getSuperClass();
1410 std::string ResultStr;
1411 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
1412 // we haven't seen a forward decl - generate a typedef.
1413 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
1414 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1416 RewriteObjCInternalStruct(ClassDecl, ResultStr);
1417 // Mark this typedef as having been written into its c++ equivalent.
1418 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
1420 for (auto *I : ClassDecl->properties())
1422 for (auto *I : ClassDecl->instance_methods())
1423 RewriteMethodDeclaration(I);
1424 for (auto *I : ClassDecl->class_methods())
1425 RewriteMethodDeclaration(I);
1427 // Lastly, comment out the @end.
1428 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1433 Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1434 SourceRange OldRange = PseudoOp->getSourceRange();
1436 // We just magically know some things about the structure of this
1438 ObjCMessageExpr *OldMsg =
1439 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1440 PseudoOp->getNumSemanticExprs() - 1));
1442 // Because the rewriter doesn't allow us to rewrite rewritten code,
1443 // we need to suppress rewriting the sub-statements.
1445 SmallVector<Expr*, 2> Args;
1447 DisableReplaceStmtScope S(*this);
1449 // Rebuild the base expression if we have one.
1451 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1452 Base = OldMsg->getInstanceReceiver();
1453 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1454 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1457 unsigned numArgs = OldMsg->getNumArgs();
1458 for (unsigned i = 0; i < numArgs; i++) {
1459 Expr *Arg = OldMsg->getArg(i);
1460 if (isa<OpaqueValueExpr>(Arg))
1461 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1462 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1463 Args.push_back(Arg);
1467 // TODO: avoid this copy.
1468 SmallVector<SourceLocation, 1> SelLocs;
1469 OldMsg->getSelectorLocs(SelLocs);
1471 ObjCMessageExpr *NewMsg = nullptr;
1472 switch (OldMsg->getReceiverKind()) {
1473 case ObjCMessageExpr::Class:
1474 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1475 OldMsg->getValueKind(),
1476 OldMsg->getLeftLoc(),
1477 OldMsg->getClassReceiverTypeInfo(),
1478 OldMsg->getSelector(),
1480 OldMsg->getMethodDecl(),
1482 OldMsg->getRightLoc(),
1483 OldMsg->isImplicit());
1486 case ObjCMessageExpr::Instance:
1487 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1488 OldMsg->getValueKind(),
1489 OldMsg->getLeftLoc(),
1491 OldMsg->getSelector(),
1493 OldMsg->getMethodDecl(),
1495 OldMsg->getRightLoc(),
1496 OldMsg->isImplicit());
1499 case ObjCMessageExpr::SuperClass:
1500 case ObjCMessageExpr::SuperInstance:
1501 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1502 OldMsg->getValueKind(),
1503 OldMsg->getLeftLoc(),
1504 OldMsg->getSuperLoc(),
1505 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1506 OldMsg->getSuperType(),
1507 OldMsg->getSelector(),
1509 OldMsg->getMethodDecl(),
1511 OldMsg->getRightLoc(),
1512 OldMsg->isImplicit());
1516 Stmt *Replacement = SynthMessageExpr(NewMsg);
1517 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1521 Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1522 SourceRange OldRange = PseudoOp->getSourceRange();
1524 // We just magically know some things about the structure of this
1526 ObjCMessageExpr *OldMsg =
1527 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1529 // Because the rewriter doesn't allow us to rewrite rewritten code,
1530 // we need to suppress rewriting the sub-statements.
1531 Expr *Base = nullptr;
1532 SmallVector<Expr*, 1> Args;
1534 DisableReplaceStmtScope S(*this);
1535 // Rebuild the base expression if we have one.
1536 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1537 Base = OldMsg->getInstanceReceiver();
1538 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1539 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1541 unsigned numArgs = OldMsg->getNumArgs();
1542 for (unsigned i = 0; i < numArgs; i++) {
1543 Expr *Arg = OldMsg->getArg(i);
1544 if (isa<OpaqueValueExpr>(Arg))
1545 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1546 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1547 Args.push_back(Arg);
1551 // Intentionally empty.
1552 SmallVector<SourceLocation, 1> SelLocs;
1554 ObjCMessageExpr *NewMsg = nullptr;
1555 switch (OldMsg->getReceiverKind()) {
1556 case ObjCMessageExpr::Class:
1557 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1558 OldMsg->getValueKind(),
1559 OldMsg->getLeftLoc(),
1560 OldMsg->getClassReceiverTypeInfo(),
1561 OldMsg->getSelector(),
1563 OldMsg->getMethodDecl(),
1565 OldMsg->getRightLoc(),
1566 OldMsg->isImplicit());
1569 case ObjCMessageExpr::Instance:
1570 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1571 OldMsg->getValueKind(),
1572 OldMsg->getLeftLoc(),
1574 OldMsg->getSelector(),
1576 OldMsg->getMethodDecl(),
1578 OldMsg->getRightLoc(),
1579 OldMsg->isImplicit());
1582 case ObjCMessageExpr::SuperClass:
1583 case ObjCMessageExpr::SuperInstance:
1584 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1585 OldMsg->getValueKind(),
1586 OldMsg->getLeftLoc(),
1587 OldMsg->getSuperLoc(),
1588 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1589 OldMsg->getSuperType(),
1590 OldMsg->getSelector(),
1592 OldMsg->getMethodDecl(),
1594 OldMsg->getRightLoc(),
1595 OldMsg->isImplicit());
1599 Stmt *Replacement = SynthMessageExpr(NewMsg);
1600 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1604 /// SynthCountByEnumWithState - To print:
1605 /// ((NSUInteger (*)
1606 /// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1607 /// (void *)objc_msgSend)((id)l_collection,
1608 /// sel_registerName(
1609 /// "countByEnumeratingWithState:objects:count:"),
1611 /// (id *)__rw_items, (NSUInteger)16)
1613 void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
1614 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1615 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
1617 buf += "((id)l_collection,\n\t\t";
1618 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1620 buf += "&enumState, "
1621 "(id *)__rw_items, (_WIN_NSUInteger)16)";
1624 /// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1625 /// statement to exit to its outer synthesized loop.
1627 Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1628 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1630 // replace break with goto __break_label
1633 SourceLocation startLoc = S->getLocStart();
1634 buf = "goto __break_label_";
1635 buf += utostr(ObjCBcLabelNo.back());
1636 ReplaceText(startLoc, strlen("break"), buf);
1641 void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1643 std::string &LineString) {
1644 if (Loc.isFileID() && GenerateLineInfo) {
1645 LineString += "\n#line ";
1646 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1647 LineString += utostr(PLoc.getLine());
1648 LineString += " \"";
1649 LineString += Lexer::Stringify(PLoc.getFilename());
1650 LineString += "\"\n";
1654 /// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1655 /// statement to continue with its inner synthesized loop.
1657 Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1658 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1660 // replace continue with goto __continue_label
1663 SourceLocation startLoc = S->getLocStart();
1664 buf = "goto __continue_label_";
1665 buf += utostr(ObjCBcLabelNo.back());
1666 ReplaceText(startLoc, strlen("continue"), buf);
1671 /// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1673 /// for ( type elem in collection) { stmts; }
1678 /// struct __objcFastEnumerationState enumState = { 0 };
1679 /// id __rw_items[16];
1680 /// id l_collection = (id)collection;
1681 /// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
1682 /// objects:__rw_items count:16];
1684 /// unsigned long startMutations = *enumState.mutationsPtr;
1686 /// unsigned long counter = 0;
1688 /// if (startMutations != *enumState.mutationsPtr)
1689 /// objc_enumerationMutation(l_collection);
1690 /// elem = (type)enumState.itemsPtr[counter++];
1692 /// __continue_label: ;
1693 /// } while (counter < limit);
1694 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1695 /// objects:__rw_items count:16]));
1697 /// __break_label: ;
1703 Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1704 SourceLocation OrigEnd) {
1705 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1706 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1707 "ObjCForCollectionStmt Statement stack mismatch");
1708 assert(!ObjCBcLabelNo.empty() &&
1709 "ObjCForCollectionStmt - Label No stack empty");
1711 SourceLocation startLoc = S->getLocStart();
1712 const char *startBuf = SM->getCharacterData(startLoc);
1713 StringRef elementName;
1714 std::string elementTypeAsString;
1716 // line directive first.
1717 SourceLocation ForEachLoc = S->getForLoc();
1718 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1720 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1722 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1723 QualType ElementType = cast<ValueDecl>(D)->getType();
1724 if (ElementType->isObjCQualifiedIdType() ||
1725 ElementType->isObjCQualifiedInterfaceType())
1726 // Simply use 'id' for all qualified types.
1727 elementTypeAsString = "id";
1729 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1730 buf += elementTypeAsString;
1732 elementName = D->getName();
1737 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1738 elementName = DR->getDecl()->getName();
1739 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1740 if (VD->getType()->isObjCQualifiedIdType() ||
1741 VD->getType()->isObjCQualifiedInterfaceType())
1742 // Simply use 'id' for all qualified types.
1743 elementTypeAsString = "id";
1745 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1748 // struct __objcFastEnumerationState enumState = { 0 };
1749 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1750 // id __rw_items[16];
1751 buf += "id __rw_items[16];\n\t";
1752 // id l_collection = (id)
1753 buf += "id l_collection = (id)";
1754 // Find start location of 'collection' the hard way!
1755 const char *startCollectionBuf = startBuf;
1756 startCollectionBuf += 3; // skip 'for'
1757 startCollectionBuf = strchr(startCollectionBuf, '(');
1758 startCollectionBuf++; // skip '('
1759 // find 'in' and skip it.
1760 while (*startCollectionBuf != ' ' ||
1761 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1762 (*(startCollectionBuf+3) != ' ' &&
1763 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1764 startCollectionBuf++;
1765 startCollectionBuf += 3;
1767 // Replace: "for (type element in" with string constructed thus far.
1768 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1769 // Replace ')' in for '(' type elem in collection ')' with ';'
1770 SourceLocation rightParenLoc = S->getRParenLoc();
1771 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1772 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1775 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1776 // objects:__rw_items count:16];
1777 // which is synthesized into:
1778 // NSUInteger limit =
1780 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
1781 // (void *)objc_msgSend)((id)l_collection,
1782 // sel_registerName(
1783 // "countByEnumeratingWithState:objects:count:"),
1784 // (struct __objcFastEnumerationState *)&state,
1785 // (id *)__rw_items, (NSUInteger)16);
1786 buf += "_WIN_NSUInteger limit =\n\t\t";
1787 SynthCountByEnumWithState(buf);
1790 /// unsigned long startMutations = *enumState.mutationsPtr;
1792 /// unsigned long counter = 0;
1794 /// if (startMutations != *enumState.mutationsPtr)
1795 /// objc_enumerationMutation(l_collection);
1796 /// elem = (type)enumState.itemsPtr[counter++];
1797 buf += "if (limit) {\n\t";
1798 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1799 buf += "do {\n\t\t";
1800 buf += "unsigned long counter = 0;\n\t\t";
1801 buf += "do {\n\t\t\t";
1802 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1803 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1806 buf += elementTypeAsString;
1807 buf += ")enumState.itemsPtr[counter++];";
1808 // Replace ')' in for '(' type elem in collection ')' with all of these.
1809 ReplaceText(lparenLoc, 1, buf);
1811 /// __continue_label: ;
1812 /// } while (counter < limit);
1813 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1814 /// objects:__rw_items count:16]));
1816 /// __break_label: ;
1823 buf += "__continue_label_";
1824 buf += utostr(ObjCBcLabelNo.back());
1827 buf += "} while (counter < limit);\n\t";
1828 buf += "} while ((limit = ";
1829 SynthCountByEnumWithState(buf);
1833 buf += elementTypeAsString;
1835 buf += "__break_label_";
1836 buf += utostr(ObjCBcLabelNo.back());
1839 buf += "else\n\t\t";
1842 buf += elementTypeAsString;
1846 // Insert all these *after* the statement body.
1847 // FIXME: If this should support Obj-C++, support CXXTryStmt
1848 if (isa<CompoundStmt>(S->getBody())) {
1849 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1850 InsertText(endBodyLoc, buf);
1852 /* Need to treat single statements specially. For example:
1854 * for (A *a in b) if (stuff()) break;
1855 * for (A *a in b) xxxyy;
1857 * The following code simply scans ahead to the semi to find the actual end.
1859 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1860 const char *semiBuf = strchr(stmtBuf, ';');
1861 assert(semiBuf && "Can't find ';'");
1862 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1863 InsertText(endBodyLoc, buf);
1866 ObjCBcLabelNo.pop_back();
1870 static void Write_RethrowObject(std::string &buf) {
1871 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1872 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1873 buf += "\tid rethrow;\n";
1874 buf += "\t} _fin_force_rethow(_rethrow);";
1877 /// RewriteObjCSynchronizedStmt -
1878 /// This routine rewrites @synchronized(expr) stmt;
1880 /// objc_sync_enter(expr);
1881 /// @try stmt @finally { objc_sync_exit(expr); }
1883 Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1884 // Get the start location and compute the semi location.
1885 SourceLocation startLoc = S->getLocStart();
1886 const char *startBuf = SM->getCharacterData(startLoc);
1888 assert((*startBuf == '@') && "bogus @synchronized location");
1891 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1892 ConvertSourceLocationToLineDirective(SynchLoc, buf);
1893 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
1895 const char *lparenBuf = startBuf;
1896 while (*lparenBuf != '(') lparenBuf++;
1897 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1899 buf = "; objc_sync_enter(_sync_obj);\n";
1900 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1901 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1902 buf += "\n\tid sync_exit;";
1903 buf += "\n\t} _sync_exit(_sync_obj);\n";
1905 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1906 // the sync expression is typically a message expression that's already
1907 // been rewritten! (which implies the SourceLocation's are invalid).
1908 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1909 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1910 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1911 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1913 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1914 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1915 assert (*LBraceLocBuf == '{');
1916 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
1918 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
1919 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1920 "bogus @synchronized block");
1922 buf = "} catch (id e) {_rethrow = e;}\n";
1923 Write_RethrowObject(buf);
1927 ReplaceText(startRBraceLoc, 1, buf);
1932 void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1934 // Perform a bottom up traversal of all children.
1935 for (Stmt *SubStmt : S->children())
1937 WarnAboutReturnGotoStmts(SubStmt);
1939 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1940 Diags.Report(Context->getFullLoc(S->getLocStart()),
1941 TryFinallyContainsReturnDiag);
1946 Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1947 SourceLocation startLoc = S->getAtLoc();
1948 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
1949 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1950 "{ __AtAutoreleasePool __autoreleasepool; ");
1955 Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1956 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
1957 bool noCatch = S->getNumCatchStmts() == 0;
1959 SourceLocation TryLocation = S->getAtTryLoc();
1960 ConvertSourceLocationToLineDirective(TryLocation, buf);
1964 buf += "{ id volatile _rethrow = 0;\n";
1966 buf += "{ id volatile _rethrow = 0;\ntry {\n";
1969 // Get the start location and compute the semi location.
1970 SourceLocation startLoc = S->getLocStart();
1971 const char *startBuf = SM->getCharacterData(startLoc);
1973 assert((*startBuf == '@') && "bogus @try location");
1975 ReplaceText(startLoc, 1, buf);
1978 ReplaceText(startLoc, 1, "");
1980 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1981 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1982 VarDecl *catchDecl = Catch->getCatchParamDecl();
1984 startLoc = Catch->getLocStart();
1985 bool AtRemoved = false;
1987 QualType t = catchDecl->getType();
1988 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
1989 // Should be a pointer to a class.
1990 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1993 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
1995 startBuf = SM->getCharacterData(startLoc);
1996 assert((*startBuf == '@') && "bogus @catch location");
1997 SourceLocation rParenLoc = Catch->getRParenLoc();
1998 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2000 // _objc_exc_Foo *_e as argument to catch.
2001 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
2002 Result += " *_"; Result += catchDecl->getNameAsString();
2004 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2005 // Foo *e = (Foo *)_e;
2008 Result += IDecl->getNameAsString();
2009 Result += " *"; Result += catchDecl->getNameAsString();
2010 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2011 Result += "_"; Result += catchDecl->getNameAsString();
2014 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2015 ReplaceText(lBraceLoc, 1, Result);
2022 ReplaceText(startLoc, 1, "");
2027 SourceLocation FinallyLoc = finalStmt->getLocStart();
2030 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2031 buf += "catch (id e) {_rethrow = e;}\n";
2035 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2036 buf += "catch (id e) {_rethrow = e;}\n";
2039 SourceLocation startFinalLoc = finalStmt->getLocStart();
2040 ReplaceText(startFinalLoc, 8, buf);
2041 Stmt *body = finalStmt->getFinallyBody();
2042 SourceLocation startFinalBodyLoc = body->getLocStart();
2044 Write_RethrowObject(buf);
2045 ReplaceText(startFinalBodyLoc, 1, buf);
2047 SourceLocation endFinalBodyLoc = body->getLocEnd();
2048 ReplaceText(endFinalBodyLoc, 1, "}\n}");
2049 // Now check for any return/continue/go statements within the @try.
2050 WarnAboutReturnGotoStmts(S->getTryBody());
2056 // This can't be done with ReplaceStmt(S, ThrowExpr), since
2057 // the throw expression is typically a message expression that's already
2058 // been rewritten! (which implies the SourceLocation's are invalid).
2059 Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2060 // Get the start location and compute the semi location.
2061 SourceLocation startLoc = S->getLocStart();
2062 const char *startBuf = SM->getCharacterData(startLoc);
2064 assert((*startBuf == '@') && "bogus @throw location");
2067 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2068 if (S->getThrowExpr())
2069 buf = "objc_exception_throw(";
2073 // handle "@ throw" correctly.
2074 const char *wBuf = strchr(startBuf, 'w');
2075 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2076 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2078 SourceLocation endLoc = S->getLocEnd();
2079 const char *endBuf = SM->getCharacterData(endLoc);
2080 const char *semiBuf = strchr(endBuf, ';');
2081 assert((*semiBuf == ';') && "@throw: can't find ';'");
2082 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
2083 if (S->getThrowExpr())
2084 ReplaceText(semiLoc, 1, ");");
2088 Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2089 // Create a new string expression.
2090 std::string StrEncoding;
2091 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2092 Expr *Replacement = getStringLiteral(StrEncoding);
2093 ReplaceStmt(Exp, Replacement);
2095 // Replace this subexpr in the parent.
2096 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2100 Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2101 if (!SelGetUidFunctionDecl)
2102 SynthSelGetUidFunctionDecl();
2103 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2104 // Create a call to sel_registerName("selName").
2105 SmallVector<Expr*, 8> SelExprs;
2106 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2107 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2109 ReplaceStmt(Exp, SelExp);
2110 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2115 RewriteModernObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2116 ArrayRef<Expr *> Args,
2117 SourceLocation StartLoc,
2118 SourceLocation EndLoc) {
2119 // Get the type, we will need to reference it in a couple spots.
2120 QualType msgSendType = FD->getType();
2122 // Create a reference to the objc_msgSend() declaration.
2124 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
2126 // Now, we cast the reference to a pointer to the objc_msgSend type.
2127 QualType pToFunc = Context->getPointerType(msgSendType);
2128 ImplicitCastExpr *ICE =
2129 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2130 DRE, nullptr, VK_RValue);
2132 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2134 CallExpr *Exp = new (Context) CallExpr(*Context, ICE, Args,
2135 FT->getCallResultType(*Context),
2140 static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2141 const char *&startRef, const char *&endRef) {
2142 while (startBuf < endBuf) {
2143 if (*startBuf == '<')
2144 startRef = startBuf; // mark the start.
2145 if (*startBuf == '>') {
2146 if (startRef && *startRef == '<') {
2147 endRef = startBuf; // mark the end.
2157 static void scanToNextArgument(const char *&argRef) {
2159 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2162 else if (*argRef == '>')
2166 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2169 bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2170 if (T->isObjCQualifiedIdType())
2172 if (const PointerType *PT = T->getAs<PointerType>()) {
2173 if (PT->getPointeeType()->isObjCQualifiedIdType())
2176 if (T->isObjCObjectPointerType()) {
2177 T = T->getPointeeType();
2178 return T->isObjCQualifiedInterfaceType();
2180 if (T->isArrayType()) {
2181 QualType ElemTy = Context->getBaseElementType(T);
2182 return needToScanForQualifiers(ElemTy);
2187 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2188 QualType Type = E->getType();
2189 if (needToScanForQualifiers(Type)) {
2190 SourceLocation Loc, EndLoc;
2192 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2193 Loc = ECE->getLParenLoc();
2194 EndLoc = ECE->getRParenLoc();
2196 Loc = E->getLocStart();
2197 EndLoc = E->getLocEnd();
2199 // This will defend against trying to rewrite synthesized expressions.
2200 if (Loc.isInvalid() || EndLoc.isInvalid())
2203 const char *startBuf = SM->getCharacterData(Loc);
2204 const char *endBuf = SM->getCharacterData(EndLoc);
2205 const char *startRef = nullptr, *endRef = nullptr;
2206 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2207 // Get the locations of the startRef, endRef.
2208 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2209 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2210 // Comment out the protocol references.
2211 InsertText(LessLoc, "/*");
2212 InsertText(GreaterLoc, "*/");
2217 void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2220 const FunctionProtoType *proto = nullptr;
2221 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2222 Loc = VD->getLocation();
2223 Type = VD->getType();
2225 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2226 Loc = FD->getLocation();
2227 // Check for ObjC 'id' and class types that have been adorned with protocol
2228 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2229 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2230 assert(funcType && "missing function type");
2231 proto = dyn_cast<FunctionProtoType>(funcType);
2234 Type = proto->getReturnType();
2236 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2237 Loc = FD->getLocation();
2238 Type = FD->getType();
2240 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2241 Loc = TD->getLocation();
2242 Type = TD->getUnderlyingType();
2247 if (needToScanForQualifiers(Type)) {
2248 // Since types are unique, we need to scan the buffer.
2250 const char *endBuf = SM->getCharacterData(Loc);
2251 const char *startBuf = endBuf;
2252 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2253 startBuf--; // scan backward (from the decl location) for return type.
2254 const char *startRef = nullptr, *endRef = nullptr;
2255 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2256 // Get the locations of the startRef, endRef.
2257 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2258 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2259 // Comment out the protocol references.
2260 InsertText(LessLoc, "/*");
2261 InsertText(GreaterLoc, "*/");
2265 return; // most likely, was a variable
2266 // Now check arguments.
2267 const char *startBuf = SM->getCharacterData(Loc);
2268 const char *startFuncBuf = startBuf;
2269 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2270 if (needToScanForQualifiers(proto->getParamType(i))) {
2271 // Since types are unique, we need to scan the buffer.
2273 const char *endBuf = startBuf;
2274 // scan forward (from the decl location) for argument types.
2275 scanToNextArgument(endBuf);
2276 const char *startRef = nullptr, *endRef = nullptr;
2277 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2278 // Get the locations of the startRef, endRef.
2279 SourceLocation LessLoc =
2280 Loc.getLocWithOffset(startRef-startFuncBuf);
2281 SourceLocation GreaterLoc =
2282 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2283 // Comment out the protocol references.
2284 InsertText(LessLoc, "/*");
2285 InsertText(GreaterLoc, "*/");
2287 startBuf = ++endBuf;
2290 // If the function name is derived from a macro expansion, then the
2291 // argument buffer will not follow the name. Need to speak with Chris.
2292 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2293 startBuf++; // scan forward (from the decl location) for argument types.
2299 void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2300 QualType QT = ND->getType();
2301 const Type* TypePtr = QT->getAs<Type>();
2302 if (!isa<TypeOfExprType>(TypePtr))
2304 while (isa<TypeOfExprType>(TypePtr)) {
2305 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2306 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2307 TypePtr = QT->getAs<Type>();
2309 // FIXME. This will not work for multiple declarators; as in:
2310 // __typeof__(a) b,c,d;
2311 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2312 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2313 const char *startBuf = SM->getCharacterData(DeclLoc);
2314 if (ND->getInit()) {
2315 std::string Name(ND->getNameAsString());
2316 TypeAsString += " " + Name + " = ";
2317 Expr *E = ND->getInit();
2318 SourceLocation startLoc;
2319 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2320 startLoc = ECE->getLParenLoc();
2322 startLoc = E->getLocStart();
2323 startLoc = SM->getExpansionLoc(startLoc);
2324 const char *endBuf = SM->getCharacterData(startLoc);
2325 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2328 SourceLocation X = ND->getLocEnd();
2329 X = SM->getExpansionLoc(X);
2330 const char *endBuf = SM->getCharacterData(X);
2331 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2335 // SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2336 void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2337 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2338 SmallVector<QualType, 16> ArgTys;
2339 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2340 QualType getFuncType =
2341 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2342 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2345 SelGetUidIdent, getFuncType,
2346 nullptr, SC_Extern);
2349 void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2350 // declared in <objc/objc.h>
2351 if (FD->getIdentifier() &&
2352 FD->getName() == "sel_registerName") {
2353 SelGetUidFunctionDecl = FD;
2356 RewriteObjCQualifiedInterfaceTypes(FD);
2359 void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2360 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2361 const char *argPtr = TypeString.c_str();
2362 if (!strchr(argPtr, '^')) {
2367 Str += (*argPtr == '^' ? '*' : *argPtr);
2372 // FIXME. Consolidate this routine with RewriteBlockPointerType.
2373 void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2375 QualType Type = VD->getType();
2376 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2377 const char *argPtr = TypeString.c_str();
2392 Str += VD->getNameAsString();
2402 void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2403 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2404 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2405 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2408 QualType Type = proto->getReturnType();
2409 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2411 FdStr += FD->getName();
2413 unsigned numArgs = proto->getNumParams();
2414 for (unsigned i = 0; i < numArgs; i++) {
2415 QualType ArgType = proto->getParamType(i);
2416 RewriteBlockPointerType(FdStr, ArgType);
2420 if (FD->isVariadic()) {
2421 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2425 InsertText(FunLocStart, FdStr);
2428 // SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2429 void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2430 if (SuperConstructorFunctionDecl)
2432 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2433 SmallVector<QualType, 16> ArgTys;
2434 QualType argT = Context->getObjCIdType();
2435 assert(!argT.isNull() && "Can't find 'id' type");
2436 ArgTys.push_back(argT);
2437 ArgTys.push_back(argT);
2438 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2440 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2443 msgSendIdent, msgSendType,
2444 nullptr, SC_Extern);
2447 // SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2448 void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2449 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2450 SmallVector<QualType, 16> ArgTys;
2451 QualType argT = Context->getObjCIdType();
2452 assert(!argT.isNull() && "Can't find 'id' type");
2453 ArgTys.push_back(argT);
2454 argT = Context->getObjCSelType();
2455 assert(!argT.isNull() && "Can't find 'SEL' type");
2456 ArgTys.push_back(argT);
2457 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2458 ArgTys, /*isVariadic=*/true);
2459 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2462 msgSendIdent, msgSendType, nullptr,
2466 // SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
2467 void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2468 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2469 SmallVector<QualType, 2> ArgTys;
2470 ArgTys.push_back(Context->VoidTy);
2471 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2472 ArgTys, /*isVariadic=*/true);
2473 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2476 msgSendIdent, msgSendType,
2477 nullptr, SC_Extern);
2480 // SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2481 void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2482 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2483 SmallVector<QualType, 16> ArgTys;
2484 QualType argT = Context->getObjCIdType();
2485 assert(!argT.isNull() && "Can't find 'id' type");
2486 ArgTys.push_back(argT);
2487 argT = Context->getObjCSelType();
2488 assert(!argT.isNull() && "Can't find 'SEL' type");
2489 ArgTys.push_back(argT);
2490 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2491 ArgTys, /*isVariadic=*/true);
2492 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2495 msgSendIdent, msgSendType,
2496 nullptr, SC_Extern);
2499 // SynthMsgSendSuperStretFunctionDecl -
2500 // id objc_msgSendSuper_stret(void);
2501 void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2502 IdentifierInfo *msgSendIdent =
2503 &Context->Idents.get("objc_msgSendSuper_stret");
2504 SmallVector<QualType, 2> ArgTys;
2505 ArgTys.push_back(Context->VoidTy);
2506 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2507 ArgTys, /*isVariadic=*/true);
2508 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2512 msgSendType, nullptr,
2516 // SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2517 void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2518 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2519 SmallVector<QualType, 16> ArgTys;
2520 QualType argT = Context->getObjCIdType();
2521 assert(!argT.isNull() && "Can't find 'id' type");
2522 ArgTys.push_back(argT);
2523 argT = Context->getObjCSelType();
2524 assert(!argT.isNull() && "Can't find 'SEL' type");
2525 ArgTys.push_back(argT);
2526 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2527 ArgTys, /*isVariadic=*/true);
2528 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2531 msgSendIdent, msgSendType,
2532 nullptr, SC_Extern);
2535 // SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
2536 void RewriteModernObjC::SynthGetClassFunctionDecl() {
2537 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2538 SmallVector<QualType, 16> ArgTys;
2539 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2540 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2542 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2545 getClassIdent, getClassType,
2546 nullptr, SC_Extern);
2549 // SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2550 void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2551 IdentifierInfo *getSuperClassIdent =
2552 &Context->Idents.get("class_getSuperclass");
2553 SmallVector<QualType, 16> ArgTys;
2554 ArgTys.push_back(Context->getObjCClassType());
2555 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2557 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2561 getClassType, nullptr,
2565 // SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
2566 void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2567 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2568 SmallVector<QualType, 16> ArgTys;
2569 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2570 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2572 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2575 getClassIdent, getClassType,
2576 nullptr, SC_Extern);
2579 Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2580 assert (Exp != nullptr && "Expected non-null ObjCStringLiteral");
2581 QualType strType = getConstantStringStructType();
2583 std::string S = "__NSConstantStringImpl_";
2585 std::string tmpName = InFileName;
2587 for (i=0; i < tmpName.length(); i++) {
2588 char c = tmpName.at(i);
2589 // replace any non-alphanumeric characters with '_'.
2590 if (!isAlphanumeric(c))
2595 S += utostr(NumObjCStringLiterals++);
2597 Preamble += "static __NSConstantStringImpl " + S;
2598 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2599 Preamble += "0x000007c8,"; // utf8_str
2600 // The pretty printer for StringLiteral handles escape characters properly.
2601 std::string prettyBufS;
2602 llvm::raw_string_ostream prettyBuf(prettyBufS);
2603 Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2604 Preamble += prettyBuf.str();
2606 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2608 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2609 SourceLocation(), &Context->Idents.get(S),
2610 strType, nullptr, SC_Static);
2611 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
2613 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2614 Context->getPointerType(DRE->getType()),
2615 VK_RValue, OK_Ordinary,
2617 // cast to NSConstantString *
2618 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2619 CK_CPointerToObjCPointerCast, Unop);
2620 ReplaceStmt(Exp, cast);
2621 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2625 Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2627 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2629 Expr *FlagExp = IntegerLiteral::Create(*Context,
2630 llvm::APInt(IntSize, Exp->getValue()),
2631 Context->IntTy, Exp->getLocation());
2632 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2633 CK_BitCast, FlagExp);
2634 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2636 ReplaceStmt(Exp, PE);
2640 Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
2641 // synthesize declaration of helper functions needed in this routine.
2642 if (!SelGetUidFunctionDecl)
2643 SynthSelGetUidFunctionDecl();
2644 // use objc_msgSend() for all.
2645 if (!MsgSendFunctionDecl)
2646 SynthMsgSendFunctionDecl();
2647 if (!GetClassFunctionDecl)
2648 SynthGetClassFunctionDecl();
2650 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2651 SourceLocation StartLoc = Exp->getLocStart();
2652 SourceLocation EndLoc = Exp->getLocEnd();
2654 // Synthesize a call to objc_msgSend().
2655 SmallVector<Expr*, 4> MsgExprs;
2656 SmallVector<Expr*, 4> ClsExprs;
2658 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2659 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2660 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
2662 IdentifierInfo *clsName = BoxingClass->getIdentifier();
2663 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2664 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2666 MsgExprs.push_back(Cls);
2668 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
2669 // it will be the 2nd argument.
2670 SmallVector<Expr*, 4> SelExprs;
2672 getStringLiteral(BoxingMethod->getSelector().getAsString()));
2673 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2674 SelExprs, StartLoc, EndLoc);
2675 MsgExprs.push_back(SelExp);
2677 // User provided sub-expression is the 3rd, and last, argument.
2678 Expr *subExpr = Exp->getSubExpr();
2679 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
2680 QualType type = ICE->getType();
2681 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2682 CastKind CK = CK_BitCast;
2683 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2684 CK = CK_IntegralToBoolean;
2685 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
2687 MsgExprs.push_back(subExpr);
2689 SmallVector<QualType, 4> ArgTypes;
2690 ArgTypes.push_back(Context->getObjCClassType());
2691 ArgTypes.push_back(Context->getObjCSelType());
2692 for (const auto PI : BoxingMethod->parameters())
2693 ArgTypes.push_back(PI->getType());
2695 QualType returnType = Exp->getType();
2696 // Get the type, we will need to reference it in a couple spots.
2697 QualType msgSendType = MsgSendFlavor->getType();
2699 // Create a reference to the objc_msgSend() declaration.
2700 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2701 VK_LValue, SourceLocation());
2703 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2704 Context->getPointerType(Context->VoidTy),
2707 // Now do the "normal" pointer to function cast.
2709 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
2710 castType = Context->getPointerType(castType);
2711 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2714 // Don't forget the parens to enforce the proper binding.
2715 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2717 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2718 CallExpr *CE = new (Context)
2719 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2720 ReplaceStmt(Exp, CE);
2724 Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2725 // synthesize declaration of helper functions needed in this routine.
2726 if (!SelGetUidFunctionDecl)
2727 SynthSelGetUidFunctionDecl();
2728 // use objc_msgSend() for all.
2729 if (!MsgSendFunctionDecl)
2730 SynthMsgSendFunctionDecl();
2731 if (!GetClassFunctionDecl)
2732 SynthGetClassFunctionDecl();
2734 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2735 SourceLocation StartLoc = Exp->getLocStart();
2736 SourceLocation EndLoc = Exp->getLocEnd();
2738 // Build the expression: __NSContainer_literal(int, ...).arr
2739 QualType IntQT = Context->IntTy;
2740 QualType NSArrayFType =
2741 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2742 std::string NSArrayFName("__NSContainer_literal");
2743 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2744 DeclRefExpr *NSArrayDRE =
2745 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2748 SmallVector<Expr*, 16> InitExprs;
2749 unsigned NumElements = Exp->getNumElements();
2750 unsigned UnsignedIntSize =
2751 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2752 Expr *count = IntegerLiteral::Create(*Context,
2753 llvm::APInt(UnsignedIntSize, NumElements),
2754 Context->UnsignedIntTy, SourceLocation());
2755 InitExprs.push_back(count);
2756 for (unsigned i = 0; i < NumElements; i++)
2757 InitExprs.push_back(Exp->getElement(i));
2758 Expr *NSArrayCallExpr =
2759 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
2760 NSArrayFType, VK_LValue, SourceLocation());
2762 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2764 &Context->Idents.get("arr"),
2765 Context->getPointerType(Context->VoidPtrTy),
2766 nullptr, /*BitWidth=*/nullptr,
2767 /*Mutable=*/true, ICIS_NoInit);
2768 MemberExpr *ArrayLiteralME = new (Context)
2769 MemberExpr(NSArrayCallExpr, false, SourceLocation(), ARRFD,
2770 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2771 QualType ConstIdT = Context->getObjCIdType().withConst();
2772 CStyleCastExpr * ArrayLiteralObjects =
2773 NoTypeInfoCStyleCastExpr(Context,
2774 Context->getPointerType(ConstIdT),
2778 // Synthesize a call to objc_msgSend().
2779 SmallVector<Expr*, 32> MsgExprs;
2780 SmallVector<Expr*, 4> ClsExprs;
2781 QualType expType = Exp->getType();
2783 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2784 ObjCInterfaceDecl *Class =
2785 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2787 IdentifierInfo *clsName = Class->getIdentifier();
2788 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2789 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2791 MsgExprs.push_back(Cls);
2793 // Create a call to sel_registerName("arrayWithObjects:count:").
2794 // it will be the 2nd argument.
2795 SmallVector<Expr*, 4> SelExprs;
2796 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2798 getStringLiteral(ArrayMethod->getSelector().getAsString()));
2799 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2800 SelExprs, StartLoc, EndLoc);
2801 MsgExprs.push_back(SelExp);
2803 // (const id [])objects
2804 MsgExprs.push_back(ArrayLiteralObjects);
2807 Expr *cnt = IntegerLiteral::Create(*Context,
2808 llvm::APInt(UnsignedIntSize, NumElements),
2809 Context->UnsignedIntTy, SourceLocation());
2810 MsgExprs.push_back(cnt);
2813 SmallVector<QualType, 4> ArgTypes;
2814 ArgTypes.push_back(Context->getObjCClassType());
2815 ArgTypes.push_back(Context->getObjCSelType());
2816 for (const auto *PI : ArrayMethod->params())
2817 ArgTypes.push_back(PI->getType());
2819 QualType returnType = Exp->getType();
2820 // Get the type, we will need to reference it in a couple spots.
2821 QualType msgSendType = MsgSendFlavor->getType();
2823 // Create a reference to the objc_msgSend() declaration.
2824 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2825 VK_LValue, SourceLocation());
2827 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2828 Context->getPointerType(Context->VoidTy),
2831 // Now do the "normal" pointer to function cast.
2833 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
2834 castType = Context->getPointerType(castType);
2835 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2838 // Don't forget the parens to enforce the proper binding.
2839 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2841 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2842 CallExpr *CE = new (Context)
2843 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
2844 ReplaceStmt(Exp, CE);
2848 Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2849 // synthesize declaration of helper functions needed in this routine.
2850 if (!SelGetUidFunctionDecl)
2851 SynthSelGetUidFunctionDecl();
2852 // use objc_msgSend() for all.
2853 if (!MsgSendFunctionDecl)
2854 SynthMsgSendFunctionDecl();
2855 if (!GetClassFunctionDecl)
2856 SynthGetClassFunctionDecl();
2858 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2859 SourceLocation StartLoc = Exp->getLocStart();
2860 SourceLocation EndLoc = Exp->getLocEnd();
2862 // Build the expression: __NSContainer_literal(int, ...).arr
2863 QualType IntQT = Context->IntTy;
2864 QualType NSDictFType =
2865 getSimpleFunctionType(Context->VoidTy, IntQT, true);
2866 std::string NSDictFName("__NSContainer_literal");
2867 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2868 DeclRefExpr *NSDictDRE =
2869 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2872 SmallVector<Expr*, 16> KeyExprs;
2873 SmallVector<Expr*, 16> ValueExprs;
2875 unsigned NumElements = Exp->getNumElements();
2876 unsigned UnsignedIntSize =
2877 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2878 Expr *count = IntegerLiteral::Create(*Context,
2879 llvm::APInt(UnsignedIntSize, NumElements),
2880 Context->UnsignedIntTy, SourceLocation());
2881 KeyExprs.push_back(count);
2882 ValueExprs.push_back(count);
2883 for (unsigned i = 0; i < NumElements; i++) {
2884 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2885 KeyExprs.push_back(Element.Key);
2886 ValueExprs.push_back(Element.Value);
2889 // (const id [])objects
2890 Expr *NSValueCallExpr =
2891 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
2892 NSDictFType, VK_LValue, SourceLocation());
2894 FieldDecl *ARRFD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
2896 &Context->Idents.get("arr"),
2897 Context->getPointerType(Context->VoidPtrTy),
2898 nullptr, /*BitWidth=*/nullptr,
2899 /*Mutable=*/true, ICIS_NoInit);
2900 MemberExpr *DictLiteralValueME = new (Context)
2901 MemberExpr(NSValueCallExpr, false, SourceLocation(), ARRFD,
2902 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2903 QualType ConstIdT = Context->getObjCIdType().withConst();
2904 CStyleCastExpr * DictValueObjects =
2905 NoTypeInfoCStyleCastExpr(Context,
2906 Context->getPointerType(ConstIdT),
2908 DictLiteralValueME);
2909 // (const id <NSCopying> [])keys
2910 Expr *NSKeyCallExpr =
2911 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
2912 NSDictFType, VK_LValue, SourceLocation());
2914 MemberExpr *DictLiteralKeyME = new (Context)
2915 MemberExpr(NSKeyCallExpr, false, SourceLocation(), ARRFD,
2916 SourceLocation(), ARRFD->getType(), VK_LValue, OK_Ordinary);
2918 CStyleCastExpr * DictKeyObjects =
2919 NoTypeInfoCStyleCastExpr(Context,
2920 Context->getPointerType(ConstIdT),
2926 // Synthesize a call to objc_msgSend().
2927 SmallVector<Expr*, 32> MsgExprs;
2928 SmallVector<Expr*, 4> ClsExprs;
2929 QualType expType = Exp->getType();
2931 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2932 ObjCInterfaceDecl *Class =
2933 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2935 IdentifierInfo *clsName = Class->getIdentifier();
2936 ClsExprs.push_back(getStringLiteral(clsName->getName()));
2937 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2939 MsgExprs.push_back(Cls);
2941 // Create a call to sel_registerName("arrayWithObjects:count:").
2942 // it will be the 2nd argument.
2943 SmallVector<Expr*, 4> SelExprs;
2944 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
2945 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
2946 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2947 SelExprs, StartLoc, EndLoc);
2948 MsgExprs.push_back(SelExp);
2950 // (const id [])objects
2951 MsgExprs.push_back(DictValueObjects);
2953 // (const id <NSCopying> [])keys
2954 MsgExprs.push_back(DictKeyObjects);
2957 Expr *cnt = IntegerLiteral::Create(*Context,
2958 llvm::APInt(UnsignedIntSize, NumElements),
2959 Context->UnsignedIntTy, SourceLocation());
2960 MsgExprs.push_back(cnt);
2963 SmallVector<QualType, 8> ArgTypes;
2964 ArgTypes.push_back(Context->getObjCClassType());
2965 ArgTypes.push_back(Context->getObjCSelType());
2966 for (const auto *PI : DictMethod->params()) {
2967 QualType T = PI->getType();
2968 if (const PointerType* PT = T->getAs<PointerType>()) {
2969 QualType PointeeTy = PT->getPointeeType();
2970 convertToUnqualifiedObjCType(PointeeTy);
2971 T = Context->getPointerType(PointeeTy);
2973 ArgTypes.push_back(T);
2976 QualType returnType = Exp->getType();
2977 // Get the type, we will need to reference it in a couple spots.
2978 QualType msgSendType = MsgSendFlavor->getType();
2980 // Create a reference to the objc_msgSend() declaration.
2981 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2982 VK_LValue, SourceLocation());
2984 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2985 Context->getPointerType(Context->VoidTy),
2988 // Now do the "normal" pointer to function cast.
2990 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
2991 castType = Context->getPointerType(castType);
2992 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2995 // Don't forget the parens to enforce the proper binding.
2996 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2998 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2999 CallExpr *CE = new (Context)
3000 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
3001 ReplaceStmt(Exp, CE);
3005 // struct __rw_objc_super {
3006 // struct objc_object *object; struct objc_object *superClass;
3008 QualType RewriteModernObjC::getSuperStructType() {
3009 if (!SuperStructDecl) {
3010 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3011 SourceLocation(), SourceLocation(),
3012 &Context->Idents.get("__rw_objc_super"));
3013 QualType FieldTypes[2];
3015 // struct objc_object *object;
3016 FieldTypes[0] = Context->getObjCIdType();
3017 // struct objc_object *superClass;
3018 FieldTypes[1] = Context->getObjCIdType();
3021 for (unsigned i = 0; i < 2; ++i) {
3022 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3024 SourceLocation(), nullptr,
3025 FieldTypes[i], nullptr,
3026 /*BitWidth=*/nullptr,
3031 SuperStructDecl->completeDefinition();
3033 return Context->getTagDeclType(SuperStructDecl);
3036 QualType RewriteModernObjC::getConstantStringStructType() {
3037 if (!ConstantStringDecl) {
3038 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3039 SourceLocation(), SourceLocation(),
3040 &Context->Idents.get("__NSConstantStringImpl"));
3041 QualType FieldTypes[4];
3043 // struct objc_object *receiver;
3044 FieldTypes[0] = Context->getObjCIdType();
3046 FieldTypes[1] = Context->IntTy;
3048 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3050 FieldTypes[3] = Context->LongTy;
3053 for (unsigned i = 0; i < 4; ++i) {
3054 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3057 SourceLocation(), nullptr,
3058 FieldTypes[i], nullptr,
3059 /*BitWidth=*/nullptr,
3064 ConstantStringDecl->completeDefinition();
3066 return Context->getTagDeclType(ConstantStringDecl);
3069 /// getFunctionSourceLocation - returns start location of a function
3070 /// definition. Complication arises when function has declared as
3071 /// extern "C" or extern "C" {...}
3072 static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3074 if (FD->isExternC() && !FD->isMain()) {
3075 const DeclContext *DC = FD->getDeclContext();
3076 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3077 // if it is extern "C" {...}, return function decl's own location.
3078 if (!LSD->getRBraceLoc().isValid())
3079 return LSD->getExternLoc();
3081 if (FD->getStorageClass() != SC_None)
3082 R.RewriteBlockLiteralFunctionDecl(FD);
3083 return FD->getTypeSpecStartLoc();
3086 void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3088 SourceLocation Location = D->getLocation();
3090 if (Location.isFileID() && GenerateLineInfo) {
3091 std::string LineString("\n#line ");
3092 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3093 LineString += utostr(PLoc.getLine());
3094 LineString += " \"";
3095 LineString += Lexer::Stringify(PLoc.getFilename());
3096 if (isa<ObjCMethodDecl>(D))
3098 else LineString += "\"\n";
3100 Location = D->getLocStart();
3101 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3102 if (FD->isExternC() && !FD->isMain()) {
3103 const DeclContext *DC = FD->getDeclContext();
3104 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3105 // if it is extern "C" {...}, return function decl's own location.
3106 if (!LSD->getRBraceLoc().isValid())
3107 Location = LSD->getExternLoc();
3110 InsertText(Location, LineString);
3114 /// SynthMsgSendStretCallExpr - This routine translates message expression
3115 /// into a call to objc_msgSend_stret() entry point. Tricky part is that
3116 /// nil check on receiver must be performed before calling objc_msgSend_stret.
3117 /// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3118 /// msgSendType - function type of objc_msgSend_stret(...)
3119 /// returnType - Result type of the method being synthesized.
3120 /// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3121 /// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3122 /// starting with receiver.
3123 /// Method - Method being rewritten.
3124 Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
3125 QualType returnType,
3126 SmallVectorImpl<QualType> &ArgTypes,
3127 SmallVectorImpl<Expr*> &MsgExprs,
3128 ObjCMethodDecl *Method) {
3129 // Now do the "normal" pointer to function cast.
3130 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3131 Method ? Method->isVariadic()
3133 castType = Context->getPointerType(castType);
3135 // build type for containing the objc_msgSend_stret object.
3136 static unsigned stretCount=0;
3137 std::string name = "__Stret"; name += utostr(stretCount);
3139 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
3140 str += "namespace {\n";
3141 str += "struct "; str += name;
3144 str += "(id receiver, SEL sel";
3145 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3146 std::string ArgName = "arg"; ArgName += utostr(i);
3147 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3148 str += ", "; str += ArgName;
3151 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3152 std::string ArgName = "arg"; ArgName += utostr(i);
3153 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3154 Context->getPrintingPolicy());
3155 str += ", "; str += ArgName;
3159 str += "\t unsigned size = sizeof(";
3160 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3162 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3164 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3165 str += ")(void *)objc_msgSend)(receiver, sel";
3166 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3167 str += ", arg"; str += utostr(i);
3170 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3171 str += ", arg"; str += utostr(i);
3175 str += "\t else if (receiver == 0)\n";
3176 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3180 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3181 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3182 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3183 str += ", arg"; str += utostr(i);
3186 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3187 str += ", arg"; str += utostr(i);
3193 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3195 str += "};\n};\n\n";
3196 SourceLocation FunLocStart;
3198 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3200 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3201 FunLocStart = CurMethodDef->getLocStart();
3204 InsertText(FunLocStart, str);
3207 // AST for __Stretn(receiver, args).s;
3208 IdentifierInfo *ID = &Context->Idents.get(name);
3209 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
3210 SourceLocation(), ID, castType,
3211 nullptr, SC_Extern, false, false);
3212 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3214 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
3215 castType, VK_LValue, SourceLocation());
3217 FieldDecl *FieldD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3219 &Context->Idents.get("s"),
3220 returnType, nullptr,
3221 /*BitWidth=*/nullptr,
3222 /*Mutable=*/true, ICIS_NoInit);
3223 MemberExpr *ME = new (Context)
3224 MemberExpr(STCE, false, SourceLocation(), FieldD, SourceLocation(),
3225 FieldD->getType(), VK_LValue, OK_Ordinary);
3230 Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3231 SourceLocation StartLoc,
3232 SourceLocation EndLoc) {
3233 if (!SelGetUidFunctionDecl)
3234 SynthSelGetUidFunctionDecl();
3235 if (!MsgSendFunctionDecl)
3236 SynthMsgSendFunctionDecl();
3237 if (!MsgSendSuperFunctionDecl)
3238 SynthMsgSendSuperFunctionDecl();
3239 if (!MsgSendStretFunctionDecl)
3240 SynthMsgSendStretFunctionDecl();
3241 if (!MsgSendSuperStretFunctionDecl)
3242 SynthMsgSendSuperStretFunctionDecl();
3243 if (!MsgSendFpretFunctionDecl)
3244 SynthMsgSendFpretFunctionDecl();
3245 if (!GetClassFunctionDecl)
3246 SynthGetClassFunctionDecl();
3247 if (!GetSuperClassFunctionDecl)
3248 SynthGetSuperClassFunctionDecl();
3249 if (!GetMetaClassFunctionDecl)
3250 SynthGetMetaClassFunctionDecl();
3252 // default to objc_msgSend().
3253 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3254 // May need to use objc_msgSend_stret() as well.
3255 FunctionDecl *MsgSendStretFlavor = nullptr;
3256 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3257 QualType resultType = mDecl->getReturnType();
3258 if (resultType->isRecordType())
3259 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3260 else if (resultType->isRealFloatingType())
3261 MsgSendFlavor = MsgSendFpretFunctionDecl;
3264 // Synthesize a call to objc_msgSend().
3265 SmallVector<Expr*, 8> MsgExprs;
3266 switch (Exp->getReceiverKind()) {
3267 case ObjCMessageExpr::SuperClass: {
3268 MsgSendFlavor = MsgSendSuperFunctionDecl;
3269 if (MsgSendStretFlavor)
3270 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3271 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3273 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3275 SmallVector<Expr*, 4> InitExprs;
3277 // set the receiver to self, the first argument to all methods.
3278 InitExprs.push_back(
3279 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3281 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3283 Context->getObjCIdType(),
3286 ); // set the 'receiver'.
3288 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3289 SmallVector<Expr*, 8> ClsExprs;
3290 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3291 // (Class)objc_getClass("CurrentClass")
3292 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3293 ClsExprs, StartLoc, EndLoc);
3295 ClsExprs.push_back(Cls);
3296 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3299 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3300 // To turn off a warning, type-cast to 'id'
3301 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3302 NoTypeInfoCStyleCastExpr(Context,
3303 Context->getObjCIdType(),
3305 // struct __rw_objc_super
3306 QualType superType = getSuperStructType();
3309 if (LangOpts.MicrosoftExt) {
3310 SynthSuperConstructorFunctionDecl();
3311 // Simulate a constructor call...
3312 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3313 false, superType, VK_LValue,
3315 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3316 superType, VK_LValue,
3318 // The code for super is a little tricky to prevent collision with
3319 // the structure definition in the header. The rewriter has it's own
3320 // internal definition (__rw_objc_super) that is uses. This is why
3321 // we need the cast below. For example:
3322 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3324 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3325 Context->getPointerType(SuperRep->getType()),
3326 VK_RValue, OK_Ordinary,
3328 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3329 Context->getPointerType(superType),
3330 CK_BitCast, SuperRep);
3332 // (struct __rw_objc_super) { <exprs from above> }
3334 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3336 TypeSourceInfo *superTInfo
3337 = Context->getTrivialTypeSourceInfo(superType);
3338 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3339 superType, VK_LValue,
3341 // struct __rw_objc_super *
3342 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3343 Context->getPointerType(SuperRep->getType()),
3344 VK_RValue, OK_Ordinary,
3347 MsgExprs.push_back(SuperRep);
3351 case ObjCMessageExpr::Class: {
3352 SmallVector<Expr*, 8> ClsExprs;
3353 ObjCInterfaceDecl *Class
3354 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3355 IdentifierInfo *clsName = Class->getIdentifier();
3356 ClsExprs.push_back(getStringLiteral(clsName->getName()));
3357 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3359 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3360 Context->getObjCIdType(),
3362 MsgExprs.push_back(ArgExpr);
3366 case ObjCMessageExpr::SuperInstance:{
3367 MsgSendFlavor = MsgSendSuperFunctionDecl;
3368 if (MsgSendStretFlavor)
3369 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3370 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3371 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3372 SmallVector<Expr*, 4> InitExprs;
3374 InitExprs.push_back(
3375 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3377 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
3379 Context->getObjCIdType(),
3380 VK_RValue, SourceLocation()))
3381 ); // set the 'receiver'.
3383 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3384 SmallVector<Expr*, 8> ClsExprs;
3385 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
3386 // (Class)objc_getClass("CurrentClass")
3387 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
3390 ClsExprs.push_back(Cls);
3391 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
3394 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3395 // To turn off a warning, type-cast to 'id'
3396 InitExprs.push_back(
3397 // set 'super class', using class_getSuperclass().
3398 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3400 // struct __rw_objc_super
3401 QualType superType = getSuperStructType();
3404 if (LangOpts.MicrosoftExt) {
3405 SynthSuperConstructorFunctionDecl();
3406 // Simulate a constructor call...
3407 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
3408 false, superType, VK_LValue,
3410 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
3411 superType, VK_LValue, SourceLocation());
3412 // The code for super is a little tricky to prevent collision with
3413 // the structure definition in the header. The rewriter has it's own
3414 // internal definition (__rw_objc_super) that is uses. This is why
3415 // we need the cast below. For example:
3416 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
3418 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3419 Context->getPointerType(SuperRep->getType()),
3420 VK_RValue, OK_Ordinary,
3422 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3423 Context->getPointerType(superType),
3424 CK_BitCast, SuperRep);
3426 // (struct __rw_objc_super) { <exprs from above> }
3428 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
3430 TypeSourceInfo *superTInfo
3431 = Context->getTrivialTypeSourceInfo(superType);
3432 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3433 superType, VK_RValue, ILE,
3436 MsgExprs.push_back(SuperRep);
3440 case ObjCMessageExpr::Instance: {
3441 // Remove all type-casts because it may contain objc-style types; e.g.
3443 Expr *recExpr = Exp->getInstanceReceiver();
3444 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3445 recExpr = CE->getSubExpr();
3446 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3447 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3448 ? CK_BlockPointerToObjCPointerCast
3449 : CK_CPointerToObjCPointerCast;
3451 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3453 MsgExprs.push_back(recExpr);
3458 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3459 SmallVector<Expr*, 8> SelExprs;
3460 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
3461 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3462 SelExprs, StartLoc, EndLoc);
3463 MsgExprs.push_back(SelExp);
3465 // Now push any user supplied arguments.
3466 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3467 Expr *userExpr = Exp->getArg(i);
3468 // Make all implicit casts explicit...ICE comes in handy:-)
3469 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3470 // Reuse the ICE type, it is exactly what the doctor ordered.
3471 QualType type = ICE->getType();
3472 if (needToScanForQualifiers(type))
3473 type = Context->getObjCIdType();
3474 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3475 (void)convertBlockPointerToFunctionPointer(type);
3476 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3478 if (SubExpr->getType()->isIntegralType(*Context) &&
3479 type->isBooleanType()) {
3480 CK = CK_IntegralToBoolean;
3481 } else if (type->isObjCObjectPointerType()) {
3482 if (SubExpr->getType()->isBlockPointerType()) {
3483 CK = CK_BlockPointerToObjCPointerCast;
3484 } else if (SubExpr->getType()->isPointerType()) {
3485 CK = CK_CPointerToObjCPointerCast;
3493 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3495 // Make id<P...> cast into an 'id' cast.
3496 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3497 if (CE->getType()->isObjCQualifiedIdType()) {
3498 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3499 userExpr = CE->getSubExpr();
3501 if (userExpr->getType()->isIntegralType(*Context)) {
3502 CK = CK_IntegralToPointer;
3503 } else if (userExpr->getType()->isBlockPointerType()) {
3504 CK = CK_BlockPointerToObjCPointerCast;
3505 } else if (userExpr->getType()->isPointerType()) {
3506 CK = CK_CPointerToObjCPointerCast;
3510 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3514 MsgExprs.push_back(userExpr);
3515 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3516 // out the argument in the original expression (since we aren't deleting
3517 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3518 //Exp->setArg(i, 0);
3520 // Generate the funky cast.
3522 SmallVector<QualType, 8> ArgTypes;
3523 QualType returnType;
3525 // Push 'id' and 'SEL', the 2 implicit arguments.
3526 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3527 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3529 ArgTypes.push_back(Context->getObjCIdType());
3530 ArgTypes.push_back(Context->getObjCSelType());
3531 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3532 // Push any user argument types.
3533 for (const auto *PI : OMD->params()) {
3534 QualType t = PI->getType()->isObjCQualifiedIdType()
3535 ? Context->getObjCIdType()
3537 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3538 (void)convertBlockPointerToFunctionPointer(t);
3539 ArgTypes.push_back(t);
3541 returnType = Exp->getType();
3542 convertToUnqualifiedObjCType(returnType);
3543 (void)convertBlockPointerToFunctionPointer(returnType);
3545 returnType = Context->getObjCIdType();
3547 // Get the type, we will need to reference it in a couple spots.
3548 QualType msgSendType = MsgSendFlavor->getType();
3550 // Create a reference to the objc_msgSend() declaration.
3551 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3552 VK_LValue, SourceLocation());
3554 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3555 // If we don't do this cast, we get the following bizarre warning/note:
3556 // xx.m:13: warning: function called through a non-compatible type
3557 // xx.m:13: note: if this code is reached, the program will abort
3558 cast = NoTypeInfoCStyleCastExpr(Context,
3559 Context->getPointerType(Context->VoidTy),
3562 // Now do the "normal" pointer to function cast.
3563 // If we don't have a method decl, force a variadic cast.
3564 const ObjCMethodDecl *MD = Exp->getMethodDecl();
3566 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
3567 castType = Context->getPointerType(castType);
3568 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3571 // Don't forget the parens to enforce the proper binding.
3572 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3574 const FunctionType *FT = msgSendType->getAs<FunctionType>();
3575 CallExpr *CE = new (Context)
3576 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
3577 Stmt *ReplacingStmt = CE;
3578 if (MsgSendStretFlavor) {
3579 // We have the method which returns a struct/union. Must also generate
3580 // call to objc_msgSend_stret and hang both varieties on a conditional
3581 // expression which dictate which one to envoke depending on size of
3582 // method's return type.
3584 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3587 Exp->getMethodDecl());
3588 ReplacingStmt = STCE;
3590 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3591 return ReplacingStmt;
3594 Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3595 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3598 // Now do the actual rewrite.
3599 ReplaceStmt(Exp, ReplacingStmt);
3601 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3602 return ReplacingStmt;
3605 // typedef struct objc_object Protocol;
3606 QualType RewriteModernObjC::getProtocolType() {
3607 if (!ProtocolTypeDecl) {
3608 TypeSourceInfo *TInfo
3609 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3610 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3611 SourceLocation(), SourceLocation(),
3612 &Context->Idents.get("Protocol"),
3615 return Context->getTypeDeclType(ProtocolTypeDecl);
3618 /// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3619 /// a synthesized/forward data reference (to the protocol's metadata).
3620 /// The forward references (and metadata) are generated in
3621 /// RewriteModernObjC::HandleTranslationUnit().
3622 Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3623 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3624 Exp->getProtocol()->getNameAsString();
3625 IdentifierInfo *ID = &Context->Idents.get(Name);
3626 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3627 SourceLocation(), ID, getProtocolType(),
3628 nullptr, SC_Extern);
3629 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3630 VK_LValue, SourceLocation());
3631 CastExpr *castExpr =
3632 NoTypeInfoCStyleCastExpr(
3633 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
3634 ReplaceStmt(Exp, castExpr);
3635 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3636 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3641 bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3642 const char *endBuf) {
3643 while (startBuf < endBuf) {
3644 if (*startBuf == '#') {
3646 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3648 if (!strncmp(startBuf, "if", strlen("if")) ||
3649 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3650 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3651 !strncmp(startBuf, "define", strlen("define")) ||
3652 !strncmp(startBuf, "undef", strlen("undef")) ||
3653 !strncmp(startBuf, "else", strlen("else")) ||
3654 !strncmp(startBuf, "elif", strlen("elif")) ||
3655 !strncmp(startBuf, "endif", strlen("endif")) ||
3656 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3657 !strncmp(startBuf, "include", strlen("include")) ||
3658 !strncmp(startBuf, "import", strlen("import")) ||
3659 !strncmp(startBuf, "include_next", strlen("include_next")))
3667 /// IsTagDefinedInsideClass - This routine checks that a named tagged type
3668 /// is defined inside an objective-c class. If so, it returns true.
3669 bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
3671 bool &IsNamedDefinition) {
3674 SourceLocation TagLocation;
3675 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3676 RD = RD->getDefinition();
3677 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
3679 IsNamedDefinition = true;
3680 TagLocation = RD->getLocation();
3681 return Context->getSourceManager().isBeforeInTranslationUnit(
3682 IDecl->getLocation(), TagLocation);
3684 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3685 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3687 IsNamedDefinition = true;
3688 TagLocation = ED->getLocation();
3689 return Context->getSourceManager().isBeforeInTranslationUnit(
3690 IDecl->getLocation(), TagLocation);
3696 /// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
3697 /// It handles elaborated types, as well as enum types in the process.
3698 bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3699 std::string &Result) {
3700 if (isa<TypedefType>(Type)) {
3705 if (Type->isArrayType()) {
3706 QualType ElemTy = Context->getBaseElementType(Type);
3707 return RewriteObjCFieldDeclType(ElemTy, Result);
3709 else if (Type->isRecordType()) {
3710 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3711 if (RD->isCompleteDefinition()) {
3713 Result += "\n\tstruct ";
3714 else if (RD->isUnion())
3715 Result += "\n\tunion ";
3717 assert(false && "class not allowed as an ivar type");
3719 Result += RD->getName();
3720 if (GlobalDefinedTags.count(RD)) {
3721 // struct/union is defined globally, use it.
3726 for (auto *FD : RD->fields())
3727 RewriteObjCFieldDecl(FD, Result);
3732 else if (Type->isEnumeralType()) {
3733 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3734 if (ED->isCompleteDefinition()) {
3735 Result += "\n\tenum ";
3736 Result += ED->getName();
3737 if (GlobalDefinedTags.count(ED)) {
3738 // Enum is globall defined, use it.
3744 for (const auto *EC : ED->enumerators()) {
3745 Result += "\t"; Result += EC->getName(); Result += " = ";
3746 llvm::APSInt Val = EC->getInitVal();
3747 Result += Val.toString(10);
3756 convertObjCTypeToCStyleType(Type);
3761 /// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3762 /// It handles elaborated types, as well as enum types in the process.
3763 void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3764 std::string &Result) {
3765 QualType Type = fieldDecl->getType();
3766 std::string Name = fieldDecl->getNameAsString();
3768 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3769 if (!EleboratedType)
3770 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
3772 if (fieldDecl->isBitField()) {
3773 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3775 else if (EleboratedType && Type->isArrayType()) {
3776 const ArrayType *AT = Context->getAsArrayType(Type);
3778 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
3780 llvm::APInt Dim = CAT->getSize();
3781 Result += utostr(Dim.getZExtValue());
3784 AT = Context->getAsArrayType(AT->getElementType());
3791 /// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3792 /// named aggregate types into the input buffer.
3793 void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3794 std::string &Result) {
3795 QualType Type = fieldDecl->getType();
3796 if (isa<TypedefType>(Type))
3798 if (Type->isArrayType())
3799 Type = Context->getBaseElementType(Type);
3800 ObjCContainerDecl *IDecl =
3801 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
3803 TagDecl *TD = nullptr;
3804 if (Type->isRecordType()) {
3805 TD = Type->getAs<RecordType>()->getDecl();
3807 else if (Type->isEnumeralType()) {
3808 TD = Type->getAs<EnumType>()->getDecl();
3812 if (GlobalDefinedTags.count(TD))
3815 bool IsNamedDefinition = false;
3816 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3817 RewriteObjCFieldDeclType(Type, Result);
3820 if (IsNamedDefinition)
3821 GlobalDefinedTags.insert(TD);
3826 unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3827 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3828 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3829 return IvarGroupNumber[IV];
3831 unsigned GroupNo = 0;
3832 SmallVector<const ObjCIvarDecl *, 8> IVars;
3833 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3834 IVD; IVD = IVD->getNextIvar())
3835 IVars.push_back(IVD);
3837 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3838 if (IVars[i]->isBitField()) {
3839 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3840 while (i < e && IVars[i]->isBitField())
3841 IvarGroupNumber[IVars[i++]] = GroupNo;
3846 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3847 return IvarGroupNumber[IV];
3850 QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3852 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3853 std::string StructTagName;
3854 ObjCIvarBitfieldGroupType(IV, StructTagName);
3855 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3856 Context->getTranslationUnitDecl(),
3857 SourceLocation(), SourceLocation(),
3858 &Context->Idents.get(StructTagName));
3859 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3860 ObjCIvarDecl *Ivar = IVars[i];
3861 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3862 &Context->Idents.get(Ivar->getName()),
3864 nullptr, /*Expr *BW */Ivar->getBitWidth(),
3865 false, ICIS_NoInit));
3867 RD->completeDefinition();
3868 return Context->getTagDeclType(RD);
3871 QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3872 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3873 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3874 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3875 if (GroupRecordType.count(tuple))
3876 return GroupRecordType[tuple];
3878 SmallVector<ObjCIvarDecl *, 8> IVars;
3879 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3880 IVD; IVD = IVD->getNextIvar()) {
3881 if (IVD->isBitField())
3882 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3884 if (!IVars.empty()) {
3885 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3886 // Generate the struct type for this group of bitfield ivars.
3887 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3888 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3893 if (!IVars.empty()) {
3895 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3896 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3897 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3899 QualType RetQT = GroupRecordType[tuple];
3900 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3905 /// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3906 /// Name would be: classname__GRBF_n where n is the group number for this ivar.
3907 void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3908 std::string &Result) {
3909 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3910 Result += CDecl->getName();
3911 Result += "__GRBF_";
3912 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3913 Result += utostr(GroupNo);
3917 /// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3918 /// Name of the struct would be: classname__T_n where n is the group number for
3920 void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3921 std::string &Result) {
3922 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3923 Result += CDecl->getName();
3925 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3926 Result += utostr(GroupNo);
3930 /// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3931 /// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3933 void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3934 std::string &Result) {
3935 Result += "OBJC_IVAR_$_";
3936 ObjCIvarBitfieldGroupDecl(IV, Result);
3939 #define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3940 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3946 /// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3947 /// an objective-c class with ivars.
3948 void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3949 std::string &Result) {
3950 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3951 assert(CDecl->getName() != "" &&
3952 "Name missing in SynthesizeObjCInternalStruct");
3953 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3954 SmallVector<ObjCIvarDecl *, 8> IVars;
3955 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3956 IVD; IVD = IVD->getNextIvar())
3957 IVars.push_back(IVD);
3959 SourceLocation LocStart = CDecl->getLocStart();
3960 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3962 const char *startBuf = SM->getCharacterData(LocStart);
3963 const char *endBuf = SM->getCharacterData(LocEnd);
3965 // If no ivars and no root or if its root, directly or indirectly,
3966 // have no ivars (thus not synthesized) then no need to synthesize this class.
3967 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
3968 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
3969 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3970 ReplaceText(LocStart, endBuf-startBuf, Result);
3974 // Insert named struct/union definitions inside class to
3975 // outer scope. This follows semantics of locally defined
3976 // struct/unions in objective-c classes.
3977 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3978 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
3980 // Insert named structs which are syntheized to group ivar bitfields
3981 // to outer scope as well.
3982 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3983 if (IVars[i]->isBitField()) {
3984 ObjCIvarDecl *IV = IVars[i];
3985 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
3986 RewriteObjCFieldDeclType(QT, Result);
3988 // skip over ivar bitfields in this group.
3989 SKIP_BITFIELDS(i , e, IVars);
3992 Result += "\nstruct ";
3993 Result += CDecl->getNameAsString();
3994 Result += "_IMPL {\n";
3996 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
3997 Result += "\tstruct "; Result += RCDecl->getNameAsString();
3998 Result += "_IMPL "; Result += RCDecl->getNameAsString();
3999 Result += "_IVARS;\n";
4002 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4003 if (IVars[i]->isBitField()) {
4004 ObjCIvarDecl *IV = IVars[i];
4005 Result += "\tstruct ";
4006 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4007 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4008 // skip over ivar bitfields in this group.
4009 SKIP_BITFIELDS(i , e, IVars);
4012 RewriteObjCFieldDecl(IVars[i], Result);
4016 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4017 ReplaceText(LocStart, endBuf-startBuf, Result);
4018 // Mark this struct as having been generated.
4019 if (!ObjCSynthesizedStructs.insert(CDecl).second)
4020 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
4023 /// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4024 /// have been referenced in an ivar access expression.
4025 void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4026 std::string &Result) {
4027 // write out ivar offset symbols which have been referenced in an ivar
4028 // access expression.
4029 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4033 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
4034 for (ObjCIvarDecl *IvarDecl : Ivars) {
4035 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4036 unsigned GroupNo = 0;
4037 if (IvarDecl->isBitField()) {
4038 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4039 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4043 if (LangOpts.MicrosoftExt)
4044 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
4045 Result += "extern \"C\" ";
4046 if (LangOpts.MicrosoftExt &&
4047 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
4048 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4049 Result += "__declspec(dllimport) ";
4051 Result += "unsigned long ";
4052 if (IvarDecl->isBitField()) {
4053 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4054 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4057 WriteInternalIvarName(CDecl, IvarDecl, Result);
4062 //===----------------------------------------------------------------------===//
4063 // Meta Data Emission
4064 //===----------------------------------------------------------------------===//
4067 /// RewriteImplementations - This routine rewrites all method implementations
4068 /// and emits meta-data.
4070 void RewriteModernObjC::RewriteImplementations() {
4071 int ClsDefCount = ClassImplementation.size();
4072 int CatDefCount = CategoryImplementation.size();
4074 // Rewrite implemented methods
4075 for (int i = 0; i < ClsDefCount; i++) {
4076 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4077 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4078 if (CDecl->isImplicitInterfaceDecl())
4080 "Legacy implicit interface rewriting not supported in moder abi");
4081 RewriteImplementationDecl(OIMP);
4084 for (int i = 0; i < CatDefCount; i++) {
4085 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4086 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4087 if (CDecl->isImplicitInterfaceDecl())
4089 "Legacy implicit interface rewriting not supported in moder abi");
4090 RewriteImplementationDecl(CIMP);
4094 void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4095 const std::string &Name,
4096 ValueDecl *VD, bool def) {
4097 assert(BlockByRefDeclNo.count(VD) &&
4098 "RewriteByRefString: ByRef decl missing");
4100 ResultStr += "struct ";
4101 ResultStr += "__Block_byref_" + Name +
4102 "_" + utostr(BlockByRefDeclNo[VD]) ;
4105 static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4106 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4107 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4111 std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4114 const FunctionType *AFT = CE->getFunctionType();
4115 QualType RT = AFT->getReturnType();
4116 std::string StructRef = "struct " + Tag;
4117 SourceLocation BlockLoc = CE->getExprLoc();
4119 ConvertSourceLocationToLineDirective(BlockLoc, S);
4121 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4122 funcName.str() + "_block_func_" + utostr(i);
4124 BlockDecl *BD = CE->getBlockDecl();
4126 if (isa<FunctionNoProtoType>(AFT)) {
4127 // No user-supplied arguments. Still need to pass in a pointer to the
4128 // block (to reference imported block decl refs).
4129 S += "(" + StructRef + " *__cself)";
4130 } else if (BD->param_empty()) {
4131 S += "(" + StructRef + " *__cself)";
4133 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4134 assert(FT && "SynthesizeBlockFunc: No function proto");
4136 // first add the implicit argument.
4137 S += StructRef + " *__cself, ";
4138 std::string ParamStr;
4139 for (BlockDecl::param_iterator AI = BD->param_begin(),
4140 E = BD->param_end(); AI != E; ++AI) {
4141 if (AI != BD->param_begin()) S += ", ";
4142 ParamStr = (*AI)->getNameAsString();
4143 QualType QT = (*AI)->getType();
4144 (void)convertBlockPointerToFunctionPointer(QT);
4145 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
4148 if (FT->isVariadic()) {
4149 if (!BD->param_empty()) S += ", ";
4156 // Create local declarations to avoid rewriting all closure decl ref exprs.
4157 // First, emit a declaration for all "by ref" decls.
4158 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4159 E = BlockByRefDecls.end(); I != E; ++I) {
4161 std::string Name = (*I)->getNameAsString();
4162 std::string TypeString;
4163 RewriteByRefString(TypeString, Name, (*I));
4165 Name = TypeString + Name;
4166 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4168 // Next, emit a declaration for all "by copy" declarations.
4169 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4170 E = BlockByCopyDecls.end(); I != E; ++I) {
4172 // Handle nested closure invocation. For example:
4174 // void (^myImportedClosure)(void);
4175 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4177 // void (^anotherClosure)(void);
4178 // anotherClosure = ^(void) {
4179 // myImportedClosure(); // import and invoke the closure
4182 if (isTopLevelBlockPointerType((*I)->getType())) {
4183 RewriteBlockPointerTypeVariable(S, (*I));
4185 RewriteBlockPointerType(S, (*I)->getType());
4187 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4190 std::string Name = (*I)->getNameAsString();
4191 QualType QT = (*I)->getType();
4192 if (HasLocalVariableExternalStorage(*I))
4193 QT = Context->getPointerType(QT);
4194 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4195 S += Name + " = __cself->" +
4196 (*I)->getNameAsString() + "; // bound by copy\n";
4199 std::string RewrittenStr = RewrittenBlockExprs[CE];
4200 const char *cstr = RewrittenStr.c_str();
4201 while (*cstr++ != '{') ;
4207 std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4210 std::string StructRef = "struct " + Tag;
4211 std::string S = "static void __";
4214 S += "_block_copy_" + utostr(i);
4215 S += "(" + StructRef;
4216 S += "*dst, " + StructRef;
4218 for (ValueDecl *VD : ImportedBlockDecls) {
4219 S += "_Block_object_assign((void*)&dst->";
4220 S += VD->getNameAsString();
4221 S += ", (void*)src->";
4222 S += VD->getNameAsString();
4223 if (BlockByRefDeclsPtrSet.count(VD))
4224 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4225 else if (VD->getType()->isBlockPointerType())
4226 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4228 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4232 S += "\nstatic void __";
4234 S += "_block_dispose_" + utostr(i);
4235 S += "(" + StructRef;
4237 for (ValueDecl *VD : ImportedBlockDecls) {
4238 S += "_Block_object_dispose((void*)src->";
4239 S += VD->getNameAsString();
4240 if (BlockByRefDeclsPtrSet.count(VD))
4241 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4242 else if (VD->getType()->isBlockPointerType())
4243 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4245 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4251 std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4253 std::string S = "\nstruct " + Tag;
4254 std::string Constructor = " " + Tag;
4256 S += " {\n struct __block_impl impl;\n";
4257 S += " struct " + Desc;
4260 Constructor += "(void *fp, "; // Invoke function pointer.
4261 Constructor += "struct " + Desc; // Descriptor pointer.
4262 Constructor += " *desc";
4264 if (BlockDeclRefs.size()) {
4265 // Output all "by copy" declarations.
4266 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4267 E = BlockByCopyDecls.end(); I != E; ++I) {
4269 std::string FieldName = (*I)->getNameAsString();
4270 std::string ArgName = "_" + FieldName;
4271 // Handle nested closure invocation. For example:
4273 // void (^myImportedBlock)(void);
4274 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4276 // void (^anotherBlock)(void);
4277 // anotherBlock = ^(void) {
4278 // myImportedBlock(); // import and invoke the closure
4281 if (isTopLevelBlockPointerType((*I)->getType())) {
4282 S += "struct __block_impl *";
4283 Constructor += ", void *" + ArgName;
4285 QualType QT = (*I)->getType();
4286 if (HasLocalVariableExternalStorage(*I))
4287 QT = Context->getPointerType(QT);
4288 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4289 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4290 Constructor += ", " + ArgName;
4292 S += FieldName + ";\n";
4294 // Output all "by ref" declarations.
4295 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4296 E = BlockByRefDecls.end(); I != E; ++I) {
4298 std::string FieldName = (*I)->getNameAsString();
4299 std::string ArgName = "_" + FieldName;
4301 std::string TypeString;
4302 RewriteByRefString(TypeString, FieldName, (*I));
4304 FieldName = TypeString + FieldName;
4305 ArgName = TypeString + ArgName;
4306 Constructor += ", " + ArgName;
4308 S += FieldName + "; // by ref\n";
4310 // Finish writing the constructor.
4311 Constructor += ", int flags=0)";
4312 // Initialize all "by copy" arguments.
4313 bool firsTime = true;
4314 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4315 E = BlockByCopyDecls.end(); I != E; ++I) {
4316 std::string Name = (*I)->getNameAsString();
4318 Constructor += " : ";
4322 Constructor += ", ";
4323 if (isTopLevelBlockPointerType((*I)->getType()))
4324 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4326 Constructor += Name + "(_" + Name + ")";
4328 // Initialize all "by ref" arguments.
4329 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4330 E = BlockByRefDecls.end(); I != E; ++I) {
4331 std::string Name = (*I)->getNameAsString();
4333 Constructor += " : ";
4337 Constructor += ", ";
4338 Constructor += Name + "(_" + Name + "->__forwarding)";
4341 Constructor += " {\n";
4343 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4345 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4346 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4348 Constructor += " Desc = desc;\n";
4350 // Finish writing the constructor.
4351 Constructor += ", int flags=0) {\n";
4353 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4355 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4356 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4357 Constructor += " Desc = desc;\n";
4360 Constructor += "}\n";
4366 std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4367 std::string ImplTag, int i,
4370 std::string S = "\nstatic struct " + DescTag;
4372 S += " {\n size_t reserved;\n";
4373 S += " size_t Block_size;\n";
4375 S += " void (*copy)(struct ";
4376 S += ImplTag; S += "*, struct ";
4377 S += ImplTag; S += "*);\n";
4379 S += " void (*dispose)(struct ";
4380 S += ImplTag; S += "*);\n";
4384 S += DescTag + "_DATA = { 0, sizeof(struct ";
4387 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4388 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4394 void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4395 StringRef FunName) {
4396 bool RewriteSC = (GlobalVarDecl &&
4398 GlobalVarDecl->getStorageClass() == SC_Static &&
4399 GlobalVarDecl->getType().getCVRQualifiers());
4401 std::string SC(" void __");
4402 SC += GlobalVarDecl->getNameAsString();
4404 InsertText(FunLocStart, SC);
4407 // Insert closures that were part of the function.
4408 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4409 CollectBlockDeclRefInfo(Blocks[i]);
4410 // Need to copy-in the inner copied-in variables not actually used in this
4412 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
4413 DeclRefExpr *Exp = InnerDeclRefs[count++];
4414 ValueDecl *VD = Exp->getDecl();
4415 BlockDeclRefs.push_back(Exp);
4416 if (!VD->hasAttr<BlocksAttr>()) {
4417 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4418 BlockByCopyDeclsPtrSet.insert(VD);
4419 BlockByCopyDecls.push_back(VD);
4424 if (!BlockByRefDeclsPtrSet.count(VD)) {
4425 BlockByRefDeclsPtrSet.insert(VD);
4426 BlockByRefDecls.push_back(VD);
4429 // imported objects in the inner blocks not used in the outer
4430 // blocks must be copied/disposed in the outer block as well.
4431 if (VD->getType()->isObjCObjectPointerType() ||
4432 VD->getType()->isBlockPointerType())
4433 ImportedBlockDecls.insert(VD);
4436 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4437 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4439 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4441 InsertText(FunLocStart, CI);
4443 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4445 InsertText(FunLocStart, CF);
4447 if (ImportedBlockDecls.size()) {
4448 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4449 InsertText(FunLocStart, HF);
4451 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4452 ImportedBlockDecls.size() > 0);
4453 InsertText(FunLocStart, BD);
4455 BlockDeclRefs.clear();
4456 BlockByRefDecls.clear();
4457 BlockByRefDeclsPtrSet.clear();
4458 BlockByCopyDecls.clear();
4459 BlockByCopyDeclsPtrSet.clear();
4460 ImportedBlockDecls.clear();
4463 // Must insert any 'const/volatile/static here. Since it has been
4464 // removed as result of rewriting of block literals.
4466 if (GlobalVarDecl->getStorageClass() == SC_Static)
4468 if (GlobalVarDecl->getType().isConstQualified())
4470 if (GlobalVarDecl->getType().isVolatileQualified())
4472 if (GlobalVarDecl->getType().isRestrictQualified())
4474 InsertText(FunLocStart, SC);
4476 if (GlobalConstructionExp) {
4477 // extra fancy dance for global literal expression.
4479 // Always the latest block expression on the block stack.
4480 std::string Tag = "__";
4482 Tag += "_block_impl_";
4483 Tag += utostr(Blocks.size()-1);
4484 std::string globalBuf = "static ";
4485 globalBuf += Tag; globalBuf += " ";
4488 llvm::raw_string_ostream constructorExprBuf(SStr);
4489 GlobalConstructionExp->printPretty(constructorExprBuf, nullptr,
4490 PrintingPolicy(LangOpts));
4491 globalBuf += constructorExprBuf.str();
4493 InsertText(FunLocStart, globalBuf);
4494 GlobalConstructionExp = nullptr;
4498 InnerDeclRefsCount.clear();
4499 InnerDeclRefs.clear();
4500 RewrittenBlockExprs.clear();
4503 void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
4504 SourceLocation FunLocStart =
4505 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4506 : FD->getTypeSpecStartLoc();
4507 StringRef FuncName = FD->getName();
4509 SynthesizeBlockLiterals(FunLocStart, FuncName);
4512 static void BuildUniqueMethodName(std::string &Name,
4513 ObjCMethodDecl *MD) {
4514 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4515 Name = IFace->getName();
4516 Name += "__" + MD->getSelector().getAsString();
4517 // Convert colons to underscores.
4518 std::string::size_type loc = 0;
4519 while ((loc = Name.find(":", loc)) != std::string::npos)
4520 Name.replace(loc, 1, "_");
4523 void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4524 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4525 //SourceLocation FunLocStart = MD->getLocStart();
4526 SourceLocation FunLocStart = MD->getLocStart();
4527 std::string FuncName;
4528 BuildUniqueMethodName(FuncName, MD);
4529 SynthesizeBlockLiterals(FunLocStart, FuncName);
4532 void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4533 for (Stmt *SubStmt : S->children())
4535 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
4536 GetBlockDeclRefExprs(CBE->getBody());
4538 GetBlockDeclRefExprs(SubStmt);
4540 // Handle specific things.
4541 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
4542 if (DRE->refersToEnclosingVariableOrCapture() ||
4543 HasLocalVariableExternalStorage(DRE->getDecl()))
4544 // FIXME: Handle enums.
4545 BlockDeclRefs.push_back(DRE);
4550 void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4551 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
4552 llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
4553 for (Stmt *SubStmt : S->children())
4555 if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
4556 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4557 GetInnerBlockDeclRefExprs(CBE->getBody(),
4562 GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
4564 // Handle specific things.
4565 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4566 if (DRE->refersToEnclosingVariableOrCapture() ||
4567 HasLocalVariableExternalStorage(DRE->getDecl())) {
4568 if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
4569 InnerBlockDeclRefs.push_back(DRE);
4570 if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
4571 if (Var->isFunctionOrMethodVarDecl())
4572 ImportedLocalExternalDecls.insert(Var);
4579 /// convertObjCTypeToCStyleType - This routine converts such objc types
4580 /// as qualified objects, and blocks to their closest c/c++ types that
4581 /// it can. It returns true if input type was modified.
4582 bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4584 convertBlockPointerToFunctionPointer(T);
4585 if (T->isFunctionPointerType()) {
4587 if (const PointerType* PT = T->getAs<PointerType>()) {
4588 PointeeTy = PT->getPointeeType();
4589 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4590 T = convertFunctionTypeOfBlocks(FT);
4591 T = Context->getPointerType(T);
4596 convertToUnqualifiedObjCType(T);
4600 /// convertFunctionTypeOfBlocks - This routine converts a function type
4601 /// whose result type may be a block pointer or whose argument type(s)
4602 /// might be block pointers to an equivalent function type replacing
4603 /// all block pointers to function pointers.
4604 QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4605 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4606 // FTP will be null for closures that don't take arguments.
4607 // Generate a funky cast.
4608 SmallVector<QualType, 8> ArgTypes;
4609 QualType Res = FT->getReturnType();
4610 bool modified = convertObjCTypeToCStyleType(Res);
4613 for (auto &I : FTP->param_types()) {
4615 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4616 if (convertObjCTypeToCStyleType(t))
4618 ArgTypes.push_back(t);
4623 FuncType = getSimpleFunctionType(Res, ArgTypes);
4624 else FuncType = QualType(FT, 0);
4628 Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4629 // Navigate to relevant type information.
4630 const BlockPointerType *CPT = nullptr;
4632 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4633 CPT = DRE->getType()->getAs<BlockPointerType>();
4634 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4635 CPT = MExpr->getType()->getAs<BlockPointerType>();
4637 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4638 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4640 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4641 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4642 else if (const ConditionalOperator *CEXPR =
4643 dyn_cast<ConditionalOperator>(BlockExp)) {
4644 Expr *LHSExp = CEXPR->getLHS();
4645 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4646 Expr *RHSExp = CEXPR->getRHS();
4647 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4648 Expr *CONDExp = CEXPR->getCond();
4649 ConditionalOperator *CondExpr =
4650 new (Context) ConditionalOperator(CONDExp,
4651 SourceLocation(), cast<Expr>(LHSStmt),
4652 SourceLocation(), cast<Expr>(RHSStmt),
4653 Exp->getType(), VK_RValue, OK_Ordinary);
4655 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4656 CPT = IRE->getType()->getAs<BlockPointerType>();
4657 } else if (const PseudoObjectExpr *POE
4658 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4659 CPT = POE->getType()->castAs<BlockPointerType>();
4661 assert(1 && "RewriteBlockClass: Bad type");
4663 assert(CPT && "RewriteBlockClass: Bad type");
4664 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4665 assert(FT && "RewriteBlockClass: Bad type");
4666 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4667 // FTP will be null for closures that don't take arguments.
4669 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4670 SourceLocation(), SourceLocation(),
4671 &Context->Idents.get("__block_impl"));
4672 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4674 // Generate a funky cast.
4675 SmallVector<QualType, 8> ArgTypes;
4677 // Push the block argument type.
4678 ArgTypes.push_back(PtrBlock);
4680 for (auto &I : FTP->param_types()) {
4682 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4683 if (!convertBlockPointerToFunctionPointer(t))
4684 convertToUnqualifiedObjCType(t);
4685 ArgTypes.push_back(t);
4688 // Now do the pointer to function cast.
4689 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
4691 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4693 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4695 const_cast<Expr*>(BlockExp));
4696 // Don't forget the parens to enforce the proper binding.
4697 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4701 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4703 &Context->Idents.get("FuncPtr"),
4704 Context->VoidPtrTy, nullptr,
4705 /*BitWidth=*/nullptr, /*Mutable=*/true,
4708 new (Context) MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
4709 FD->getType(), VK_LValue, OK_Ordinary);
4711 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4713 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4715 SmallVector<Expr*, 8> BlkExprs;
4716 // Add the implicit argument.
4717 BlkExprs.push_back(BlkCast);
4718 // Add the user arguments.
4719 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4720 E = Exp->arg_end(); I != E; ++I) {
4721 BlkExprs.push_back(*I);
4723 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
4724 Exp->getType(), VK_RValue,
4729 // We need to return the rewritten expression to handle cases where the
4730 // DeclRefExpr is embedded in another expression being rewritten.
4737 // void (^myblock)() = ^() {
4738 // [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
4742 Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
4743 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4744 // for each DeclRefExp where BYREFVAR is name of the variable.
4745 ValueDecl *VD = DeclRefExp->getDecl();
4746 bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
4747 HasLocalVariableExternalStorage(DeclRefExp->getDecl());
4749 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
4751 &Context->Idents.get("__forwarding"),
4752 Context->VoidPtrTy, nullptr,
4753 /*BitWidth=*/nullptr, /*Mutable=*/true,
4755 MemberExpr *ME = new (Context)
4756 MemberExpr(DeclRefExp, isArrow, SourceLocation(), FD, SourceLocation(),
4757 FD->getType(), VK_LValue, OK_Ordinary);
4759 StringRef Name = VD->getName();
4760 FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
4761 &Context->Idents.get(Name),
4762 Context->VoidPtrTy, nullptr,
4763 /*BitWidth=*/nullptr, /*Mutable=*/true,
4766 new (Context) MemberExpr(ME, true, SourceLocation(), FD, SourceLocation(),
4767 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4769 // Need parens to enforce precedence.
4770 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4771 DeclRefExp->getExprLoc(),
4773 ReplaceStmt(DeclRefExp, PE);
4777 // Rewrites the imported local variable V with external storage
4778 // (static, extern, etc.) as *V
4780 Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4781 ValueDecl *VD = DRE->getDecl();
4782 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4783 if (!ImportedLocalExternalDecls.count(Var))
4785 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4786 VK_LValue, OK_Ordinary,
4787 DRE->getLocation());
4788 // Need parens to enforce precedence.
4789 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4791 ReplaceStmt(DRE, PE);
4795 void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4796 SourceLocation LocStart = CE->getLParenLoc();
4797 SourceLocation LocEnd = CE->getRParenLoc();
4799 // Need to avoid trying to rewrite synthesized casts.
4800 if (LocStart.isInvalid())
4802 // Need to avoid trying to rewrite casts contained in macros.
4803 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4806 const char *startBuf = SM->getCharacterData(LocStart);
4807 const char *endBuf = SM->getCharacterData(LocEnd);
4808 QualType QT = CE->getType();
4809 const Type* TypePtr = QT->getAs<Type>();
4810 if (isa<TypeOfExprType>(TypePtr)) {
4811 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4812 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4813 std::string TypeAsString = "(";
4814 RewriteBlockPointerType(TypeAsString, QT);
4815 TypeAsString += ")";
4816 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4819 // advance the location to startArgList.
4820 const char *argPtr = startBuf;
4822 while (*argPtr++ && (argPtr < endBuf)) {
4825 // Replace the '^' with '*'.
4826 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4827 ReplaceText(LocStart, 1, "*");
4834 void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4835 CastKind CastKind = IC->getCastKind();
4836 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4837 CastKind != CK_AnyPointerToBlockPointerCast)
4840 QualType QT = IC->getType();
4841 (void)convertBlockPointerToFunctionPointer(QT);
4842 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4843 std::string Str = "(";
4846 InsertText(IC->getSubExpr()->getLocStart(), Str);
4851 void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4852 SourceLocation DeclLoc = FD->getLocation();
4853 unsigned parenCount = 0;
4855 // We have 1 or more arguments that have closure pointers.
4856 const char *startBuf = SM->getCharacterData(DeclLoc);
4857 const char *startArgList = strchr(startBuf, '(');
4859 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4862 // advance the location to startArgList.
4863 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4864 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4866 const char *argPtr = startArgList;
4868 while (*argPtr++ && parenCount) {
4871 // Replace the '^' with '*'.
4872 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4873 ReplaceText(DeclLoc, 1, "*");
4886 bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4887 const FunctionProtoType *FTP;
4888 const PointerType *PT = QT->getAs<PointerType>();
4890 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4892 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4893 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4894 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4897 for (const auto &I : FTP->param_types())
4898 if (isTopLevelBlockPointerType(I))
4904 bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4905 const FunctionProtoType *FTP;
4906 const PointerType *PT = QT->getAs<PointerType>();
4908 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4910 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4911 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4912 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4915 for (const auto &I : FTP->param_types()) {
4916 if (I->isObjCQualifiedIdType())
4918 if (I->isObjCObjectPointerType() &&
4919 I->getPointeeType()->isObjCQualifiedInterfaceType())
4927 void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4928 const char *&RParen) {
4929 const char *argPtr = strchr(Name, '(');
4930 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4932 LParen = argPtr; // output the start.
4933 argPtr++; // skip past the left paren.
4934 unsigned parenCount = 1;
4936 while (*argPtr && parenCount) {
4938 case '(': parenCount++; break;
4939 case ')': parenCount--; break;
4942 if (parenCount) argPtr++;
4944 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4945 RParen = argPtr; // output the end
4948 void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4949 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4950 RewriteBlockPointerFunctionArgs(FD);
4953 // Handle Variables and Typedefs.
4954 SourceLocation DeclLoc = ND->getLocation();
4956 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4957 DeclT = VD->getType();
4958 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4959 DeclT = TDD->getUnderlyingType();
4960 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4961 DeclT = FD->getType();
4963 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4965 const char *startBuf = SM->getCharacterData(DeclLoc);
4966 const char *endBuf = startBuf;
4967 // scan backward (from the decl location) for the end of the previous decl.
4968 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
4970 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4972 unsigned OrigLength=0;
4973 // *startBuf != '^' if we are dealing with a pointer to function that
4974 // may take block argument types (which will be handled below).
4975 if (*startBuf == '^') {
4976 // Replace the '^' with '*', computing a negative offset.
4981 while (*startBuf != ')') {
4989 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4990 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
4991 // Replace the '^' with '*' for arguments.
4992 // Replace id<P> with id/*<>*/
4993 DeclLoc = ND->getLocation();
4994 startBuf = SM->getCharacterData(DeclLoc);
4995 const char *argListBegin, *argListEnd;
4996 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4997 while (argListBegin < argListEnd) {
4998 if (*argListBegin == '^')
5000 else if (*argListBegin == '<') {
5002 buf += *argListBegin++;
5004 while (*argListBegin != '>') {
5005 buf += *argListBegin++;
5008 buf += *argListBegin;
5012 buf += *argListBegin;
5019 ReplaceText(Start, OrigLength, buf);
5025 /// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5026 /// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5027 /// struct Block_byref_id_object *src) {
5028 /// _Block_object_assign (&_dest->object, _src->object,
5029 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5030 /// [|BLOCK_FIELD_IS_WEAK]) // object
5031 /// _Block_object_assign(&_dest->object, _src->object,
5032 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5033 /// [|BLOCK_FIELD_IS_WEAK]) // block
5036 /// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5037 /// _Block_object_dispose(_src->object,
5038 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5039 /// [|BLOCK_FIELD_IS_WEAK]) // object
5040 /// _Block_object_dispose(_src->object,
5041 /// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5042 /// [|BLOCK_FIELD_IS_WEAK]) // block
5045 std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5048 if (CopyDestroyCache.count(flag))
5050 CopyDestroyCache.insert(flag);
5051 S = "static void __Block_byref_id_object_copy_";
5053 S += "(void *dst, void *src) {\n";
5055 // offset into the object pointer is computed as:
5056 // void * + void* + int + int + void* + void *
5058 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5059 unsigned VoidPtrSize =
5060 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5062 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5063 S += " _Block_object_assign((char*)dst + ";
5064 S += utostr(offset);
5065 S += ", *(void * *) ((char*)src + ";
5066 S += utostr(offset);
5071 S += "static void __Block_byref_id_object_dispose_";
5073 S += "(void *src) {\n";
5074 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5075 S += utostr(offset);
5082 /// RewriteByRefVar - For each __block typex ND variable this routine transforms
5083 /// the declaration into:
5084 /// struct __Block_byref_ND {
5085 /// void *__isa; // NULL for everything except __weak pointers
5086 /// struct __Block_byref_ND *__forwarding;
5087 /// int32_t __flags;
5089 /// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5090 /// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5094 /// It then replaces declaration of ND variable with:
5095 /// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5096 /// __size=sizeof(struct __Block_byref_ND),
5097 /// ND=initializer-if-any};
5100 void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5104 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5105 if (DeclLoc.isInvalid())
5106 // If type location is missing, it is because of missing type (a warning).
5107 // Use variable's location which is good for this case.
5108 DeclLoc = ND->getLocation();
5109 const char *startBuf = SM->getCharacterData(DeclLoc);
5110 SourceLocation X = ND->getLocEnd();
5111 X = SM->getExpansionLoc(X);
5112 const char *endBuf = SM->getCharacterData(X);
5113 std::string Name(ND->getNameAsString());
5114 std::string ByrefType;
5115 RewriteByRefString(ByrefType, Name, ND, true);
5116 ByrefType += " {\n";
5117 ByrefType += " void *__isa;\n";
5118 RewriteByRefString(ByrefType, Name, ND);
5119 ByrefType += " *__forwarding;\n";
5120 ByrefType += " int __flags;\n";
5121 ByrefType += " int __size;\n";
5122 // Add void *__Block_byref_id_object_copy;
5123 // void *__Block_byref_id_object_dispose; if needed.
5124 QualType Ty = ND->getType();
5125 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
5126 if (HasCopyAndDispose) {
5127 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5128 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5132 (void)convertBlockPointerToFunctionPointer(T);
5133 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5135 ByrefType += " " + Name + ";\n";
5136 ByrefType += "};\n";
5137 // Insert this type in global scope. It is needed by helper function.
5138 SourceLocation FunLocStart;
5140 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
5142 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5143 FunLocStart = CurMethodDef->getLocStart();
5145 InsertText(FunLocStart, ByrefType);
5147 if (Ty.isObjCGCWeak()) {
5148 flag |= BLOCK_FIELD_IS_WEAK;
5151 if (HasCopyAndDispose) {
5152 flag = BLOCK_BYREF_CALLER;
5153 QualType Ty = ND->getType();
5154 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5155 if (Ty->isBlockPointerType())
5156 flag |= BLOCK_FIELD_IS_BLOCK;
5158 flag |= BLOCK_FIELD_IS_OBJECT;
5159 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5164 // struct __Block_byref_ND ND =
5165 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5166 // initializer-if-any};
5167 bool hasInit = (ND->getInit() != nullptr);
5168 // FIXME. rewriter does not support __block c++ objects which
5169 // require construction.
5171 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5172 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5173 if (CXXDecl && CXXDecl->isDefaultConstructor())
5178 if (HasCopyAndDispose)
5179 flags |= BLOCK_HAS_COPY_DISPOSE;
5180 Name = ND->getNameAsString();
5182 RewriteByRefString(ByrefType, Name, ND);
5183 std::string ForwardingCastType("(");
5184 ForwardingCastType += ByrefType + " *)";
5185 ByrefType += " " + Name + " = {(void*)";
5186 ByrefType += utostr(isa);
5187 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5188 ByrefType += utostr(flags);
5190 ByrefType += "sizeof(";
5191 RewriteByRefString(ByrefType, Name, ND);
5193 if (HasCopyAndDispose) {
5194 ByrefType += ", __Block_byref_id_object_copy_";
5195 ByrefType += utostr(flag);
5196 ByrefType += ", __Block_byref_id_object_dispose_";
5197 ByrefType += utostr(flag);
5201 // In multiple __block declarations, and for all but 1st declaration,
5202 // find location of the separating comma. This would be start location
5203 // where new text is to be inserted.
5204 DeclLoc = ND->getLocation();
5205 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5206 const char *commaBuf = startDeclBuf;
5207 while (*commaBuf != ',')
5209 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5210 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5211 startBuf = commaBuf;
5215 ByrefType += "};\n";
5216 unsigned nameSize = Name.size();
5217 // for block or function pointer declaration. Name is aleady
5218 // part of the declaration.
5219 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5221 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5225 SourceLocation startLoc;
5226 Expr *E = ND->getInit();
5227 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5228 startLoc = ECE->getLParenLoc();
5230 startLoc = E->getLocStart();
5231 startLoc = SM->getExpansionLoc(startLoc);
5232 endBuf = SM->getCharacterData(startLoc);
5233 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
5235 const char separator = lastDecl ? ';' : ',';
5236 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5237 const char *separatorBuf = strchr(startInitializerBuf, separator);
5238 assert((*separatorBuf == separator) &&
5239 "RewriteByRefVar: can't find ';' or ','");
5240 SourceLocation separatorLoc =
5241 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5243 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
5248 void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5249 // Add initializers for any closure decl refs.
5250 GetBlockDeclRefExprs(Exp->getBody());
5251 if (BlockDeclRefs.size()) {
5252 // Unique all "by copy" declarations.
5253 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5254 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5255 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5256 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5257 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5260 // Unique all "by ref" declarations.
5261 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5262 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
5263 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5264 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5265 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5268 // Find any imported blocks...they will need special attention.
5269 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
5270 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5271 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5272 BlockDeclRefs[i]->getType()->isBlockPointerType())
5273 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5277 FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5278 IdentifierInfo *ID = &Context->Idents.get(name);
5279 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5280 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5281 SourceLocation(), ID, FType, nullptr, SC_Extern,
5285 Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
5286 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
5288 const BlockDecl *block = Exp->getBlockDecl();
5290 Blocks.push_back(Exp);
5292 CollectBlockDeclRefInfo(Exp);
5294 // Add inner imported variables now used in current block.
5295 int countOfInnerDecls = 0;
5296 if (!InnerBlockDeclRefs.empty()) {
5297 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
5298 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
5299 ValueDecl *VD = Exp->getDecl();
5300 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
5301 // We need to save the copied-in variables in nested
5302 // blocks because it is needed at the end for some of the API generations.
5303 // See SynthesizeBlockLiterals routine.
5304 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5305 BlockDeclRefs.push_back(Exp);
5306 BlockByCopyDeclsPtrSet.insert(VD);
5307 BlockByCopyDecls.push_back(VD);
5309 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
5310 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5311 BlockDeclRefs.push_back(Exp);
5312 BlockByRefDeclsPtrSet.insert(VD);
5313 BlockByRefDecls.push_back(VD);
5316 // Find any imported blocks...they will need special attention.
5317 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
5318 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
5319 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5320 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5321 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5323 InnerDeclRefsCount.push_back(countOfInnerDecls);
5325 std::string FuncName;
5328 FuncName = CurFunctionDef->getNameAsString();
5329 else if (CurMethodDef)
5330 BuildUniqueMethodName(FuncName, CurMethodDef);
5331 else if (GlobalVarDecl)
5332 FuncName = std::string(GlobalVarDecl->getNameAsString());
5334 bool GlobalBlockExpr =
5335 block->getDeclContext()->getRedeclContext()->isFileContext();
5337 if (GlobalBlockExpr && !GlobalVarDecl) {
5338 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5339 GlobalBlockExpr = false;
5342 std::string BlockNumber = utostr(Blocks.size()-1);
5344 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5346 // Get a pointer to the function type so we can cast appropriately.
5347 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5348 QualType FType = Context->getPointerType(BFT);
5353 // Simulate a constructor call...
5356 if (GlobalBlockExpr)
5360 Tag += FuncName + "_block_impl_" + BlockNumber;
5362 FD = SynthBlockInitFunctionDecl(Tag);
5363 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
5366 SmallVector<Expr*, 4> InitExprs;
5368 // Initialize the block function.
5369 FD = SynthBlockInitFunctionDecl(Func);
5370 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5371 VK_LValue, SourceLocation());
5372 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5374 InitExprs.push_back(castExpr);
5376 // Initialize the block descriptor.
5377 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5379 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5380 SourceLocation(), SourceLocation(),
5381 &Context->Idents.get(DescData.c_str()),
5382 Context->VoidPtrTy, nullptr,
5384 UnaryOperator *DescRefExpr =
5385 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
5390 Context->getPointerType(Context->VoidPtrTy),
5391 VK_RValue, OK_Ordinary,
5393 InitExprs.push_back(DescRefExpr);
5395 // Add initializers for any closure decl refs.
5396 if (BlockDeclRefs.size()) {
5398 // Output all "by copy" declarations.
5399 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
5400 E = BlockByCopyDecls.end(); I != E; ++I) {
5401 if (isObjCType((*I)->getType())) {
5402 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5403 FD = SynthBlockInitFunctionDecl((*I)->getName());
5404 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5405 VK_LValue, SourceLocation());
5406 if (HasLocalVariableExternalStorage(*I)) {
5407 QualType QT = (*I)->getType();
5408 QT = Context->getPointerType(QT);
5409 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5410 OK_Ordinary, SourceLocation());
5412 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5413 FD = SynthBlockInitFunctionDecl((*I)->getName());
5414 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5415 VK_LValue, SourceLocation());
5416 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5419 FD = SynthBlockInitFunctionDecl((*I)->getName());
5420 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5421 VK_LValue, SourceLocation());
5422 if (HasLocalVariableExternalStorage(*I)) {
5423 QualType QT = (*I)->getType();
5424 QT = Context->getPointerType(QT);
5425 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5426 OK_Ordinary, SourceLocation());
5430 InitExprs.push_back(Exp);
5432 // Output all "by ref" declarations.
5433 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
5434 E = BlockByRefDecls.end(); I != E; ++I) {
5435 ValueDecl *ND = (*I);
5436 std::string Name(ND->getNameAsString());
5437 std::string RecName;
5438 RewriteByRefString(RecName, Name, ND, true);
5439 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5440 + sizeof("struct"));
5441 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5442 SourceLocation(), SourceLocation(),
5444 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5445 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5447 FD = SynthBlockInitFunctionDecl((*I)->getName());
5448 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
5450 bool isNestedCapturedVar = false;
5452 for (const auto &CI : block->captures()) {
5453 const VarDecl *variable = CI.getVariable();
5454 if (variable == ND && CI.isNested()) {
5455 assert (CI.isByRef() &&
5456 "SynthBlockInitExpr - captured block variable is not byref");
5457 isNestedCapturedVar = true;
5461 // captured nested byref variable has its address passed. Do not take
5462 // its address again.
5463 if (!isNestedCapturedVar)
5464 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5465 Context->getPointerType(Exp->getType()),
5466 VK_RValue, OK_Ordinary, SourceLocation());
5467 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5468 InitExprs.push_back(Exp);
5471 if (ImportedBlockDecls.size()) {
5472 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5473 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5475 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5476 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5477 Context->IntTy, SourceLocation());
5478 InitExprs.push_back(FlagExp);
5480 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
5481 FType, VK_LValue, SourceLocation());
5483 if (GlobalBlockExpr) {
5484 assert (!GlobalConstructionExp &&
5485 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5486 GlobalConstructionExp = NewRep;
5490 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5491 Context->getPointerType(NewRep->getType()),
5492 VK_RValue, OK_Ordinary, SourceLocation());
5493 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5495 // Put Paren around the call.
5496 NewRep = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
5499 BlockDeclRefs.clear();
5500 BlockByRefDecls.clear();
5501 BlockByRefDeclsPtrSet.clear();
5502 BlockByCopyDecls.clear();
5503 BlockByCopyDeclsPtrSet.clear();
5504 ImportedBlockDecls.clear();
5508 bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5509 if (const ObjCForCollectionStmt * CS =
5510 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5511 return CS->getElement() == DS;
5515 //===----------------------------------------------------------------------===//
5516 // Function Body / Expression rewriting
5517 //===----------------------------------------------------------------------===//
5519 Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5520 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5521 isa<DoStmt>(S) || isa<ForStmt>(S))
5523 else if (isa<ObjCForCollectionStmt>(S)) {
5525 ObjCBcLabelNo.push_back(++BcLabelCount);
5528 // Pseudo-object operations and ivar references need special
5529 // treatment because we're going to recursively rewrite them.
5530 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5531 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5532 return RewritePropertyOrImplicitSetter(PseudoOp);
5534 return RewritePropertyOrImplicitGetter(PseudoOp);
5536 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5537 return RewriteObjCIvarRefExpr(IvarRefExpr);
5539 else if (isa<OpaqueValueExpr>(S))
5540 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
5542 SourceRange OrigStmtRange = S->getSourceRange();
5544 // Perform a bottom up rewrite of all children.
5545 for (Stmt *&childStmt : S->children())
5547 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5549 childStmt = newStmt;
5553 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
5554 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
5555 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5556 InnerContexts.insert(BE->getBlockDecl());
5557 ImportedLocalExternalDecls.clear();
5558 GetInnerBlockDeclRefExprs(BE->getBody(),
5559 InnerBlockDeclRefs, InnerContexts);
5560 // Rewrite the block body in place.
5561 Stmt *SaveCurrentBody = CurrentBody;
5562 CurrentBody = BE->getBody();
5563 PropParentMap = nullptr;
5564 // block literal on rhs of a property-dot-sytax assignment
5565 // must be replaced by its synthesize ast so getRewrittenText
5566 // works as expected. In this case, what actually ends up on RHS
5567 // is the blockTranscribed which is the helper function for the
5568 // block literal; as in: self.c = ^() {[ace ARR];};
5569 bool saveDisableReplaceStmt = DisableReplaceStmt;
5570 DisableReplaceStmt = false;
5571 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5572 DisableReplaceStmt = saveDisableReplaceStmt;
5573 CurrentBody = SaveCurrentBody;
5574 PropParentMap = nullptr;
5575 ImportedLocalExternalDecls.clear();
5576 // Now we snarf the rewritten text and stash it away for later use.
5577 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5578 RewrittenBlockExprs[BE] = Str;
5580 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5582 //blockTranscribed->dump();
5583 ReplaceStmt(S, blockTranscribed);
5584 return blockTranscribed;
5586 // Handle specific things.
5587 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5588 return RewriteAtEncode(AtEncode);
5590 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5591 return RewriteAtSelector(AtSelector);
5593 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5594 return RewriteObjCStringLiteral(AtString);
5596 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5597 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
5599 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5600 return RewriteObjCBoxedExpr(BoxedExpr);
5602 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5603 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
5605 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5606 dyn_cast<ObjCDictionaryLiteral>(S))
5607 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
5609 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5611 // Before we rewrite it, put the original message expression in a comment.
5612 SourceLocation startLoc = MessExpr->getLocStart();
5613 SourceLocation endLoc = MessExpr->getLocEnd();
5615 const char *startBuf = SM->getCharacterData(startLoc);
5616 const char *endBuf = SM->getCharacterData(endLoc);
5618 std::string messString;
5619 messString += "// ";
5620 messString.append(startBuf, endBuf-startBuf+1);
5623 // FIXME: Missing definition of
5624 // InsertText(clang::SourceLocation, char const*, unsigned int).
5625 // InsertText(startLoc, messString);
5626 // Tried this, but it didn't work either...
5627 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5629 return RewriteMessageExpr(MessExpr);
5632 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5633 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5634 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5637 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5638 return RewriteObjCTryStmt(StmtTry);
5640 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5641 return RewriteObjCSynchronizedStmt(StmtTry);
5643 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5644 return RewriteObjCThrowStmt(StmtThrow);
5646 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5647 return RewriteObjCProtocolExpr(ProtocolExp);
5649 if (ObjCForCollectionStmt *StmtForCollection =
5650 dyn_cast<ObjCForCollectionStmt>(S))
5651 return RewriteObjCForCollectionStmt(StmtForCollection,
5652 OrigStmtRange.getEnd());
5653 if (BreakStmt *StmtBreakStmt =
5654 dyn_cast<BreakStmt>(S))
5655 return RewriteBreakStmt(StmtBreakStmt);
5656 if (ContinueStmt *StmtContinueStmt =
5657 dyn_cast<ContinueStmt>(S))
5658 return RewriteContinueStmt(StmtContinueStmt);
5660 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5662 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5663 // FIXME: What we're doing here is modifying the type-specifier that
5664 // precedes the first Decl. In the future the DeclGroup should have
5665 // a separate type-specifier that we can rewrite.
5666 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5667 // the context of an ObjCForCollectionStmt. For example:
5668 // NSArray *someArray;
5669 // for (id <FooProtocol> index in someArray) ;
5670 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5671 // and it depends on the original text locations/positions.
5672 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5673 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5675 // Blocks rewrite rules.
5676 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5679 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5680 if (isTopLevelBlockPointerType(ND->getType()))
5681 RewriteBlockPointerDecl(ND);
5682 else if (ND->getType()->isFunctionPointerType())
5683 CheckFunctionPointerDecl(ND->getType(), ND);
5684 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5685 if (VD->hasAttr<BlocksAttr>()) {
5686 static unsigned uniqueByrefDeclCount = 0;
5687 assert(!BlockByRefDeclNo.count(ND) &&
5688 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5689 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
5690 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
5693 RewriteTypeOfDecl(VD);
5696 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5697 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5698 RewriteBlockPointerDecl(TD);
5699 else if (TD->getUnderlyingType()->isFunctionPointerType())
5700 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5705 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5706 RewriteObjCQualifiedInterfaceTypes(CE);
5708 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5709 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5710 assert(!Stmts.empty() && "Statement stack is empty");
5711 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5712 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5713 && "Statement stack mismatch");
5716 // Handle blocks rewriting.
5717 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5718 ValueDecl *VD = DRE->getDecl();
5719 if (VD->hasAttr<BlocksAttr>())
5720 return RewriteBlockDeclRefExpr(DRE);
5721 if (HasLocalVariableExternalStorage(VD))
5722 return RewriteLocalVariableExternalStorage(DRE);
5725 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5726 if (CE->getCallee()->getType()->isBlockPointerType()) {
5727 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5728 ReplaceStmt(S, BlockCall);
5732 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5733 RewriteCastExpr(CE);
5735 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5736 RewriteImplicitCastObjCExpr(ICE);
5740 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5741 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5744 // Get the new text.
5746 llvm::raw_string_ostream Buf(SStr);
5747 Replacement->printPretty(Buf);
5748 const std::string &Str = Buf.str();
5750 printf("CAST = %s\n", &Str[0]);
5751 InsertText(ICE->getSubExpr()->getLocStart(), Str);
5756 // Return this stmt unmodified.
5760 void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5761 for (auto *FD : RD->fields()) {
5762 if (isTopLevelBlockPointerType(FD->getType()))
5763 RewriteBlockPointerDecl(FD);
5764 if (FD->getType()->isObjCQualifiedIdType() ||
5765 FD->getType()->isObjCQualifiedInterfaceType())
5766 RewriteObjCQualifiedInterfaceTypes(FD);
5770 /// HandleDeclInMainFile - This is called for each top-level decl defined in the
5771 /// main file of the input.
5772 void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5773 switch (D->getKind()) {
5774 case Decl::Function: {
5775 FunctionDecl *FD = cast<FunctionDecl>(D);
5776 if (FD->isOverloadedOperator())
5779 // Since function prototypes don't have ParmDecl's, we check the function
5780 // prototype. This enables us to rewrite function declarations and
5781 // definitions using the same code.
5782 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5784 if (!FD->isThisDeclarationADefinition())
5787 // FIXME: If this should support Obj-C++, support CXXTryStmt
5788 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5789 CurFunctionDef = FD;
5792 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5794 CurrentBody = nullptr;
5795 if (PropParentMap) {
5796 delete PropParentMap;
5797 PropParentMap = nullptr;
5799 // This synthesizes and inserts the block "impl" struct, invoke function,
5800 // and any copy/dispose helper functions.
5801 InsertBlockLiteralsWithinFunction(FD);
5802 RewriteLineDirective(D);
5803 CurFunctionDef = nullptr;
5807 case Decl::ObjCMethod: {
5808 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5809 if (CompoundStmt *Body = MD->getCompoundBody()) {
5813 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5815 CurrentBody = nullptr;
5816 if (PropParentMap) {
5817 delete PropParentMap;
5818 PropParentMap = nullptr;
5820 InsertBlockLiteralsWithinMethod(MD);
5821 RewriteLineDirective(D);
5822 CurMethodDef = nullptr;
5826 case Decl::ObjCImplementation: {
5827 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5828 ClassImplementation.push_back(CI);
5831 case Decl::ObjCCategoryImpl: {
5832 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5833 CategoryImplementation.push_back(CI);
5837 VarDecl *VD = cast<VarDecl>(D);
5838 RewriteObjCQualifiedInterfaceTypes(VD);
5839 if (isTopLevelBlockPointerType(VD->getType()))
5840 RewriteBlockPointerDecl(VD);
5841 else if (VD->getType()->isFunctionPointerType()) {
5842 CheckFunctionPointerDecl(VD->getType(), VD);
5843 if (VD->getInit()) {
5844 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5845 RewriteCastExpr(CE);
5848 } else if (VD->getType()->isRecordType()) {
5849 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5850 if (RD->isCompleteDefinition())
5851 RewriteRecordBody(RD);
5853 if (VD->getInit()) {
5855 CurrentBody = VD->getInit();
5856 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5857 CurrentBody = nullptr;
5858 if (PropParentMap) {
5859 delete PropParentMap;
5860 PropParentMap = nullptr;
5862 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5863 GlobalVarDecl = nullptr;
5865 // This is needed for blocks.
5866 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5867 RewriteCastExpr(CE);
5872 case Decl::TypeAlias:
5873 case Decl::Typedef: {
5874 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5875 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5876 RewriteBlockPointerDecl(TD);
5877 else if (TD->getUnderlyingType()->isFunctionPointerType())
5878 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5880 RewriteObjCQualifiedInterfaceTypes(TD);
5884 case Decl::CXXRecord:
5885 case Decl::Record: {
5886 RecordDecl *RD = cast<RecordDecl>(D);
5887 if (RD->isCompleteDefinition())
5888 RewriteRecordBody(RD);
5897 /// Write_ProtocolExprReferencedMetadata - This routine writer out the
5898 /// protocol reference symbols in the for of:
5899 /// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5900 static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5901 ObjCProtocolDecl *PDecl,
5902 std::string &Result) {
5903 // Also output .objc_protorefs$B section and its meta-data.
5904 if (Context->getLangOpts().MicrosoftExt)
5905 Result += "static ";
5906 Result += "struct _protocol_t *";
5907 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5908 Result += PDecl->getNameAsString();
5910 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5914 void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5915 if (Diags.hasErrorOccurred())
5920 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
5921 // translation of function bodies were postponed until all class and
5922 // their extensions and implementations are seen. This is because, we
5923 // cannot build grouping structs for bitfields until they are all seen.
5924 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5925 HandleTopLevelSingleDecl(FDecl);
5928 // Here's a great place to add any extra declarations that may be needed.
5929 // Write out meta data for each @protocol(<expr>).
5930 for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls) {
5931 RewriteObjCProtocolMetaData(ProtDecl, Preamble);
5932 Write_ProtocolExprReferencedMetadata(Context, ProtDecl, Preamble);
5935 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
5937 if (ClassImplementation.size() || CategoryImplementation.size())
5938 RewriteImplementations();
5940 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5941 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
5942 // Write struct declaration for the class matching its ivar declarations.
5943 // Note that for modern abi, this is postponed until the end of TU
5944 // because class extensions and the implementation might declare their own
5946 RewriteInterfaceDecl(CDecl);
5949 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
5951 if (const RewriteBuffer *RewriteBuf =
5952 Rewrite.getRewriteBufferFor(MainFileID)) {
5953 //printf("Changed:\n");
5954 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
5956 llvm::errs() << "No changes\n";
5959 if (ClassImplementation.size() || CategoryImplementation.size() ||
5960 ProtocolExprDecls.size()) {
5961 // Rewrite Objective-c meta data*
5962 std::string ResultStr;
5963 RewriteMetaDataIntoBuffer(ResultStr);
5965 *OutFile << ResultStr;
5969 std::string ResultStr;
5970 WriteImageInfo(ResultStr);
5971 *OutFile << ResultStr;
5976 void RewriteModernObjC::Initialize(ASTContext &context) {
5977 InitializeCommon(context);
5979 Preamble += "#ifndef __OBJC2__\n";
5980 Preamble += "#define __OBJC2__\n";
5981 Preamble += "#endif\n";
5983 // declaring objc_selector outside the parameter list removes a silly
5984 // scope related warning...
5986 Preamble = "#pragma once\n";
5987 Preamble += "struct objc_selector; struct objc_class;\n";
5988 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
5989 Preamble += "\n\tstruct objc_object *superClass; ";
5990 // Add a constructor for creating temporary objects.
5991 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
5992 Preamble += ": object(o), superClass(s) {} ";
5993 Preamble += "\n};\n";
5995 if (LangOpts.MicrosoftExt) {
5996 // Define all sections using syntax that makes sense.
5997 // These are currently generated.
5998 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
5999 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
6000 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
6001 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6002 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
6003 // These are generated but not necessary for functionality.
6004 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
6005 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6006 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
6007 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
6009 // These need be generated for performance. Currently they are not,
6010 // using API calls instead.
6011 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6012 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6013 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6016 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6017 Preamble += "typedef struct objc_object Protocol;\n";
6018 Preamble += "#define _REWRITER_typedef_Protocol\n";
6019 Preamble += "#endif\n";
6020 if (LangOpts.MicrosoftExt) {
6021 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6022 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
6025 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
6027 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6028 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6029 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6030 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6031 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6033 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
6034 Preamble += "(const char *);\n";
6035 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6036 Preamble += "(struct objc_class *);\n";
6037 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
6038 Preamble += "(const char *);\n";
6039 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
6040 // @synchronized hooks.
6041 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6042 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
6043 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
6044 Preamble += "#ifdef _WIN64\n";
6045 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6046 Preamble += "#else\n";
6047 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6048 Preamble += "#endif\n";
6049 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6050 Preamble += "struct __objcFastEnumerationState {\n\t";
6051 Preamble += "unsigned long state;\n\t";
6052 Preamble += "void **itemsPtr;\n\t";
6053 Preamble += "unsigned long *mutationsPtr;\n\t";
6054 Preamble += "unsigned long extra[5];\n};\n";
6055 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6056 Preamble += "#define __FASTENUMERATIONSTATE\n";
6057 Preamble += "#endif\n";
6058 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6059 Preamble += "struct __NSConstantStringImpl {\n";
6060 Preamble += " int *isa;\n";
6061 Preamble += " int flags;\n";
6062 Preamble += " char *str;\n";
6063 Preamble += "#if _WIN64\n";
6064 Preamble += " long long length;\n";
6065 Preamble += "#else\n";
6066 Preamble += " long length;\n";
6067 Preamble += "#endif\n";
6069 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6070 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6071 Preamble += "#else\n";
6072 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6073 Preamble += "#endif\n";
6074 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6075 Preamble += "#endif\n";
6077 Preamble += "#ifndef BLOCK_IMPL\n";
6078 Preamble += "#define BLOCK_IMPL\n";
6079 Preamble += "struct __block_impl {\n";
6080 Preamble += " void *isa;\n";
6081 Preamble += " int Flags;\n";
6082 Preamble += " int Reserved;\n";
6083 Preamble += " void *FuncPtr;\n";
6085 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6086 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6087 Preamble += "extern \"C\" __declspec(dllexport) "
6088 "void _Block_object_assign(void *, const void *, const int);\n";
6089 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6090 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6091 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6092 Preamble += "#else\n";
6093 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6094 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6095 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6096 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6097 Preamble += "#endif\n";
6098 Preamble += "#endif\n";
6099 if (LangOpts.MicrosoftExt) {
6100 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6101 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6102 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6103 Preamble += "#define __attribute__(X)\n";
6104 Preamble += "#endif\n";
6105 Preamble += "#ifndef __weak\n";
6106 Preamble += "#define __weak\n";
6107 Preamble += "#endif\n";
6108 Preamble += "#ifndef __block\n";
6109 Preamble += "#define __block\n";
6110 Preamble += "#endif\n";
6113 Preamble += "#define __block\n";
6114 Preamble += "#define __weak\n";
6117 // Declarations required for modern objective-c array and dictionary literals.
6118 Preamble += "\n#include <stdarg.h>\n";
6119 Preamble += "struct __NSContainer_literal {\n";
6120 Preamble += " void * *arr;\n";
6121 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
6122 Preamble += "\tva_list marker;\n";
6123 Preamble += "\tva_start(marker, count);\n";
6124 Preamble += "\tarr = new void *[count];\n";
6125 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6126 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6127 Preamble += "\tva_end( marker );\n";
6128 Preamble += " };\n";
6129 Preamble += " ~__NSContainer_literal() {\n";
6130 Preamble += "\tdelete[] arr;\n";
6134 // Declaration required for implementation of @autoreleasepool statement.
6135 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6136 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6137 Preamble += "struct __AtAutoreleasePool {\n";
6138 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6139 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6140 Preamble += " void * atautoreleasepoolobj;\n";
6143 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6144 // as this avoids warning in any 64bit/32bit compilation model.
6145 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6148 /// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6150 void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6151 std::string &Result) {
6152 Result += "__OFFSETOFIVAR__(struct ";
6153 Result += ivar->getContainingInterface()->getNameAsString();
6154 if (LangOpts.MicrosoftExt)
6157 if (ivar->isBitField())
6158 ObjCIvarBitfieldGroupDecl(ivar, Result);
6160 Result += ivar->getNameAsString();
6164 /// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6165 /// struct _prop_t {
6166 /// const char *name;
6167 /// char *attributes;
6170 /// struct _prop_list_t {
6171 /// uint32_t entsize; // sizeof(struct _prop_t)
6172 /// uint32_t count_of_properties;
6173 /// struct _prop_t prop_list[count_of_properties];
6176 /// struct _protocol_t;
6178 /// struct _protocol_list_t {
6179 /// long protocol_count; // Note, this is 32/64 bit
6180 /// struct _protocol_t * protocol_list[protocol_count];
6183 /// struct _objc_method {
6185 /// const char *method_type;
6189 /// struct _method_list_t {
6190 /// uint32_t entsize; // sizeof(struct _objc_method)
6191 /// uint32_t method_count;
6192 /// struct _objc_method method_list[method_count];
6195 /// struct _protocol_t {
6197 /// const char *protocol_name;
6198 /// const struct _protocol_list_t * protocol_list; // super protocols
6199 /// const struct method_list_t *instance_methods;
6200 /// const struct method_list_t *class_methods;
6201 /// const struct method_list_t *optionalInstanceMethods;
6202 /// const struct method_list_t *optionalClassMethods;
6203 /// const struct _prop_list_t * properties;
6204 /// const uint32_t size; // sizeof(struct _protocol_t)
6205 /// const uint32_t flags; // = 0
6206 /// const char ** extendedMethodTypes;
6209 /// struct _ivar_t {
6210 /// unsigned long int *offset; // pointer to ivar offset location
6211 /// const char *name;
6212 /// const char *type;
6213 /// uint32_t alignment;
6217 /// struct _ivar_list_t {
6218 /// uint32 entsize; // sizeof(struct _ivar_t)
6220 /// struct _ivar_t list[count];
6223 /// struct _class_ro_t {
6225 /// uint32_t instanceStart;
6226 /// uint32_t instanceSize;
6227 /// uint32_t reserved; // only when building for 64bit targets
6228 /// const uint8_t *ivarLayout;
6229 /// const char *name;
6230 /// const struct _method_list_t *baseMethods;
6231 /// const struct _protocol_list_t *baseProtocols;
6232 /// const struct _ivar_list_t *ivars;
6233 /// const uint8_t *weakIvarLayout;
6234 /// const struct _prop_list_t *properties;
6237 /// struct _class_t {
6238 /// struct _class_t *isa;
6239 /// struct _class_t *superclass;
6242 /// struct _class_ro_t *ro;
6245 /// struct _category_t {
6246 /// const char *name;
6247 /// struct _class_t *cls;
6248 /// const struct _method_list_t *instance_methods;
6249 /// const struct _method_list_t *class_methods;
6250 /// const struct _protocol_list_t *protocols;
6251 /// const struct _prop_list_t *properties;
6254 /// MessageRefTy - LLVM for:
6255 /// struct _message_ref_t {
6260 /// SuperMessageRefTy - LLVM for:
6261 /// struct _super_message_ref_t {
6262 /// SUPER_IMP messenger;
6266 static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
6267 static bool meta_data_declared = false;
6268 if (meta_data_declared)
6271 Result += "\nstruct _prop_t {\n";
6272 Result += "\tconst char *name;\n";
6273 Result += "\tconst char *attributes;\n";
6276 Result += "\nstruct _protocol_t;\n";
6278 Result += "\nstruct _objc_method {\n";
6279 Result += "\tstruct objc_selector * _cmd;\n";
6280 Result += "\tconst char *method_type;\n";
6281 Result += "\tvoid *_imp;\n";
6284 Result += "\nstruct _protocol_t {\n";
6285 Result += "\tvoid * isa; // NULL\n";
6286 Result += "\tconst char *protocol_name;\n";
6287 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
6288 Result += "\tconst struct method_list_t *instance_methods;\n";
6289 Result += "\tconst struct method_list_t *class_methods;\n";
6290 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6291 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6292 Result += "\tconst struct _prop_list_t * properties;\n";
6293 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6294 Result += "\tconst unsigned int flags; // = 0\n";
6295 Result += "\tconst char ** extendedMethodTypes;\n";
6298 Result += "\nstruct _ivar_t {\n";
6299 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
6300 Result += "\tconst char *name;\n";
6301 Result += "\tconst char *type;\n";
6302 Result += "\tunsigned int alignment;\n";
6303 Result += "\tunsigned int size;\n";
6306 Result += "\nstruct _class_ro_t {\n";
6307 Result += "\tunsigned int flags;\n";
6308 Result += "\tunsigned int instanceStart;\n";
6309 Result += "\tunsigned int instanceSize;\n";
6310 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6311 if (Triple.getArch() == llvm::Triple::x86_64)
6312 Result += "\tunsigned int reserved;\n";
6313 Result += "\tconst unsigned char *ivarLayout;\n";
6314 Result += "\tconst char *name;\n";
6315 Result += "\tconst struct _method_list_t *baseMethods;\n";
6316 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6317 Result += "\tconst struct _ivar_list_t *ivars;\n";
6318 Result += "\tconst unsigned char *weakIvarLayout;\n";
6319 Result += "\tconst struct _prop_list_t *properties;\n";
6322 Result += "\nstruct _class_t {\n";
6323 Result += "\tstruct _class_t *isa;\n";
6324 Result += "\tstruct _class_t *superclass;\n";
6325 Result += "\tvoid *cache;\n";
6326 Result += "\tvoid *vtable;\n";
6327 Result += "\tstruct _class_ro_t *ro;\n";
6330 Result += "\nstruct _category_t {\n";
6331 Result += "\tconst char *name;\n";
6332 Result += "\tstruct _class_t *cls;\n";
6333 Result += "\tconst struct _method_list_t *instance_methods;\n";
6334 Result += "\tconst struct _method_list_t *class_methods;\n";
6335 Result += "\tconst struct _protocol_list_t *protocols;\n";
6336 Result += "\tconst struct _prop_list_t *properties;\n";
6339 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
6340 Result += "#pragma warning(disable:4273)\n";
6341 meta_data_declared = true;
6344 static void Write_protocol_list_t_TypeDecl(std::string &Result,
6345 long super_protocol_count) {
6346 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6347 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6348 Result += "\tstruct _protocol_t *super_protocols[";
6349 Result += utostr(super_protocol_count); Result += "];\n";
6353 static void Write_method_list_t_TypeDecl(std::string &Result,
6354 unsigned int method_count) {
6355 Result += "struct /*_method_list_t*/"; Result += " {\n";
6356 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6357 Result += "\tunsigned int method_count;\n";
6358 Result += "\tstruct _objc_method method_list[";
6359 Result += utostr(method_count); Result += "];\n";
6363 static void Write__prop_list_t_TypeDecl(std::string &Result,
6364 unsigned int property_count) {
6365 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6366 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6367 Result += "\tunsigned int count_of_properties;\n";
6368 Result += "\tstruct _prop_t prop_list[";
6369 Result += utostr(property_count); Result += "];\n";
6373 static void Write__ivar_list_t_TypeDecl(std::string &Result,
6374 unsigned int ivar_count) {
6375 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6376 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6377 Result += "\tunsigned int count;\n";
6378 Result += "\tstruct _ivar_t ivar_list[";
6379 Result += utostr(ivar_count); Result += "];\n";
6383 static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6384 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6386 StringRef ProtocolName) {
6387 if (SuperProtocols.size() > 0) {
6388 Result += "\nstatic ";
6389 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6390 Result += " "; Result += VarName;
6391 Result += ProtocolName;
6392 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6393 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6394 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6395 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6396 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6397 Result += SuperPD->getNameAsString();
6406 static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6407 ASTContext *Context, std::string &Result,
6408 ArrayRef<ObjCMethodDecl *> Methods,
6410 StringRef TopLevelDeclName,
6412 if (Methods.size() > 0) {
6413 Result += "\nstatic ";
6414 Write_method_list_t_TypeDecl(Result, Methods.size());
6415 Result += " "; Result += VarName;
6416 Result += TopLevelDeclName;
6417 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6418 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6419 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6420 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6421 ObjCMethodDecl *MD = Methods[i];
6423 Result += "\t{{(struct objc_selector *)\"";
6425 Result += "\t{(struct objc_selector *)\"";
6426 Result += (MD)->getSelector().getAsString(); Result += "\"";
6428 std::string MethodTypeString;
6429 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6430 Result += "\""; Result += MethodTypeString; Result += "\"";
6435 Result += "(void *)";
6436 Result += RewriteObj.MethodInternalNames[MD];
6447 static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
6448 ASTContext *Context, std::string &Result,
6449 ArrayRef<ObjCPropertyDecl *> Properties,
6450 const Decl *Container,
6452 StringRef ProtocolName) {
6453 if (Properties.size() > 0) {
6454 Result += "\nstatic ";
6455 Write__prop_list_t_TypeDecl(Result, Properties.size());
6456 Result += " "; Result += VarName;
6457 Result += ProtocolName;
6458 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6459 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6460 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6461 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6462 ObjCPropertyDecl *PropDecl = Properties[i];
6467 Result += PropDecl->getName(); Result += "\",";
6468 std::string PropertyTypeString, QuotePropertyTypeString;
6469 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6470 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6471 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6482 enum MetaDataDlags {
6486 OBJC2_CLS_HIDDEN = 0x10,
6487 CLS_EXCEPTION = 0x20,
6489 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6490 CLS_HAS_IVAR_RELEASER = 0x40,
6491 /// class was compiled with -fobjc-arr
6492 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6495 static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6497 const std::string &InstanceStart,
6498 const std::string &InstanceSize,
6499 ArrayRef<ObjCMethodDecl *>baseMethods,
6500 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6501 ArrayRef<ObjCIvarDecl *>ivars,
6502 ArrayRef<ObjCPropertyDecl *>Properties,
6504 StringRef ClassName) {
6505 Result += "\nstatic struct _class_ro_t ";
6506 Result += VarName; Result += ClassName;
6507 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6509 Result += llvm::utostr(flags); Result += ", ";
6510 Result += InstanceStart; Result += ", ";
6511 Result += InstanceSize; Result += ", \n";
6513 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6514 if (Triple.getArch() == llvm::Triple::x86_64)
6515 // uint32_t const reserved; // only when building for 64bit targets
6516 Result += "(unsigned int)0, \n\t";
6517 // const uint8_t * const ivarLayout;
6518 Result += "0, \n\t";
6519 Result += "\""; Result += ClassName; Result += "\",\n\t";
6520 bool metaclass = ((flags & CLS_META) != 0);
6521 if (baseMethods.size() > 0) {
6522 Result += "(const struct _method_list_t *)&";
6524 Result += "_OBJC_$_CLASS_METHODS_";
6526 Result += "_OBJC_$_INSTANCE_METHODS_";
6527 Result += ClassName;
6531 Result += "0, \n\t";
6533 if (!metaclass && baseProtocols.size() > 0) {
6534 Result += "(const struct _objc_protocol_list *)&";
6535 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6539 Result += "0, \n\t";
6541 if (!metaclass && ivars.size() > 0) {
6542 Result += "(const struct _ivar_list_t *)&";
6543 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6547 Result += "0, \n\t";
6550 Result += "0, \n\t";
6551 if (!metaclass && Properties.size() > 0) {
6552 Result += "(const struct _prop_list_t *)&";
6553 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
6562 static void Write_class_t(ASTContext *Context, std::string &Result,
6564 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6565 bool rootClass = (!CDecl->getSuperClass());
6566 const ObjCInterfaceDecl *RootClass = CDecl;
6569 // Find the Root class
6570 RootClass = CDecl->getSuperClass();
6571 while (RootClass->getSuperClass()) {
6572 RootClass = RootClass->getSuperClass();
6576 if (metaclass && rootClass) {
6577 // Need to handle a case of use of forward declaration.
6579 Result += "extern \"C\" ";
6580 if (CDecl->getImplementation())
6581 Result += "__declspec(dllexport) ";
6583 Result += "__declspec(dllimport) ";
6585 Result += "struct _class_t OBJC_CLASS_$_";
6586 Result += CDecl->getNameAsString();
6589 // Also, for possibility of 'super' metadata class not having been defined yet.
6591 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
6593 Result += "extern \"C\" ";
6594 if (SuperClass->getImplementation())
6595 Result += "__declspec(dllexport) ";
6597 Result += "__declspec(dllimport) ";
6599 Result += "struct _class_t ";
6601 Result += SuperClass->getNameAsString();
6604 if (metaclass && RootClass != SuperClass) {
6605 Result += "extern \"C\" ";
6606 if (RootClass->getImplementation())
6607 Result += "__declspec(dllexport) ";
6609 Result += "__declspec(dllimport) ";
6611 Result += "struct _class_t ";
6613 Result += RootClass->getNameAsString();
6618 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6619 Result += VarName; Result += CDecl->getNameAsString();
6620 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6624 Result += "0, // &"; Result += VarName;
6625 Result += RootClass->getNameAsString();
6627 Result += "0, // &"; Result += VarName;
6628 Result += CDecl->getSuperClass()->getNameAsString();
6632 Result += "0, // &"; Result += VarName;
6633 Result += CDecl->getNameAsString();
6635 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6640 Result += "0, // &OBJC_METACLASS_$_";
6641 Result += CDecl->getNameAsString();
6644 Result += "0, // &"; Result += VarName;
6645 Result += CDecl->getSuperClass()->getNameAsString();
6651 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6652 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6654 Result += "&_OBJC_METACLASS_RO_$_";
6656 Result += "&_OBJC_CLASS_RO_$_";
6657 Result += CDecl->getNameAsString();
6658 Result += ",\n};\n";
6660 // Add static function to initialize some of the meta-data fields.
6661 // avoid doing it twice.
6665 const ObjCInterfaceDecl *SuperClass =
6666 rootClass ? CDecl : CDecl->getSuperClass();
6668 Result += "static void OBJC_CLASS_SETUP_$_";
6669 Result += CDecl->getNameAsString();
6670 Result += "(void ) {\n";
6671 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6672 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6673 Result += RootClass->getNameAsString(); Result += ";\n";
6675 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6676 Result += ".superclass = ";
6678 Result += "&OBJC_CLASS_$_";
6680 Result += "&OBJC_METACLASS_$_";
6682 Result += SuperClass->getNameAsString(); Result += ";\n";
6684 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6685 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6687 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6688 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6689 Result += CDecl->getNameAsString(); Result += ";\n";
6692 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6693 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6694 Result += SuperClass->getNameAsString(); Result += ";\n";
6697 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6698 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6702 static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6703 std::string &Result,
6704 ObjCCategoryDecl *CatDecl,
6705 ObjCInterfaceDecl *ClassDecl,
6706 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6707 ArrayRef<ObjCMethodDecl *> ClassMethods,
6708 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6709 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
6710 StringRef CatName = CatDecl->getName();
6711 StringRef ClassName = ClassDecl->getName();
6712 // must declare an extern class object in case this class is not implemented
6715 Result += "extern \"C\" ";
6716 if (ClassDecl->getImplementation())
6717 Result += "__declspec(dllexport) ";
6719 Result += "__declspec(dllimport) ";
6721 Result += "struct _class_t ";
6722 Result += "OBJC_CLASS_$_"; Result += ClassName;
6725 Result += "\nstatic struct _category_t ";
6726 Result += "_OBJC_$_CATEGORY_";
6727 Result += ClassName; Result += "_$_"; Result += CatName;
6728 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6730 Result += "\t\""; Result += ClassName; Result += "\",\n";
6731 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
6733 if (InstanceMethods.size() > 0) {
6734 Result += "\t(const struct _method_list_t *)&";
6735 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6736 Result += ClassName; Result += "_$_"; Result += CatName;
6742 if (ClassMethods.size() > 0) {
6743 Result += "\t(const struct _method_list_t *)&";
6744 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6745 Result += ClassName; Result += "_$_"; Result += CatName;
6751 if (RefedProtocols.size() > 0) {
6752 Result += "\t(const struct _protocol_list_t *)&";
6753 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6754 Result += ClassName; Result += "_$_"; Result += CatName;
6760 if (ClassProperties.size() > 0) {
6761 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6762 Result += ClassName; Result += "_$_"; Result += CatName;
6770 // Add static function to initialize the class pointer in the category structure.
6771 Result += "static void OBJC_CATEGORY_SETUP_$_";
6772 Result += ClassDecl->getNameAsString();
6775 Result += "(void ) {\n";
6776 Result += "\t_OBJC_$_CATEGORY_";
6777 Result += ClassDecl->getNameAsString();
6780 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6784 static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6785 ASTContext *Context, std::string &Result,
6786 ArrayRef<ObjCMethodDecl *> Methods,
6788 StringRef ProtocolName) {
6789 if (Methods.size() == 0)
6792 Result += "\nstatic const char *";
6793 Result += VarName; Result += ProtocolName;
6794 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6796 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6797 ObjCMethodDecl *MD = Methods[i];
6798 std::string MethodTypeString, QuoteMethodTypeString;
6799 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6800 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6801 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6810 static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6811 ASTContext *Context,
6812 std::string &Result,
6813 ArrayRef<ObjCIvarDecl *> Ivars,
6814 ObjCInterfaceDecl *CDecl) {
6815 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6816 // this is what happens:
6818 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6819 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6820 Class->getVisibility() == HiddenVisibility)
6821 Visibility shoud be: HiddenVisibility;
6823 Visibility shoud be: DefaultVisibility;
6827 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6828 ObjCIvarDecl *IvarDecl = Ivars[i];
6829 if (Context->getLangOpts().MicrosoftExt)
6830 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6832 if (!Context->getLangOpts().MicrosoftExt ||
6833 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
6834 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
6835 Result += "extern \"C\" unsigned long int ";
6837 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
6838 if (Ivars[i]->isBitField())
6839 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6841 WriteInternalIvarName(CDecl, IvarDecl, Result);
6842 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6844 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6846 if (Ivars[i]->isBitField()) {
6847 // skip over rest of the ivar bitfields.
6848 SKIP_BITFIELDS(i , e, Ivars);
6853 static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6854 ASTContext *Context, std::string &Result,
6855 ArrayRef<ObjCIvarDecl *> OriginalIvars,
6857 ObjCInterfaceDecl *CDecl) {
6858 if (OriginalIvars.size() > 0) {
6859 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6860 SmallVector<ObjCIvarDecl *, 8> Ivars;
6861 // strip off all but the first ivar bitfield from each group of ivars.
6862 // Such ivars in the ivar list table will be replaced by their grouping struct
6864 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6865 if (OriginalIvars[i]->isBitField()) {
6866 Ivars.push_back(OriginalIvars[i]);
6867 // skip over rest of the ivar bitfields.
6868 SKIP_BITFIELDS(i , e, OriginalIvars);
6871 Ivars.push_back(OriginalIvars[i]);
6874 Result += "\nstatic ";
6875 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6876 Result += " "; Result += VarName;
6877 Result += CDecl->getNameAsString();
6878 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6879 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6880 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6881 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6882 ObjCIvarDecl *IvarDecl = Ivars[i];
6887 Result += "(unsigned long int *)&";
6888 if (Ivars[i]->isBitField())
6889 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6891 WriteInternalIvarName(CDecl, IvarDecl, Result);
6895 if (Ivars[i]->isBitField())
6896 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6898 Result += IvarDecl->getName();
6901 QualType IVQT = IvarDecl->getType();
6902 if (IvarDecl->isBitField())
6903 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6905 std::string IvarTypeString, QuoteIvarTypeString;
6906 Context->getObjCEncodingForType(IVQT, IvarTypeString,
6908 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6909 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6911 // FIXME. this alignment represents the host alignment and need be changed to
6912 // represent the target alignment.
6913 unsigned Align = Context->getTypeAlign(IVQT)/8;
6914 Align = llvm::Log2_32(Align);
6915 Result += llvm::utostr(Align); Result += ", ";
6916 CharUnits Size = Context->getTypeSizeInChars(IVQT);
6917 Result += llvm::utostr(Size.getQuantity());
6927 /// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
6928 void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6929 std::string &Result) {
6931 // Do not synthesize the protocol more than once.
6932 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6934 WriteModernMetadataDeclarations(Context, Result);
6936 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6938 // Must write out all protocol definitions in current qualifier list,
6939 // and in their nested qualifiers before writing out current definition.
6940 for (auto *I : PDecl->protocols())
6941 RewriteObjCProtocolMetaData(I, Result);
6943 // Construct method lists.
6944 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6945 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
6946 for (auto *MD : PDecl->instance_methods()) {
6947 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6948 OptInstanceMethods.push_back(MD);
6950 InstanceMethods.push_back(MD);
6954 for (auto *MD : PDecl->class_methods()) {
6955 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
6956 OptClassMethods.push_back(MD);
6958 ClassMethods.push_back(MD);
6961 std::vector<ObjCMethodDecl *> AllMethods;
6962 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
6963 AllMethods.push_back(InstanceMethods[i]);
6964 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
6965 AllMethods.push_back(ClassMethods[i]);
6966 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
6967 AllMethods.push_back(OptInstanceMethods[i]);
6968 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
6969 AllMethods.push_back(OptClassMethods[i]);
6971 Write__extendedMethodTypes_initializer(*this, Context, Result,
6973 "_OBJC_PROTOCOL_METHOD_TYPES_",
6974 PDecl->getNameAsString());
6975 // Protocol's super protocol list
6976 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
6977 Write_protocol_list_initializer(Context, Result, SuperProtocols,
6978 "_OBJC_PROTOCOL_REFS_",
6979 PDecl->getNameAsString());
6981 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
6982 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
6983 PDecl->getNameAsString(), false);
6985 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
6986 "_OBJC_PROTOCOL_CLASS_METHODS_",
6987 PDecl->getNameAsString(), false);
6989 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
6990 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
6991 PDecl->getNameAsString(), false);
6993 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
6994 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
6995 PDecl->getNameAsString(), false);
6997 // Protocol's property metadata.
6998 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
6999 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
7000 /* Container */nullptr,
7001 "_OBJC_PROTOCOL_PROPERTIES_",
7002 PDecl->getNameAsString());
7004 // Writer out root metadata for current protocol: struct _protocol_t
7006 if (LangOpts.MicrosoftExt)
7007 Result += "static ";
7008 Result += "struct _protocol_t _OBJC_PROTOCOL_";
7009 Result += PDecl->getNameAsString();
7010 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7011 Result += "\t0,\n"; // id is; is null
7012 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
7013 if (SuperProtocols.size() > 0) {
7014 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7015 Result += PDecl->getNameAsString(); Result += ",\n";
7019 if (InstanceMethods.size() > 0) {
7020 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7021 Result += PDecl->getNameAsString(); Result += ",\n";
7026 if (ClassMethods.size() > 0) {
7027 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7028 Result += PDecl->getNameAsString(); Result += ",\n";
7033 if (OptInstanceMethods.size() > 0) {
7034 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7035 Result += PDecl->getNameAsString(); Result += ",\n";
7040 if (OptClassMethods.size() > 0) {
7041 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7042 Result += PDecl->getNameAsString(); Result += ",\n";
7047 if (ProtocolProperties.size() > 0) {
7048 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7049 Result += PDecl->getNameAsString(); Result += ",\n";
7054 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7057 if (AllMethods.size() > 0) {
7058 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7059 Result += PDecl->getNameAsString();
7063 Result += "\t0\n};\n";
7065 if (LangOpts.MicrosoftExt)
7066 Result += "static ";
7067 Result += "struct _protocol_t *";
7068 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7069 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7072 // Mark this protocol as having been generated.
7073 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()).second)
7074 llvm_unreachable("protocol already synthesized");
7078 void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7079 const ObjCList<ObjCProtocolDecl> &Protocols,
7080 StringRef prefix, StringRef ClassName,
7081 std::string &Result) {
7082 if (Protocols.empty()) return;
7084 for (unsigned i = 0; i != Protocols.size(); i++)
7085 RewriteObjCProtocolMetaData(Protocols[i], Result);
7087 // Output the top lovel protocol meta-data for the class.
7088 /* struct _objc_protocol_list {
7089 struct _objc_protocol_list *next;
7091 struct _objc_protocol *class_protocols[];
7095 if (LangOpts.MicrosoftExt)
7096 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7097 Result += "static struct {\n";
7098 Result += "\tstruct _objc_protocol_list *next;\n";
7099 Result += "\tint protocol_count;\n";
7100 Result += "\tstruct _objc_protocol *class_protocols[";
7101 Result += utostr(Protocols.size());
7102 Result += "];\n} _OBJC_";
7104 Result += "_PROTOCOLS_";
7105 Result += ClassName;
7106 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7108 Result += utostr(Protocols.size());
7111 Result += "\t,{&_OBJC_PROTOCOL_";
7112 Result += Protocols[0]->getNameAsString();
7115 for (unsigned i = 1; i != Protocols.size(); i++) {
7116 Result += "\t ,&_OBJC_PROTOCOL_";
7117 Result += Protocols[i]->getNameAsString();
7120 Result += "\t }\n};\n";
7123 /// hasObjCExceptionAttribute - Return true if this class or any super
7124 /// class has the __objc_exception__ attribute.
7125 /// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7126 static bool hasObjCExceptionAttribute(ASTContext &Context,
7127 const ObjCInterfaceDecl *OID) {
7128 if (OID->hasAttr<ObjCExceptionAttr>())
7130 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7131 return hasObjCExceptionAttribute(Context, Super);
7135 void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7136 std::string &Result) {
7137 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7139 // Explicitly declared @interface's are already synthesized.
7140 if (CDecl->isImplicitInterfaceDecl())
7142 "Legacy implicit interface rewriting not supported in moder abi");
7144 WriteModernMetadataDeclarations(Context, Result);
7145 SmallVector<ObjCIvarDecl *, 8> IVars;
7147 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7148 IVD; IVD = IVD->getNextIvar()) {
7149 // Ignore unnamed bit-fields.
7150 if (!IVD->getDeclName())
7152 IVars.push_back(IVD);
7155 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
7156 "_OBJC_$_INSTANCE_VARIABLES_",
7159 // Build _objc_method_list for class's instance methods if needed
7160 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7162 // If any of our property implementations have associated getters or
7163 // setters, produce metadata for them as well.
7164 for (const auto *Prop : IDecl->property_impls()) {
7165 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7167 if (!Prop->getPropertyIvarDecl())
7169 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7172 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7173 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
7174 InstanceMethods.push_back(Getter);
7175 if (PD->isReadOnly())
7177 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7178 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
7179 InstanceMethods.push_back(Setter);
7182 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7183 "_OBJC_$_INSTANCE_METHODS_",
7184 IDecl->getNameAsString(), true);
7186 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7188 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7189 "_OBJC_$_CLASS_METHODS_",
7190 IDecl->getNameAsString(), true);
7192 // Protocols referenced in class declaration?
7193 // Protocol's super protocol list
7194 std::vector<ObjCProtocolDecl *> RefedProtocols;
7195 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7196 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7197 E = Protocols.end();
7199 RefedProtocols.push_back(*I);
7200 // Must write out all protocol definitions in current qualifier list,
7201 // and in their nested qualifiers before writing out current definition.
7202 RewriteObjCProtocolMetaData(*I, Result);
7205 Write_protocol_list_initializer(Context, Result,
7207 "_OBJC_CLASS_PROTOCOLS_$_",
7208 IDecl->getNameAsString());
7210 // Protocol's property metadata.
7211 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
7212 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7213 /* Container */IDecl,
7214 "_OBJC_$_PROP_LIST_",
7215 CDecl->getNameAsString());
7218 // Data for initializing _class_ro_t metaclass meta-data
7219 uint32_t flags = CLS_META;
7220 std::string InstanceSize;
7221 std::string InstanceStart;
7224 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7226 flags |= OBJC2_CLS_HIDDEN;
7228 if (!CDecl->getSuperClass())
7231 InstanceSize = "sizeof(struct _class_t)";
7232 InstanceStart = InstanceSize;
7233 Write__class_ro_t_initializer(Context, Result, flags,
7234 InstanceStart, InstanceSize,
7239 "_OBJC_METACLASS_RO_$_",
7240 CDecl->getNameAsString());
7242 // Data for initializing _class_ro_t meta-data
7245 flags |= OBJC2_CLS_HIDDEN;
7247 if (hasObjCExceptionAttribute(*Context, CDecl))
7248 flags |= CLS_EXCEPTION;
7250 if (!CDecl->getSuperClass())
7254 InstanceSize.clear();
7255 InstanceStart.clear();
7256 if (!ObjCSynthesizedStructs.count(CDecl)) {
7258 InstanceStart = "0";
7261 InstanceSize = "sizeof(struct ";
7262 InstanceSize += CDecl->getNameAsString();
7263 InstanceSize += "_IMPL)";
7265 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7267 RewriteIvarOffsetComputation(IVD, InstanceStart);
7270 InstanceStart = InstanceSize;
7272 Write__class_ro_t_initializer(Context, Result, flags,
7273 InstanceStart, InstanceSize,
7278 "_OBJC_CLASS_RO_$_",
7279 CDecl->getNameAsString());
7281 Write_class_t(Context, Result,
7282 "OBJC_METACLASS_$_",
7283 CDecl, /*metaclass*/true);
7285 Write_class_t(Context, Result,
7287 CDecl, /*metaclass*/false);
7289 if (ImplementationIsNonLazy(IDecl))
7290 DefinedNonLazyClasses.push_back(CDecl);
7294 void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7295 int ClsDefCount = ClassImplementation.size();
7298 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7299 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7300 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7301 for (int i = 0; i < ClsDefCount; i++) {
7302 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7303 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7304 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7305 Result += CDecl->getName(); Result += ",\n";
7310 void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7311 int ClsDefCount = ClassImplementation.size();
7312 int CatDefCount = CategoryImplementation.size();
7314 // For each implemented class, write out all its meta data.
7315 for (int i = 0; i < ClsDefCount; i++)
7316 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7318 RewriteClassSetupInitHook(Result);
7320 // For each implemented category, write out all its meta data.
7321 for (int i = 0; i < CatDefCount; i++)
7322 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7324 RewriteCategorySetupInitHook(Result);
7326 if (ClsDefCount > 0) {
7327 if (LangOpts.MicrosoftExt)
7328 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
7329 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7330 Result += llvm::utostr(ClsDefCount); Result += "]";
7332 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7333 "regular,no_dead_strip\")))= {\n";
7334 for (int i = 0; i < ClsDefCount; i++) {
7335 Result += "\t&OBJC_CLASS_$_";
7336 Result += ClassImplementation[i]->getNameAsString();
7341 if (!DefinedNonLazyClasses.empty()) {
7342 if (LangOpts.MicrosoftExt)
7343 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7344 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7345 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7346 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7353 if (CatDefCount > 0) {
7354 if (LangOpts.MicrosoftExt)
7355 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
7356 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7357 Result += llvm::utostr(CatDefCount); Result += "]";
7359 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7360 "regular,no_dead_strip\")))= {\n";
7361 for (int i = 0; i < CatDefCount; i++) {
7362 Result += "\t&_OBJC_$_CATEGORY_";
7364 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7366 Result += CategoryImplementation[i]->getNameAsString();
7372 if (!DefinedNonLazyCategories.empty()) {
7373 if (LangOpts.MicrosoftExt)
7374 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7375 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7376 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7377 Result += "\t&_OBJC_$_CATEGORY_";
7379 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7381 Result += DefinedNonLazyCategories[i]->getNameAsString();
7388 void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7389 if (LangOpts.MicrosoftExt)
7390 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7392 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7393 // version 0, ObjCABI is 2
7394 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
7397 /// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7399 void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7400 std::string &Result) {
7401 WriteModernMetadataDeclarations(Context, Result);
7402 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7403 // Find category declaration for this implementation.
7404 ObjCCategoryDecl *CDecl
7405 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
7407 std::string FullCategoryName = ClassDecl->getNameAsString();
7408 FullCategoryName += "_$_";
7409 FullCategoryName += CDecl->getNameAsString();
7411 // Build _objc_method_list for class's instance methods if needed
7412 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
7414 // If any of our property implementations have associated getters or
7415 // setters, produce metadata for them as well.
7416 for (const auto *Prop : IDecl->property_impls()) {
7417 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
7419 if (!Prop->getPropertyIvarDecl())
7421 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
7424 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7425 InstanceMethods.push_back(Getter);
7426 if (PD->isReadOnly())
7428 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7429 InstanceMethods.push_back(Setter);
7432 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7433 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7434 FullCategoryName, true);
7436 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
7438 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7439 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7440 FullCategoryName, true);
7442 // Protocols referenced in class declaration?
7443 // Protocol's super protocol list
7444 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7445 for (auto *I : CDecl->protocols())
7446 // Must write out all protocol definitions in current qualifier list,
7447 // and in their nested qualifiers before writing out current definition.
7448 RewriteObjCProtocolMetaData(I, Result);
7450 Write_protocol_list_initializer(Context, Result,
7452 "_OBJC_CATEGORY_PROTOCOLS_$_",
7455 // Protocol's property metadata.
7456 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
7457 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
7458 /* Container */IDecl,
7459 "_OBJC_$_PROP_LIST_",
7462 Write_category_t(*this, Context, Result,
7470 // Determine if this category is also "non-lazy".
7471 if (ImplementationIsNonLazy(IDecl))
7472 DefinedNonLazyCategories.push_back(CDecl);
7476 void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7477 int CatDefCount = CategoryImplementation.size();
7480 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7481 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7482 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7483 for (int i = 0; i < CatDefCount; i++) {
7484 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7485 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7486 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7487 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7488 Result += ClassDecl->getName();
7490 Result += CatDecl->getName();
7496 // RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7498 template<typename MethodIterator>
7499 void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7500 MethodIterator MethodEnd,
7501 bool IsInstanceMethod,
7503 StringRef ClassName,
7504 std::string &Result) {
7505 if (MethodBegin == MethodEnd) return;
7507 if (!objc_impl_method) {
7508 /* struct _objc_method {
7514 Result += "\nstruct _objc_method {\n";
7515 Result += "\tSEL _cmd;\n";
7516 Result += "\tchar *method_types;\n";
7517 Result += "\tvoid *_imp;\n";
7520 objc_impl_method = true;
7523 // Build _objc_method_list for class's methods if needed
7526 struct _objc_method_list *next_method;
7528 struct _objc_method method_list[];
7531 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
7533 if (LangOpts.MicrosoftExt) {
7534 if (IsInstanceMethod)
7535 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7537 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7539 Result += "static struct {\n";
7540 Result += "\tstruct _objc_method_list *next_method;\n";
7541 Result += "\tint method_count;\n";
7542 Result += "\tstruct _objc_method method_list[";
7543 Result += utostr(NumMethods);
7544 Result += "];\n} _OBJC_";
7546 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7547 Result += "_METHODS_";
7548 Result += ClassName;
7549 Result += " __attribute__ ((used, section (\"__OBJC, __";
7550 Result += IsInstanceMethod ? "inst" : "cls";
7551 Result += "_meth\")))= ";
7552 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7554 Result += "\t,{{(SEL)\"";
7555 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7556 std::string MethodTypeString;
7557 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7559 Result += MethodTypeString;
7560 Result += "\", (void *)";
7561 Result += MethodInternalNames[*MethodBegin];
7563 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7564 Result += "\t ,{(SEL)\"";
7565 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7566 std::string MethodTypeString;
7567 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7569 Result += MethodTypeString;
7570 Result += "\", (void *)";
7571 Result += MethodInternalNames[*MethodBegin];
7574 Result += "\t }\n};\n";
7577 Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7578 SourceRange OldRange = IV->getSourceRange();
7579 Expr *BaseExpr = IV->getBase();
7581 // Rewrite the base, but without actually doing replaces.
7583 DisableReplaceStmtScope S(*this);
7584 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7585 IV->setBase(BaseExpr);
7588 ObjCIvarDecl *D = IV->getDecl();
7590 Expr *Replacement = IV;
7592 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7593 const ObjCInterfaceType *iFaceDecl =
7594 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
7595 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7596 // lookup which class implements the instance variable.
7597 ObjCInterfaceDecl *clsDeclared = nullptr;
7598 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7600 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7602 // Build name of symbol holding ivar offset.
7603 std::string IvarOffsetName;
7604 if (D->isBitField())
7605 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7607 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
7609 ReferencedIvars[clsDeclared].insert(D);
7611 // cast offset to "char *".
7612 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7613 Context->getPointerType(Context->CharTy),
7616 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7617 SourceLocation(), &Context->Idents.get(IvarOffsetName),
7618 Context->UnsignedLongTy, nullptr,
7620 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7621 Context->UnsignedLongTy, VK_LValue,
7623 BinaryOperator *addExpr =
7624 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7625 Context->getPointerType(Context->CharTy),
7626 VK_RValue, OK_Ordinary, SourceLocation(), false);
7627 // Don't forget the parens to enforce the proper binding.
7628 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7631 QualType IvarT = D->getType();
7632 if (D->isBitField())
7633 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
7635 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
7636 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
7637 RD = RD->getDefinition();
7638 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
7639 // decltype(((Foo_IMPL*)0)->bar) *
7640 ObjCContainerDecl *CDecl =
7641 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7642 // ivar in class extensions requires special treatment.
7643 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7644 CDecl = CatDecl->getClassInterface();
7645 std::string RecName = CDecl->getName();
7647 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7648 SourceLocation(), SourceLocation(),
7649 &Context->Idents.get(RecName.c_str()));
7650 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7651 unsigned UnsignedIntSize =
7652 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7653 Expr *Zero = IntegerLiteral::Create(*Context,
7654 llvm::APInt(UnsignedIntSize, 0),
7655 Context->UnsignedIntTy, SourceLocation());
7656 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7657 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7659 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7661 &Context->Idents.get(D->getNameAsString()),
7663 /*BitWidth=*/nullptr,
7664 /*Mutable=*/true, ICIS_NoInit);
7665 MemberExpr *ME = new (Context)
7666 MemberExpr(PE, true, SourceLocation(), FD, SourceLocation(),
7667 FD->getType(), VK_LValue, OK_Ordinary);
7668 IvarT = Context->getDecltypeType(ME, ME->getType());
7671 convertObjCTypeToCStyleType(IvarT);
7672 QualType castT = Context->getPointerType(IvarT);
7674 castExpr = NoTypeInfoCStyleCastExpr(Context,
7680 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
7681 VK_LValue, OK_Ordinary,
7683 PE = new (Context) ParenExpr(OldRange.getBegin(),
7687 if (D->isBitField()) {
7688 FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
7690 &Context->Idents.get(D->getNameAsString()),
7691 D->getType(), nullptr,
7692 /*BitWidth=*/D->getBitWidth(),
7693 /*Mutable=*/true, ICIS_NoInit);
7694 MemberExpr *ME = new (Context)
7695 MemberExpr(PE, /*isArrow*/ false, SourceLocation(), FD,
7696 SourceLocation(), FD->getType(), VK_LValue, OK_Ordinary);
7704 ReplaceStmtWithRange(IV, Replacement, OldRange);