CGCall.cpp 137 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587
  1. //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
  2. //
  3. // The LLVM Compiler Infrastructure
  4. //
  5. // This file is distributed under the University of Illinois Open Source
  6. // License. See LICENSE.TXT for details.
  7. //
  8. //===----------------------------------------------------------------------===//
  9. //
  10. // These classes wrap the information about a call or function
  11. // definition used to handle ABI compliancy.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #include "CGCall.h"
  15. #include "ABIInfo.h"
  16. #include "CGCXXABI.h"
  17. #include "CodeGenFunction.h"
  18. #include "CodeGenModule.h"
  19. #include "TargetInfo.h"
  20. #include "clang/AST/Decl.h"
  21. #include "clang/AST/DeclCXX.h"
  22. #include "clang/AST/DeclObjC.h"
  23. #include "clang/Basic/TargetBuiltins.h"
  24. #include "clang/Basic/TargetInfo.h"
  25. #include "clang/CodeGen/CGFunctionInfo.h"
  26. #include "clang/Frontend/CodeGenOptions.h"
  27. #include "llvm/ADT/StringExtras.h"
  28. #include "llvm/IR/Attributes.h"
  29. #include "llvm/IR/CallSite.h"
  30. #include "llvm/IR/DataLayout.h"
  31. #include "llvm/IR/InlineAsm.h"
  32. #include "llvm/IR/Intrinsics.h"
  33. #include "llvm/IR/IntrinsicInst.h"
  34. #include "llvm/Transforms/Utils/Local.h"
  35. using namespace clang;
  36. using namespace CodeGen;
  37. /***/
  38. static unsigned ClangCallConvToLLVMCallConv(CallingConv CC) {
  39. switch (CC) {
  40. default: return llvm::CallingConv::C;
  41. case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
  42. case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
  43. case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
  44. case CC_X86_64Win64: return llvm::CallingConv::X86_64_Win64;
  45. case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
  46. case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
  47. case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  48. case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
  49. // TODO: Add support for __pascal to LLVM.
  50. case CC_X86Pascal: return llvm::CallingConv::C;
  51. // TODO: Add support for __vectorcall to LLVM.
  52. case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
  53. case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
  54. case CC_SpirKernel: return llvm::CallingConv::SPIR_KERNEL;
  55. }
  56. }
  57. /// Derives the 'this' type for codegen purposes, i.e. ignoring method
  58. /// qualification.
  59. /// FIXME: address space qualification?
  60. static CanQualType GetThisType(ASTContext &Context, const CXXRecordDecl *RD) {
  61. QualType RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
  62. return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
  63. }
  64. /// Returns the canonical formal type of the given C++ method.
  65. static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
  66. return MD->getType()->getCanonicalTypeUnqualified()
  67. .getAs<FunctionProtoType>();
  68. }
  69. /// Returns the "extra-canonicalized" return type, which discards
  70. /// qualifiers on the return type. Codegen doesn't care about them,
  71. /// and it makes ABI code a little easier to be able to assume that
  72. /// all parameter and return types are top-level unqualified.
  73. static CanQualType GetReturnType(QualType RetTy) {
  74. return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
  75. }
  76. /// Arrange the argument and result information for a value of the given
  77. /// unprototyped freestanding function type.
  78. const CGFunctionInfo &
  79. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
  80. // When translating an unprototyped function type, always use a
  81. // variadic type.
  82. return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
  83. /*instanceMethod=*/false,
  84. /*chainCall=*/false, None,
  85. FTNP->getExtInfo(), RequiredArgs(0));
  86. }
  87. /// Arrange the LLVM function layout for a value of the given function
  88. /// type, on top of any implicit parameters already stored.
  89. static const CGFunctionInfo &
  90. arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
  91. SmallVectorImpl<CanQualType> &prefix,
  92. CanQual<FunctionProtoType> FTP) {
  93. RequiredArgs required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
  94. // FIXME: Kill copy.
  95. prefix.append(FTP->param_type_begin(), FTP->param_type_end());
  96. CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
  97. return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
  98. /*chainCall=*/false, prefix,
  99. FTP->getExtInfo(), required);
  100. }
  101. /// Arrange the argument and result information for a value of the
  102. /// given freestanding function type.
  103. const CGFunctionInfo &
  104. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
  105. SmallVector<CanQualType, 16> argTypes;
  106. return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
  107. FTP);
  108. }
  109. static CallingConv getCallingConventionForDecl(const Decl *D, bool IsWindows) {
  110. // Set the appropriate calling convention for the Function.
  111. if (D->hasAttr<StdCallAttr>())
  112. return CC_X86StdCall;
  113. if (D->hasAttr<FastCallAttr>())
  114. return CC_X86FastCall;
  115. if (D->hasAttr<ThisCallAttr>())
  116. return CC_X86ThisCall;
  117. if (D->hasAttr<VectorCallAttr>())
  118. return CC_X86VectorCall;
  119. if (D->hasAttr<PascalAttr>())
  120. return CC_X86Pascal;
  121. if (PcsAttr *PCS = D->getAttr<PcsAttr>())
  122. return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
  123. if (D->hasAttr<IntelOclBiccAttr>())
  124. return CC_IntelOclBicc;
  125. if (D->hasAttr<MSABIAttr>())
  126. return IsWindows ? CC_C : CC_X86_64Win64;
  127. if (D->hasAttr<SysVABIAttr>())
  128. return IsWindows ? CC_X86_64SysV : CC_C;
  129. return CC_C;
  130. }
  131. /// Arrange the argument and result information for a call to an
  132. /// unknown C++ non-static member function of the given abstract type.
  133. /// (Zero value of RD means we don't have any meaningful "this" argument type,
  134. /// so fall back to a generic pointer type).
  135. /// The member function must be an ordinary function, i.e. not a
  136. /// constructor or destructor.
  137. const CGFunctionInfo &
  138. CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
  139. const FunctionProtoType *FTP) {
  140. SmallVector<CanQualType, 16> argTypes;
  141. // Add the 'this' pointer.
  142. if (RD)
  143. argTypes.push_back(GetThisType(Context, RD));
  144. else
  145. argTypes.push_back(Context.VoidPtrTy);
  146. return ::arrangeLLVMFunctionInfo(
  147. *this, true, argTypes,
  148. FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
  149. }
  150. /// Arrange the argument and result information for a declaration or
  151. /// definition of the given C++ non-static member function. The
  152. /// member function must be an ordinary function, i.e. not a
  153. /// constructor or destructor.
  154. const CGFunctionInfo &
  155. CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
  156. assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
  157. assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
  158. CanQual<FunctionProtoType> prototype = GetFormalType(MD);
  159. if (MD->isInstance()) {
  160. // The abstract case is perfectly fine.
  161. const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
  162. return arrangeCXXMethodType(ThisType, prototype.getTypePtr());
  163. }
  164. return arrangeFreeFunctionType(prototype);
  165. }
  166. const CGFunctionInfo &
  167. CodeGenTypes::arrangeCXXStructorDeclaration(const CXXMethodDecl *MD,
  168. StructorType Type) {
  169. SmallVector<CanQualType, 16> argTypes;
  170. argTypes.push_back(GetThisType(Context, MD->getParent()));
  171. GlobalDecl GD;
  172. if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  173. GD = GlobalDecl(CD, toCXXCtorType(Type));
  174. } else {
  175. auto *DD = dyn_cast<CXXDestructorDecl>(MD);
  176. GD = GlobalDecl(DD, toCXXDtorType(Type));
  177. }
  178. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  179. // Add the formal parameters.
  180. argTypes.append(FTP->param_type_begin(), FTP->param_type_end());
  181. TheCXXABI.buildStructorSignature(MD, Type, argTypes);
  182. RequiredArgs required =
  183. (MD->isVariadic() ? RequiredArgs(argTypes.size()) : RequiredArgs::All);
  184. FunctionType::ExtInfo extInfo = FTP->getExtInfo();
  185. CanQualType resultType = TheCXXABI.HasThisReturn(GD)
  186. ? argTypes.front()
  187. : TheCXXABI.hasMostDerivedReturn(GD)
  188. ? CGM.getContext().VoidPtrTy
  189. : Context.VoidTy;
  190. return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
  191. /*chainCall=*/false, argTypes, extInfo,
  192. required);
  193. }
  194. /// Arrange a call to a C++ method, passing the given arguments.
  195. const CGFunctionInfo &
  196. CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
  197. const CXXConstructorDecl *D,
  198. CXXCtorType CtorKind,
  199. unsigned ExtraArgs) {
  200. // FIXME: Kill copy.
  201. SmallVector<CanQualType, 16> ArgTypes;
  202. for (const auto &Arg : args)
  203. ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  204. CanQual<FunctionProtoType> FPT = GetFormalType(D);
  205. RequiredArgs Required = RequiredArgs::forPrototypePlus(FPT, 1 + ExtraArgs);
  206. GlobalDecl GD(D, CtorKind);
  207. CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
  208. ? ArgTypes.front()
  209. : TheCXXABI.hasMostDerivedReturn(GD)
  210. ? CGM.getContext().VoidPtrTy
  211. : Context.VoidTy;
  212. FunctionType::ExtInfo Info = FPT->getExtInfo();
  213. return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
  214. /*chainCall=*/false, ArgTypes, Info,
  215. Required);
  216. }
  217. /// Arrange the argument and result information for the declaration or
  218. /// definition of the given function.
  219. const CGFunctionInfo &
  220. CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
  221. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  222. if (MD->isInstance())
  223. return arrangeCXXMethodDeclaration(MD);
  224. CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
  225. assert(isa<FunctionType>(FTy));
  226. // When declaring a function without a prototype, always use a
  227. // non-variadic type.
  228. if (isa<FunctionNoProtoType>(FTy)) {
  229. CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
  230. return arrangeLLVMFunctionInfo(
  231. noProto->getReturnType(), /*instanceMethod=*/false,
  232. /*chainCall=*/false, None, noProto->getExtInfo(), RequiredArgs::All);
  233. }
  234. assert(isa<FunctionProtoType>(FTy));
  235. return arrangeFreeFunctionType(FTy.getAs<FunctionProtoType>());
  236. }
  237. /// Arrange the argument and result information for the declaration or
  238. /// definition of an Objective-C method.
  239. const CGFunctionInfo &
  240. CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
  241. // It happens that this is the same as a call with no optional
  242. // arguments, except also using the formal 'self' type.
  243. return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
  244. }
  245. /// Arrange the argument and result information for the function type
  246. /// through which to perform a send to the given Objective-C method,
  247. /// using the given receiver type. The receiver type is not always
  248. /// the 'self' type of the method or even an Objective-C pointer type.
  249. /// This is *not* the right method for actually performing such a
  250. /// message send, due to the possibility of optional arguments.
  251. const CGFunctionInfo &
  252. CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
  253. QualType receiverType) {
  254. SmallVector<CanQualType, 16> argTys;
  255. argTys.push_back(Context.getCanonicalParamType(receiverType));
  256. argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
  257. // FIXME: Kill copy?
  258. for (const auto *I : MD->params()) {
  259. argTys.push_back(Context.getCanonicalParamType(I->getType()));
  260. }
  261. FunctionType::ExtInfo einfo;
  262. bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
  263. einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
  264. if (getContext().getLangOpts().ObjCAutoRefCount &&
  265. MD->hasAttr<NSReturnsRetainedAttr>())
  266. einfo = einfo.withProducesResult(true);
  267. RequiredArgs required =
  268. (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
  269. return arrangeLLVMFunctionInfo(
  270. GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
  271. /*chainCall=*/false, argTys, einfo, required);
  272. }
  273. const CGFunctionInfo &
  274. CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
  275. // FIXME: Do we need to handle ObjCMethodDecl?
  276. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  277. if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(FD))
  278. return arrangeCXXStructorDeclaration(CD, getFromCtorType(GD.getCtorType()));
  279. if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(FD))
  280. return arrangeCXXStructorDeclaration(DD, getFromDtorType(GD.getDtorType()));
  281. return arrangeFunctionDeclaration(FD);
  282. }
  283. /// Arrange a thunk that takes 'this' as the first parameter followed by
  284. /// varargs. Return a void pointer, regardless of the actual return type.
  285. /// The body of the thunk will end in a musttail call to a function of the
  286. /// correct type, and the caller will bitcast the function to the correct
  287. /// prototype.
  288. const CGFunctionInfo &
  289. CodeGenTypes::arrangeMSMemberPointerThunk(const CXXMethodDecl *MD) {
  290. assert(MD->isVirtual() && "only virtual memptrs have thunks");
  291. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  292. CanQualType ArgTys[] = { GetThisType(Context, MD->getParent()) };
  293. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
  294. /*chainCall=*/false, ArgTys,
  295. FTP->getExtInfo(), RequiredArgs(1));
  296. }
  297. const CGFunctionInfo &
  298. CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
  299. CXXCtorType CT) {
  300. assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
  301. CanQual<FunctionProtoType> FTP = GetFormalType(CD);
  302. SmallVector<CanQualType, 2> ArgTys;
  303. const CXXRecordDecl *RD = CD->getParent();
  304. ArgTys.push_back(GetThisType(Context, RD));
  305. if (CT == Ctor_CopyingClosure)
  306. ArgTys.push_back(*FTP->param_type_begin());
  307. if (RD->getNumVBases() > 0)
  308. ArgTys.push_back(Context.IntTy);
  309. CallingConv CC = Context.getDefaultCallingConvention(
  310. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  311. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
  312. /*chainCall=*/false, ArgTys,
  313. FunctionType::ExtInfo(CC), RequiredArgs::All);
  314. }
  315. /// Arrange a call as unto a free function, except possibly with an
  316. /// additional number of formal parameters considered required.
  317. static const CGFunctionInfo &
  318. arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
  319. CodeGenModule &CGM,
  320. const CallArgList &args,
  321. const FunctionType *fnType,
  322. unsigned numExtraRequiredArgs,
  323. bool chainCall) {
  324. assert(args.size() >= numExtraRequiredArgs);
  325. // In most cases, there are no optional arguments.
  326. RequiredArgs required = RequiredArgs::All;
  327. // If we have a variadic prototype, the required arguments are the
  328. // extra prefix plus the arguments in the prototype.
  329. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
  330. if (proto->isVariadic())
  331. required = RequiredArgs(proto->getNumParams() + numExtraRequiredArgs);
  332. // If we don't have a prototype at all, but we're supposed to
  333. // explicitly use the variadic convention for unprototyped calls,
  334. // treat all of the arguments as required but preserve the nominal
  335. // possibility of variadics.
  336. } else if (CGM.getTargetCodeGenInfo()
  337. .isNoProtoCallVariadic(args,
  338. cast<FunctionNoProtoType>(fnType))) {
  339. required = RequiredArgs(args.size());
  340. }
  341. // FIXME: Kill copy.
  342. SmallVector<CanQualType, 16> argTypes;
  343. for (const auto &arg : args)
  344. argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
  345. return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
  346. /*instanceMethod=*/false, chainCall,
  347. argTypes, fnType->getExtInfo(), required);
  348. }
  349. /// Figure out the rules for calling a function with the given formal
  350. /// type using the given arguments. The arguments are necessary
  351. /// because the function might be unprototyped, in which case it's
  352. /// target-dependent in crazy ways.
  353. const CGFunctionInfo &
  354. CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
  355. const FunctionType *fnType,
  356. bool chainCall) {
  357. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
  358. chainCall ? 1 : 0, chainCall);
  359. }
  360. /// A block function call is essentially a free-function call with an
  361. /// extra implicit argument.
  362. const CGFunctionInfo &
  363. CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
  364. const FunctionType *fnType) {
  365. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
  366. /*chainCall=*/false);
  367. }
  368. const CGFunctionInfo &
  369. CodeGenTypes::arrangeFreeFunctionCall(QualType resultType,
  370. const CallArgList &args,
  371. FunctionType::ExtInfo info,
  372. RequiredArgs required) {
  373. // FIXME: Kill copy.
  374. SmallVector<CanQualType, 16> argTypes;
  375. for (const auto &Arg : args)
  376. argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  377. return arrangeLLVMFunctionInfo(
  378. GetReturnType(resultType), /*instanceMethod=*/false,
  379. /*chainCall=*/false, argTypes, info, required);
  380. }
  381. /// Arrange a call to a C++ method, passing the given arguments.
  382. const CGFunctionInfo &
  383. CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
  384. const FunctionProtoType *FPT,
  385. RequiredArgs required) {
  386. // FIXME: Kill copy.
  387. SmallVector<CanQualType, 16> argTypes;
  388. for (const auto &Arg : args)
  389. argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  390. FunctionType::ExtInfo info = FPT->getExtInfo();
  391. return arrangeLLVMFunctionInfo(
  392. GetReturnType(FPT->getReturnType()), /*instanceMethod=*/true,
  393. /*chainCall=*/false, argTypes, info, required);
  394. }
  395. const CGFunctionInfo &CodeGenTypes::arrangeFreeFunctionDeclaration(
  396. QualType resultType, const FunctionArgList &args,
  397. const FunctionType::ExtInfo &info, bool isVariadic) {
  398. // FIXME: Kill copy.
  399. SmallVector<CanQualType, 16> argTypes;
  400. for (auto Arg : args)
  401. argTypes.push_back(Context.getCanonicalParamType(Arg->getType()));
  402. RequiredArgs required =
  403. (isVariadic ? RequiredArgs(args.size()) : RequiredArgs::All);
  404. return arrangeLLVMFunctionInfo(
  405. GetReturnType(resultType), /*instanceMethod=*/false,
  406. /*chainCall=*/false, argTypes, info, required);
  407. }
  408. const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
  409. return arrangeLLVMFunctionInfo(
  410. getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
  411. None, FunctionType::ExtInfo(), RequiredArgs::All);
  412. }
  413. /// Arrange the argument and result information for an abstract value
  414. /// of a given function type. This is the method which all of the
  415. /// above functions ultimately defer to.
  416. const CGFunctionInfo &
  417. CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
  418. bool instanceMethod,
  419. bool chainCall,
  420. ArrayRef<CanQualType> argTypes,
  421. FunctionType::ExtInfo info,
  422. RequiredArgs required) {
  423. assert(std::all_of(argTypes.begin(), argTypes.end(),
  424. std::mem_fun_ref(&CanQualType::isCanonicalAsParam)));
  425. unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
  426. // Lookup or create unique function info.
  427. llvm::FoldingSetNodeID ID;
  428. CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, required,
  429. resultType, argTypes);
  430. void *insertPos = nullptr;
  431. CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
  432. if (FI)
  433. return *FI;
  434. // Construct the function info. We co-allocate the ArgInfos.
  435. FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
  436. resultType, argTypes, required);
  437. FunctionInfos.InsertNode(FI, insertPos);
  438. bool inserted = FunctionsBeingProcessed.insert(FI).second;
  439. (void)inserted;
  440. assert(inserted && "Recursively being processed?");
  441. // Compute ABI information.
  442. getABIInfo().computeInfo(*FI);
  443. // Loop over all of the computed argument and return value info. If any of
  444. // them are direct or extend without a specified coerce type, specify the
  445. // default now.
  446. ABIArgInfo &retInfo = FI->getReturnInfo();
  447. if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
  448. retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
  449. for (auto &I : FI->arguments())
  450. if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
  451. I.info.setCoerceToType(ConvertType(I.type));
  452. bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
  453. assert(erased && "Not in set?");
  454. return *FI;
  455. }
  456. CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
  457. bool instanceMethod,
  458. bool chainCall,
  459. const FunctionType::ExtInfo &info,
  460. CanQualType resultType,
  461. ArrayRef<CanQualType> argTypes,
  462. RequiredArgs required) {
  463. void *buffer = operator new(sizeof(CGFunctionInfo) +
  464. sizeof(ArgInfo) * (argTypes.size() + 1));
  465. CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
  466. FI->CallingConvention = llvmCC;
  467. FI->EffectiveCallingConvention = llvmCC;
  468. FI->ASTCallingConvention = info.getCC();
  469. FI->InstanceMethod = instanceMethod;
  470. FI->ChainCall = chainCall;
  471. FI->NoReturn = info.getNoReturn();
  472. FI->ReturnsRetained = info.getProducesResult();
  473. FI->Required = required;
  474. FI->HasRegParm = info.getHasRegParm();
  475. FI->RegParm = info.getRegParm();
  476. FI->ArgStruct = nullptr;
  477. FI->ArgStructAlign = 0;
  478. FI->NumArgs = argTypes.size();
  479. FI->getArgsBuffer()[0].type = resultType;
  480. for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
  481. FI->getArgsBuffer()[i + 1].type = argTypes[i];
  482. return FI;
  483. }
  484. /***/
  485. namespace {
  486. // ABIArgInfo::Expand implementation.
  487. // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
  488. struct TypeExpansion {
  489. enum TypeExpansionKind {
  490. // Elements of constant arrays are expanded recursively.
  491. TEK_ConstantArray,
  492. // Record fields are expanded recursively (but if record is a union, only
  493. // the field with the largest size is expanded).
  494. TEK_Record,
  495. // For complex types, real and imaginary parts are expanded recursively.
  496. TEK_Complex,
  497. // All other types are not expandable.
  498. TEK_None
  499. };
  500. const TypeExpansionKind Kind;
  501. TypeExpansion(TypeExpansionKind K) : Kind(K) {}
  502. virtual ~TypeExpansion() {}
  503. };
  504. struct ConstantArrayExpansion : TypeExpansion {
  505. QualType EltTy;
  506. uint64_t NumElts;
  507. ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
  508. : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
  509. static bool classof(const TypeExpansion *TE) {
  510. return TE->Kind == TEK_ConstantArray;
  511. }
  512. };
  513. struct RecordExpansion : TypeExpansion {
  514. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  515. SmallVector<const FieldDecl *, 1> Fields;
  516. RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
  517. SmallVector<const FieldDecl *, 1> &&Fields)
  518. : TypeExpansion(TEK_Record), Bases(Bases), Fields(Fields) {}
  519. static bool classof(const TypeExpansion *TE) {
  520. return TE->Kind == TEK_Record;
  521. }
  522. };
  523. struct ComplexExpansion : TypeExpansion {
  524. QualType EltTy;
  525. ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
  526. static bool classof(const TypeExpansion *TE) {
  527. return TE->Kind == TEK_Complex;
  528. }
  529. };
  530. struct NoExpansion : TypeExpansion {
  531. NoExpansion() : TypeExpansion(TEK_None) {}
  532. static bool classof(const TypeExpansion *TE) {
  533. return TE->Kind == TEK_None;
  534. }
  535. };
  536. } // namespace
  537. static std::unique_ptr<TypeExpansion>
  538. getTypeExpansion(QualType Ty, const ASTContext &Context) {
  539. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
  540. return llvm::make_unique<ConstantArrayExpansion>(
  541. AT->getElementType(), AT->getSize().getZExtValue());
  542. }
  543. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  544. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  545. SmallVector<const FieldDecl *, 1> Fields;
  546. const RecordDecl *RD = RT->getDecl();
  547. assert(!RD->hasFlexibleArrayMember() &&
  548. "Cannot expand structure with flexible array.");
  549. if (RD->isUnion()) {
  550. // Unions can be here only in degenerative cases - all the fields are same
  551. // after flattening. Thus we have to use the "largest" field.
  552. const FieldDecl *LargestFD = nullptr;
  553. CharUnits UnionSize = CharUnits::Zero();
  554. for (const auto *FD : RD->fields()) {
  555. // Skip zero length bitfields.
  556. if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
  557. continue;
  558. assert(!FD->isBitField() &&
  559. "Cannot expand structure with bit-field members.");
  560. CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
  561. if (UnionSize < FieldSize) {
  562. UnionSize = FieldSize;
  563. LargestFD = FD;
  564. }
  565. }
  566. if (LargestFD)
  567. Fields.push_back(LargestFD);
  568. } else {
  569. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  570. assert(!CXXRD->isDynamicClass() &&
  571. "cannot expand vtable pointers in dynamic classes");
  572. for (const CXXBaseSpecifier &BS : CXXRD->bases())
  573. Bases.push_back(&BS);
  574. }
  575. for (const auto *FD : RD->fields()) {
  576. // Skip zero length bitfields.
  577. if (FD->isBitField() && FD->getBitWidthValue(Context) == 0)
  578. continue;
  579. assert(!FD->isBitField() &&
  580. "Cannot expand structure with bit-field members.");
  581. Fields.push_back(FD);
  582. }
  583. }
  584. return llvm::make_unique<RecordExpansion>(std::move(Bases),
  585. std::move(Fields));
  586. }
  587. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  588. return llvm::make_unique<ComplexExpansion>(CT->getElementType());
  589. }
  590. return llvm::make_unique<NoExpansion>();
  591. }
  592. static int getExpansionSize(QualType Ty, const ASTContext &Context) {
  593. auto Exp = getTypeExpansion(Ty, Context);
  594. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  595. return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
  596. }
  597. if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  598. int Res = 0;
  599. for (auto BS : RExp->Bases)
  600. Res += getExpansionSize(BS->getType(), Context);
  601. for (auto FD : RExp->Fields)
  602. Res += getExpansionSize(FD->getType(), Context);
  603. return Res;
  604. }
  605. if (isa<ComplexExpansion>(Exp.get()))
  606. return 2;
  607. assert(isa<NoExpansion>(Exp.get()));
  608. return 1;
  609. }
  610. void
  611. CodeGenTypes::getExpandedTypes(QualType Ty,
  612. SmallVectorImpl<llvm::Type *>::iterator &TI) {
  613. auto Exp = getTypeExpansion(Ty, Context);
  614. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  615. for (int i = 0, n = CAExp->NumElts; i < n; i++) {
  616. getExpandedTypes(CAExp->EltTy, TI);
  617. }
  618. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  619. for (auto BS : RExp->Bases)
  620. getExpandedTypes(BS->getType(), TI);
  621. for (auto FD : RExp->Fields)
  622. getExpandedTypes(FD->getType(), TI);
  623. } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
  624. llvm::Type *EltTy = ConvertType(CExp->EltTy);
  625. *TI++ = EltTy;
  626. *TI++ = EltTy;
  627. } else {
  628. assert(isa<NoExpansion>(Exp.get()));
  629. *TI++ = ConvertType(Ty);
  630. }
  631. }
  632. static void forConstantArrayExpansion(CodeGenFunction &CGF,
  633. ConstantArrayExpansion *CAE,
  634. Address BaseAddr,
  635. llvm::function_ref<void(Address)> Fn) {
  636. CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
  637. CharUnits EltAlign =
  638. BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
  639. for (int i = 0, n = CAE->NumElts; i < n; i++) {
  640. llvm::Value *EltAddr =
  641. CGF.Builder.CreateConstGEP2_32(nullptr, BaseAddr.getPointer(), 0, i);
  642. Fn(Address(EltAddr, EltAlign));
  643. }
  644. }
  645. void CodeGenFunction::ExpandTypeFromArgs(
  646. QualType Ty, LValue LV, SmallVectorImpl<llvm::Argument *>::iterator &AI) {
  647. assert(LV.isSimple() &&
  648. "Unexpected non-simple lvalue during struct expansion.");
  649. auto Exp = getTypeExpansion(Ty, getContext());
  650. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  651. forConstantArrayExpansion(*this, CAExp, LV.getAddress(),
  652. [&](Address EltAddr) {
  653. LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
  654. ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
  655. });
  656. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  657. Address This = LV.getAddress();
  658. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  659. // Perform a single step derived-to-base conversion.
  660. Address Base =
  661. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  662. /*NullCheckValue=*/false, SourceLocation());
  663. LValue SubLV = MakeAddrLValue(Base, BS->getType());
  664. // Recurse onto bases.
  665. ExpandTypeFromArgs(BS->getType(), SubLV, AI);
  666. }
  667. for (auto FD : RExp->Fields) {
  668. // FIXME: What are the right qualifiers here?
  669. LValue SubLV = EmitLValueForField(LV, FD);
  670. ExpandTypeFromArgs(FD->getType(), SubLV, AI);
  671. }
  672. } else if (isa<ComplexExpansion>(Exp.get())) {
  673. auto realValue = *AI++;
  674. auto imagValue = *AI++;
  675. EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
  676. } else {
  677. assert(isa<NoExpansion>(Exp.get()));
  678. EmitStoreThroughLValue(RValue::get(*AI++), LV);
  679. }
  680. }
  681. void CodeGenFunction::ExpandTypeToArgs(
  682. QualType Ty, RValue RV, llvm::FunctionType *IRFuncTy,
  683. SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
  684. auto Exp = getTypeExpansion(Ty, getContext());
  685. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  686. forConstantArrayExpansion(*this, CAExp, RV.getAggregateAddress(),
  687. [&](Address EltAddr) {
  688. RValue EltRV =
  689. convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation());
  690. ExpandTypeToArgs(CAExp->EltTy, EltRV, IRFuncTy, IRCallArgs, IRCallArgPos);
  691. });
  692. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  693. Address This = RV.getAggregateAddress();
  694. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  695. // Perform a single step derived-to-base conversion.
  696. Address Base =
  697. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  698. /*NullCheckValue=*/false, SourceLocation());
  699. RValue BaseRV = RValue::getAggregate(Base);
  700. // Recurse onto bases.
  701. ExpandTypeToArgs(BS->getType(), BaseRV, IRFuncTy, IRCallArgs,
  702. IRCallArgPos);
  703. }
  704. LValue LV = MakeAddrLValue(This, Ty);
  705. for (auto FD : RExp->Fields) {
  706. RValue FldRV = EmitRValueForField(LV, FD, SourceLocation());
  707. ExpandTypeToArgs(FD->getType(), FldRV, IRFuncTy, IRCallArgs,
  708. IRCallArgPos);
  709. }
  710. } else if (isa<ComplexExpansion>(Exp.get())) {
  711. ComplexPairTy CV = RV.getComplexVal();
  712. IRCallArgs[IRCallArgPos++] = CV.first;
  713. IRCallArgs[IRCallArgPos++] = CV.second;
  714. } else {
  715. assert(isa<NoExpansion>(Exp.get()));
  716. assert(RV.isScalar() &&
  717. "Unexpected non-scalar rvalue during struct expansion.");
  718. // Insert a bitcast as needed.
  719. llvm::Value *V = RV.getScalarVal();
  720. if (IRCallArgPos < IRFuncTy->getNumParams() &&
  721. V->getType() != IRFuncTy->getParamType(IRCallArgPos))
  722. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
  723. IRCallArgs[IRCallArgPos++] = V;
  724. }
  725. }
  726. /// Create a temporary allocation for the purposes of coercion.
  727. static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
  728. CharUnits MinAlign) {
  729. // Don't use an alignment that's worse than what LLVM would prefer.
  730. auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
  731. CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
  732. return CGF.CreateTempAlloca(Ty, Align);
  733. }
  734. /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
  735. /// accessing some number of bytes out of it, try to gep into the struct to get
  736. /// at its inner goodness. Dive as deep as possible without entering an element
  737. /// with an in-memory size smaller than DstSize.
  738. static Address
  739. EnterStructPointerForCoercedAccess(Address SrcPtr,
  740. llvm::StructType *SrcSTy,
  741. uint64_t DstSize, CodeGenFunction &CGF) {
  742. // We can't dive into a zero-element struct.
  743. if (SrcSTy->getNumElements() == 0) return SrcPtr;
  744. llvm::Type *FirstElt = SrcSTy->getElementType(0);
  745. // If the first elt is at least as large as what we're looking for, or if the
  746. // first element is the same size as the whole struct, we can enter it. The
  747. // comparison must be made on the store size and not the alloca size. Using
  748. // the alloca size may overstate the size of the load.
  749. uint64_t FirstEltSize =
  750. CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
  751. if (FirstEltSize < DstSize &&
  752. FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
  753. return SrcPtr;
  754. // GEP into the first element.
  755. SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, CharUnits(), "coerce.dive");
  756. // If the first element is a struct, recurse.
  757. llvm::Type *SrcTy = SrcPtr.getElementType();
  758. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
  759. return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
  760. return SrcPtr;
  761. }
  762. /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
  763. /// are either integers or pointers. This does a truncation of the value if it
  764. /// is too large or a zero extension if it is too small.
  765. ///
  766. /// This behaves as if the value were coerced through memory, so on big-endian
  767. /// targets the high bits are preserved in a truncation, while little-endian
  768. /// targets preserve the low bits.
  769. static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
  770. llvm::Type *Ty,
  771. CodeGenFunction &CGF) {
  772. if (Val->getType() == Ty)
  773. return Val;
  774. if (isa<llvm::PointerType>(Val->getType())) {
  775. // If this is Pointer->Pointer avoid conversion to and from int.
  776. if (isa<llvm::PointerType>(Ty))
  777. return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
  778. // Convert the pointer to an integer so we can play with its width.
  779. Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
  780. }
  781. llvm::Type *DestIntTy = Ty;
  782. if (isa<llvm::PointerType>(DestIntTy))
  783. DestIntTy = CGF.IntPtrTy;
  784. if (Val->getType() != DestIntTy) {
  785. const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
  786. if (DL.isBigEndian()) {
  787. // Preserve the high bits on big-endian targets.
  788. // That is what memory coercion does.
  789. uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
  790. uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
  791. if (SrcSize > DstSize) {
  792. Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
  793. Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
  794. } else {
  795. Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
  796. Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
  797. }
  798. } else {
  799. // Little-endian targets preserve the low bits. No shifts required.
  800. Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
  801. }
  802. }
  803. if (isa<llvm::PointerType>(Ty))
  804. Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
  805. return Val;
  806. }
  807. /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
  808. /// a pointer to an object of type \arg Ty, known to be aligned to
  809. /// \arg SrcAlign bytes.
  810. ///
  811. /// This safely handles the case when the src type is smaller than the
  812. /// destination type; in this situation the values of bits which not
  813. /// present in the src are undefined.
  814. static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
  815. CodeGenFunction &CGF) {
  816. llvm::Type *SrcTy = Src.getElementType();
  817. // If SrcTy and Ty are the same, just do a load.
  818. if (SrcTy == Ty)
  819. return CGF.Builder.CreateLoad(Src);
  820. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
  821. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
  822. Src = EnterStructPointerForCoercedAccess(Src, SrcSTy, DstSize, CGF);
  823. SrcTy = Src.getType()->getElementType();
  824. }
  825. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  826. // If the source and destination are integer or pointer types, just do an
  827. // extension or truncation to the desired type.
  828. if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
  829. (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
  830. llvm::Value *Load = CGF.Builder.CreateLoad(Src);
  831. return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
  832. }
  833. // If load is legal, just bitcast the src pointer.
  834. if (SrcSize >= DstSize) {
  835. // Generally SrcSize is never greater than DstSize, since this means we are
  836. // losing bits. However, this can happen in cases where the structure has
  837. // additional padding, for example due to a user specified alignment.
  838. //
  839. // FIXME: Assert that we aren't truncating non-padding bits when have access
  840. // to that information.
  841. Src = CGF.Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(Ty));
  842. return CGF.Builder.CreateLoad(Src);
  843. }
  844. // Otherwise do coercion through memory. This is stupid, but simple.
  845. Address Tmp = CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment());
  846. Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
  847. Address SrcCasted = CGF.Builder.CreateBitCast(Src, CGF.Int8PtrTy);
  848. CGF.Builder.CreateMemCpy(Casted, SrcCasted,
  849. llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize),
  850. false);
  851. return CGF.Builder.CreateLoad(Tmp);
  852. }
  853. // Function to store a first-class aggregate into memory. We prefer to
  854. // store the elements rather than the aggregate to be more friendly to
  855. // fast-isel.
  856. // FIXME: Do we need to recurse here?
  857. static void BuildAggStore(CodeGenFunction &CGF, llvm::Value *Val,
  858. Address Dest, bool DestIsVolatile) {
  859. // Prefer scalar stores to first-class aggregate stores.
  860. if (llvm::StructType *STy =
  861. dyn_cast<llvm::StructType>(Val->getType())) {
  862. const llvm::StructLayout *Layout =
  863. CGF.CGM.getDataLayout().getStructLayout(STy);
  864. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  865. auto EltOffset = CharUnits::fromQuantity(Layout->getElementOffset(i));
  866. Address EltPtr = CGF.Builder.CreateStructGEP(Dest, i, EltOffset);
  867. llvm::Value *Elt = CGF.Builder.CreateExtractValue(Val, i);
  868. CGF.Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
  869. }
  870. } else {
  871. CGF.Builder.CreateStore(Val, Dest, DestIsVolatile);
  872. }
  873. }
  874. /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
  875. /// where the source and destination may have different types. The
  876. /// destination is known to be aligned to \arg DstAlign bytes.
  877. ///
  878. /// This safely handles the case when the src type is larger than the
  879. /// destination type; the upper bits of the src will be lost.
  880. static void CreateCoercedStore(llvm::Value *Src,
  881. Address Dst,
  882. bool DstIsVolatile,
  883. CodeGenFunction &CGF) {
  884. llvm::Type *SrcTy = Src->getType();
  885. llvm::Type *DstTy = Dst.getType()->getElementType();
  886. if (SrcTy == DstTy) {
  887. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  888. return;
  889. }
  890. uint64_t SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  891. if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
  892. Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy, SrcSize, CGF);
  893. DstTy = Dst.getType()->getElementType();
  894. }
  895. // If the source and destination are integer or pointer types, just do an
  896. // extension or truncation to the desired type.
  897. if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
  898. (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
  899. Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
  900. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  901. return;
  902. }
  903. uint64_t DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
  904. // If store is legal, just bitcast the src pointer.
  905. if (SrcSize <= DstSize) {
  906. Dst = CGF.Builder.CreateBitCast(Dst, llvm::PointerType::getUnqual(SrcTy));
  907. BuildAggStore(CGF, Src, Dst, DstIsVolatile);
  908. } else {
  909. // Otherwise do coercion through memory. This is stupid, but
  910. // simple.
  911. // Generally SrcSize is never greater than DstSize, since this means we are
  912. // losing bits. However, this can happen in cases where the structure has
  913. // additional padding, for example due to a user specified alignment.
  914. //
  915. // FIXME: Assert that we aren't truncating non-padding bits when have access
  916. // to that information.
  917. Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
  918. CGF.Builder.CreateStore(Src, Tmp);
  919. Address Casted = CGF.Builder.CreateBitCast(Tmp, CGF.Int8PtrTy);
  920. Address DstCasted = CGF.Builder.CreateBitCast(Dst, CGF.Int8PtrTy);
  921. CGF.Builder.CreateMemCpy(DstCasted, Casted,
  922. llvm::ConstantInt::get(CGF.IntPtrTy, DstSize),
  923. false);
  924. }
  925. }
  926. static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
  927. const ABIArgInfo &info) {
  928. if (unsigned offset = info.getDirectOffset()) {
  929. addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
  930. addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
  931. CharUnits::fromQuantity(offset));
  932. addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
  933. }
  934. return addr;
  935. }
  936. namespace {
  937. /// Encapsulates information about the way function arguments from
  938. /// CGFunctionInfo should be passed to actual LLVM IR function.
  939. class ClangToLLVMArgMapping {
  940. static const unsigned InvalidIndex = ~0U;
  941. unsigned InallocaArgNo;
  942. unsigned SRetArgNo;
  943. unsigned TotalIRArgs;
  944. /// Arguments of LLVM IR function corresponding to single Clang argument.
  945. struct IRArgs {
  946. unsigned PaddingArgIndex;
  947. // Argument is expanded to IR arguments at positions
  948. // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
  949. unsigned FirstArgIndex;
  950. unsigned NumberOfArgs;
  951. IRArgs()
  952. : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
  953. NumberOfArgs(0) {}
  954. };
  955. SmallVector<IRArgs, 8> ArgInfo;
  956. public:
  957. ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
  958. bool OnlyRequiredArgs = false)
  959. : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
  960. ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
  961. construct(Context, FI, OnlyRequiredArgs);
  962. }
  963. bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
  964. unsigned getInallocaArgNo() const {
  965. assert(hasInallocaArg());
  966. return InallocaArgNo;
  967. }
  968. bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
  969. unsigned getSRetArgNo() const {
  970. assert(hasSRetArg());
  971. return SRetArgNo;
  972. }
  973. unsigned totalIRArgs() const { return TotalIRArgs; }
  974. bool hasPaddingArg(unsigned ArgNo) const {
  975. assert(ArgNo < ArgInfo.size());
  976. return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
  977. }
  978. unsigned getPaddingArgNo(unsigned ArgNo) const {
  979. assert(hasPaddingArg(ArgNo));
  980. return ArgInfo[ArgNo].PaddingArgIndex;
  981. }
  982. /// Returns index of first IR argument corresponding to ArgNo, and their
  983. /// quantity.
  984. std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
  985. assert(ArgNo < ArgInfo.size());
  986. return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
  987. ArgInfo[ArgNo].NumberOfArgs);
  988. }
  989. private:
  990. void construct(const ASTContext &Context, const CGFunctionInfo &FI,
  991. bool OnlyRequiredArgs);
  992. };
  993. void ClangToLLVMArgMapping::construct(const ASTContext &Context,
  994. const CGFunctionInfo &FI,
  995. bool OnlyRequiredArgs) {
  996. unsigned IRArgNo = 0;
  997. bool SwapThisWithSRet = false;
  998. const ABIArgInfo &RetAI = FI.getReturnInfo();
  999. if (RetAI.getKind() == ABIArgInfo::Indirect) {
  1000. SwapThisWithSRet = RetAI.isSRetAfterThis();
  1001. SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
  1002. }
  1003. unsigned ArgNo = 0;
  1004. unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
  1005. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
  1006. ++I, ++ArgNo) {
  1007. assert(I != FI.arg_end());
  1008. QualType ArgType = I->type;
  1009. const ABIArgInfo &AI = I->info;
  1010. // Collect data about IR arguments corresponding to Clang argument ArgNo.
  1011. auto &IRArgs = ArgInfo[ArgNo];
  1012. if (AI.getPaddingType())
  1013. IRArgs.PaddingArgIndex = IRArgNo++;
  1014. switch (AI.getKind()) {
  1015. case ABIArgInfo::Extend:
  1016. case ABIArgInfo::Direct: {
  1017. // FIXME: handle sseregparm someday...
  1018. llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
  1019. if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
  1020. IRArgs.NumberOfArgs = STy->getNumElements();
  1021. } else {
  1022. IRArgs.NumberOfArgs = 1;
  1023. }
  1024. break;
  1025. }
  1026. case ABIArgInfo::Indirect:
  1027. IRArgs.NumberOfArgs = 1;
  1028. break;
  1029. case ABIArgInfo::Ignore:
  1030. case ABIArgInfo::InAlloca:
  1031. // ignore and inalloca doesn't have matching LLVM parameters.
  1032. IRArgs.NumberOfArgs = 0;
  1033. break;
  1034. case ABIArgInfo::Expand: {
  1035. IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
  1036. break;
  1037. }
  1038. }
  1039. if (IRArgs.NumberOfArgs > 0) {
  1040. IRArgs.FirstArgIndex = IRArgNo;
  1041. IRArgNo += IRArgs.NumberOfArgs;
  1042. }
  1043. // Skip over the sret parameter when it comes second. We already handled it
  1044. // above.
  1045. if (IRArgNo == 1 && SwapThisWithSRet)
  1046. IRArgNo++;
  1047. }
  1048. assert(ArgNo == ArgInfo.size());
  1049. if (FI.usesInAlloca())
  1050. InallocaArgNo = IRArgNo++;
  1051. TotalIRArgs = IRArgNo;
  1052. }
  1053. } // namespace
  1054. /***/
  1055. bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
  1056. return FI.getReturnInfo().isIndirect();
  1057. }
  1058. bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
  1059. return ReturnTypeUsesSRet(FI) &&
  1060. getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
  1061. }
  1062. bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
  1063. if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
  1064. switch (BT->getKind()) {
  1065. default:
  1066. return false;
  1067. case BuiltinType::Float:
  1068. return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
  1069. case BuiltinType::Double:
  1070. return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
  1071. case BuiltinType::LongDouble:
  1072. return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
  1073. }
  1074. }
  1075. return false;
  1076. }
  1077. bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
  1078. if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
  1079. if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
  1080. if (BT->getKind() == BuiltinType::LongDouble)
  1081. return getTarget().useObjCFP2RetForComplexLongDouble();
  1082. }
  1083. }
  1084. return false;
  1085. }
  1086. llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
  1087. const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
  1088. return GetFunctionType(FI);
  1089. }
  1090. llvm::FunctionType *
  1091. CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
  1092. bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
  1093. (void)Inserted;
  1094. assert(Inserted && "Recursively being processed?");
  1095. llvm::Type *resultType = nullptr;
  1096. const ABIArgInfo &retAI = FI.getReturnInfo();
  1097. switch (retAI.getKind()) {
  1098. case ABIArgInfo::Expand:
  1099. llvm_unreachable("Invalid ABI kind for return argument");
  1100. case ABIArgInfo::Extend:
  1101. case ABIArgInfo::Direct:
  1102. resultType = retAI.getCoerceToType();
  1103. break;
  1104. case ABIArgInfo::InAlloca:
  1105. if (retAI.getInAllocaSRet()) {
  1106. // sret things on win32 aren't void, they return the sret pointer.
  1107. QualType ret = FI.getReturnType();
  1108. llvm::Type *ty = ConvertType(ret);
  1109. unsigned addressSpace = Context.getTargetAddressSpace(ret);
  1110. resultType = llvm::PointerType::get(ty, addressSpace);
  1111. } else {
  1112. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1113. }
  1114. break;
  1115. case ABIArgInfo::Indirect:
  1116. case ABIArgInfo::Ignore:
  1117. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1118. break;
  1119. }
  1120. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
  1121. SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
  1122. // Add type for sret argument.
  1123. if (IRFunctionArgs.hasSRetArg()) {
  1124. QualType Ret = FI.getReturnType();
  1125. llvm::Type *Ty = ConvertType(Ret);
  1126. unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
  1127. ArgTypes[IRFunctionArgs.getSRetArgNo()] =
  1128. llvm::PointerType::get(Ty, AddressSpace);
  1129. }
  1130. // Add type for inalloca argument.
  1131. if (IRFunctionArgs.hasInallocaArg()) {
  1132. auto ArgStruct = FI.getArgStruct();
  1133. assert(ArgStruct);
  1134. ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
  1135. }
  1136. // Add in all of the required arguments.
  1137. unsigned ArgNo = 0;
  1138. CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
  1139. ie = it + FI.getNumRequiredArgs();
  1140. for (; it != ie; ++it, ++ArgNo) {
  1141. const ABIArgInfo &ArgInfo = it->info;
  1142. // Insert a padding type to ensure proper alignment.
  1143. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  1144. ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  1145. ArgInfo.getPaddingType();
  1146. unsigned FirstIRArg, NumIRArgs;
  1147. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1148. switch (ArgInfo.getKind()) {
  1149. case ABIArgInfo::Ignore:
  1150. case ABIArgInfo::InAlloca:
  1151. assert(NumIRArgs == 0);
  1152. break;
  1153. case ABIArgInfo::Indirect: {
  1154. assert(NumIRArgs == 1);
  1155. // indirect arguments are always on the stack, which is addr space #0.
  1156. llvm::Type *LTy = ConvertTypeForMem(it->type);
  1157. ArgTypes[FirstIRArg] = LTy->getPointerTo();
  1158. break;
  1159. }
  1160. case ABIArgInfo::Extend:
  1161. case ABIArgInfo::Direct: {
  1162. // Fast-isel and the optimizer generally like scalar values better than
  1163. // FCAs, so we flatten them if this is safe to do for this argument.
  1164. llvm::Type *argType = ArgInfo.getCoerceToType();
  1165. llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
  1166. if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  1167. assert(NumIRArgs == st->getNumElements());
  1168. for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
  1169. ArgTypes[FirstIRArg + i] = st->getElementType(i);
  1170. } else {
  1171. assert(NumIRArgs == 1);
  1172. ArgTypes[FirstIRArg] = argType;
  1173. }
  1174. break;
  1175. }
  1176. case ABIArgInfo::Expand:
  1177. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1178. getExpandedTypes(it->type, ArgTypesIter);
  1179. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1180. break;
  1181. }
  1182. }
  1183. bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
  1184. assert(Erased && "Not in set?");
  1185. return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
  1186. }
  1187. llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
  1188. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1189. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  1190. if (!isFuncTypeConvertible(FPT))
  1191. return llvm::StructType::get(getLLVMContext());
  1192. const CGFunctionInfo *Info;
  1193. if (isa<CXXDestructorDecl>(MD))
  1194. Info =
  1195. &arrangeCXXStructorDeclaration(MD, getFromDtorType(GD.getDtorType()));
  1196. else
  1197. Info = &arrangeCXXMethodDeclaration(MD);
  1198. return GetFunctionType(*Info);
  1199. }
  1200. void CodeGenModule::ConstructAttributeList(const CGFunctionInfo &FI,
  1201. const Decl *TargetDecl,
  1202. AttributeListType &PAL,
  1203. unsigned &CallingConv,
  1204. bool AttrOnCallSite) {
  1205. llvm::AttrBuilder FuncAttrs;
  1206. llvm::AttrBuilder RetAttrs;
  1207. bool HasOptnone = false;
  1208. CallingConv = FI.getEffectiveCallingConvention();
  1209. if (FI.isNoReturn())
  1210. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1211. // FIXME: handle sseregparm someday...
  1212. if (TargetDecl) {
  1213. if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
  1214. FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
  1215. if (TargetDecl->hasAttr<NoThrowAttr>())
  1216. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1217. if (TargetDecl->hasAttr<NoReturnAttr>())
  1218. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1219. if (TargetDecl->hasAttr<NoDuplicateAttr>())
  1220. FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
  1221. if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1222. const FunctionProtoType *FPT = Fn->getType()->getAs<FunctionProtoType>();
  1223. if (FPT && !isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  1224. FPT->isNothrow(getContext()))
  1225. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1226. // Don't use [[noreturn]] or _Noreturn for a call to a virtual function.
  1227. // These attributes are not inherited by overloads.
  1228. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
  1229. if (Fn->isNoReturn() && !(AttrOnCallSite && MD && MD->isVirtual()))
  1230. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1231. }
  1232. // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
  1233. if (TargetDecl->hasAttr<ConstAttr>()) {
  1234. FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
  1235. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1236. } else if (TargetDecl->hasAttr<PureAttr>()) {
  1237. FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
  1238. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1239. } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
  1240. FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
  1241. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1242. }
  1243. if (TargetDecl->hasAttr<RestrictAttr>())
  1244. RetAttrs.addAttribute(llvm::Attribute::NoAlias);
  1245. if (TargetDecl->hasAttr<ReturnsNonNullAttr>())
  1246. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1247. HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
  1248. }
  1249. // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
  1250. if (!HasOptnone) {
  1251. if (CodeGenOpts.OptimizeSize)
  1252. FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
  1253. if (CodeGenOpts.OptimizeSize == 2)
  1254. FuncAttrs.addAttribute(llvm::Attribute::MinSize);
  1255. }
  1256. if (CodeGenOpts.DisableRedZone)
  1257. FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
  1258. if (CodeGenOpts.NoImplicitFloat)
  1259. FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
  1260. if (CodeGenOpts.EnableSegmentedStacks &&
  1261. !(TargetDecl && TargetDecl->hasAttr<NoSplitStackAttr>()))
  1262. FuncAttrs.addAttribute("split-stack");
  1263. if (AttrOnCallSite) {
  1264. // Attributes that should go on the call site only.
  1265. if (!CodeGenOpts.SimplifyLibCalls)
  1266. FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
  1267. if (!CodeGenOpts.TrapFuncName.empty())
  1268. FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
  1269. } else {
  1270. // Attributes that should go on the function, but not the call site.
  1271. if (!CodeGenOpts.DisableFPElim) {
  1272. FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
  1273. } else if (CodeGenOpts.OmitLeafFramePointer) {
  1274. FuncAttrs.addAttribute("no-frame-pointer-elim", "false");
  1275. FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
  1276. } else {
  1277. FuncAttrs.addAttribute("no-frame-pointer-elim", "true");
  1278. FuncAttrs.addAttribute("no-frame-pointer-elim-non-leaf");
  1279. }
  1280. FuncAttrs.addAttribute("disable-tail-calls",
  1281. llvm::toStringRef(CodeGenOpts.DisableTailCalls));
  1282. FuncAttrs.addAttribute("less-precise-fpmad",
  1283. llvm::toStringRef(CodeGenOpts.LessPreciseFPMAD));
  1284. FuncAttrs.addAttribute("no-infs-fp-math",
  1285. llvm::toStringRef(CodeGenOpts.NoInfsFPMath));
  1286. FuncAttrs.addAttribute("no-nans-fp-math",
  1287. llvm::toStringRef(CodeGenOpts.NoNaNsFPMath));
  1288. FuncAttrs.addAttribute("unsafe-fp-math",
  1289. llvm::toStringRef(CodeGenOpts.UnsafeFPMath));
  1290. FuncAttrs.addAttribute("use-soft-float",
  1291. llvm::toStringRef(CodeGenOpts.SoftFloat));
  1292. FuncAttrs.addAttribute("stack-protector-buffer-size",
  1293. llvm::utostr(CodeGenOpts.SSPBufferSize));
  1294. if (CodeGenOpts.StackRealignment)
  1295. FuncAttrs.addAttribute("stackrealign");
  1296. // Add target-cpu and target-features attributes to functions. If
  1297. // we have a decl for the function and it has a target attribute then
  1298. // parse that and add it to the feature set.
  1299. StringRef TargetCPU = getTarget().getTargetOpts().CPU;
  1300. const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl);
  1301. if (FD && FD->hasAttr<TargetAttr>()) {
  1302. llvm::StringMap<bool> FeatureMap;
  1303. const auto *TD = FD->getAttr<TargetAttr>();
  1304. TargetAttr::ParsedTargetAttr ParsedAttr = TD->parse();
  1305. // Make a copy of the features as passed on the command line into the
  1306. // beginning of the additional features from the function to override.
  1307. ParsedAttr.first.insert(
  1308. ParsedAttr.first.begin(),
  1309. getTarget().getTargetOpts().FeaturesAsWritten.begin(),
  1310. getTarget().getTargetOpts().FeaturesAsWritten.end());
  1311. if (ParsedAttr.second != "")
  1312. TargetCPU = ParsedAttr.second;
  1313. // Now populate the feature map, first with the TargetCPU which is either
  1314. // the default or a new one from the target attribute string. Then we'll
  1315. // use the passed in features (FeaturesAsWritten) along with the new ones
  1316. // from the attribute.
  1317. getTarget().initFeatureMap(FeatureMap, Diags, TargetCPU, ParsedAttr.first);
  1318. // Produce the canonical string for this set of features.
  1319. std::vector<std::string> Features;
  1320. for (llvm::StringMap<bool>::const_iterator it = FeatureMap.begin(),
  1321. ie = FeatureMap.end();
  1322. it != ie; ++it)
  1323. Features.push_back((it->second ? "+" : "-") + it->first().str());
  1324. // Now add the target-cpu and target-features to the function.
  1325. if (TargetCPU != "")
  1326. FuncAttrs.addAttribute("target-cpu", TargetCPU);
  1327. if (!Features.empty()) {
  1328. std::sort(Features.begin(), Features.end());
  1329. FuncAttrs.addAttribute(
  1330. "target-features",
  1331. llvm::join(Features.begin(), Features.end(), ","));
  1332. }
  1333. } else {
  1334. // Otherwise just add the existing target cpu and target features to the
  1335. // function.
  1336. std::vector<std::string> &Features = getTarget().getTargetOpts().Features;
  1337. if (TargetCPU != "")
  1338. FuncAttrs.addAttribute("target-cpu", TargetCPU);
  1339. if (!Features.empty()) {
  1340. std::sort(Features.begin(), Features.end());
  1341. FuncAttrs.addAttribute(
  1342. "target-features",
  1343. llvm::join(Features.begin(), Features.end(), ","));
  1344. }
  1345. }
  1346. }
  1347. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
  1348. QualType RetTy = FI.getReturnType();
  1349. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1350. switch (RetAI.getKind()) {
  1351. case ABIArgInfo::Extend:
  1352. if (RetTy->hasSignedIntegerRepresentation())
  1353. RetAttrs.addAttribute(llvm::Attribute::SExt);
  1354. else if (RetTy->hasUnsignedIntegerRepresentation())
  1355. RetAttrs.addAttribute(llvm::Attribute::ZExt);
  1356. // FALL THROUGH
  1357. case ABIArgInfo::Direct:
  1358. if (RetAI.getInReg())
  1359. RetAttrs.addAttribute(llvm::Attribute::InReg);
  1360. break;
  1361. case ABIArgInfo::Ignore:
  1362. break;
  1363. case ABIArgInfo::InAlloca:
  1364. case ABIArgInfo::Indirect: {
  1365. // inalloca and sret disable readnone and readonly
  1366. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1367. .removeAttribute(llvm::Attribute::ReadNone);
  1368. break;
  1369. }
  1370. case ABIArgInfo::Expand:
  1371. llvm_unreachable("Invalid ABI kind for return argument");
  1372. }
  1373. if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
  1374. QualType PTy = RefTy->getPointeeType();
  1375. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1376. RetAttrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1377. .getQuantity());
  1378. else if (getContext().getTargetAddressSpace(PTy) == 0)
  1379. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1380. }
  1381. // Attach return attributes.
  1382. if (RetAttrs.hasAttributes()) {
  1383. PAL.push_back(llvm::AttributeSet::get(
  1384. getLLVMContext(), llvm::AttributeSet::ReturnIndex, RetAttrs));
  1385. }
  1386. // Attach attributes to sret.
  1387. if (IRFunctionArgs.hasSRetArg()) {
  1388. llvm::AttrBuilder SRETAttrs;
  1389. SRETAttrs.addAttribute(llvm::Attribute::StructRet);
  1390. if (RetAI.getInReg())
  1391. SRETAttrs.addAttribute(llvm::Attribute::InReg);
  1392. PAL.push_back(llvm::AttributeSet::get(
  1393. getLLVMContext(), IRFunctionArgs.getSRetArgNo() + 1, SRETAttrs));
  1394. }
  1395. // Attach attributes to inalloca argument.
  1396. if (IRFunctionArgs.hasInallocaArg()) {
  1397. llvm::AttrBuilder Attrs;
  1398. Attrs.addAttribute(llvm::Attribute::InAlloca);
  1399. PAL.push_back(llvm::AttributeSet::get(
  1400. getLLVMContext(), IRFunctionArgs.getInallocaArgNo() + 1, Attrs));
  1401. }
  1402. unsigned ArgNo = 0;
  1403. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
  1404. E = FI.arg_end();
  1405. I != E; ++I, ++ArgNo) {
  1406. QualType ParamType = I->type;
  1407. const ABIArgInfo &AI = I->info;
  1408. llvm::AttrBuilder Attrs;
  1409. // Add attribute for padding argument, if necessary.
  1410. if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
  1411. if (AI.getPaddingInReg())
  1412. PAL.push_back(llvm::AttributeSet::get(
  1413. getLLVMContext(), IRFunctionArgs.getPaddingArgNo(ArgNo) + 1,
  1414. llvm::Attribute::InReg));
  1415. }
  1416. // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
  1417. // have the corresponding parameter variable. It doesn't make
  1418. // sense to do it here because parameters are so messed up.
  1419. switch (AI.getKind()) {
  1420. case ABIArgInfo::Extend:
  1421. if (ParamType->isSignedIntegerOrEnumerationType())
  1422. Attrs.addAttribute(llvm::Attribute::SExt);
  1423. else if (ParamType->isUnsignedIntegerOrEnumerationType()) {
  1424. if (getTypes().getABIInfo().shouldSignExtUnsignedType(ParamType))
  1425. Attrs.addAttribute(llvm::Attribute::SExt);
  1426. else
  1427. Attrs.addAttribute(llvm::Attribute::ZExt);
  1428. }
  1429. // FALL THROUGH
  1430. case ABIArgInfo::Direct:
  1431. if (ArgNo == 0 && FI.isChainCall())
  1432. Attrs.addAttribute(llvm::Attribute::Nest);
  1433. else if (AI.getInReg())
  1434. Attrs.addAttribute(llvm::Attribute::InReg);
  1435. break;
  1436. case ABIArgInfo::Indirect: {
  1437. if (AI.getInReg())
  1438. Attrs.addAttribute(llvm::Attribute::InReg);
  1439. if (AI.getIndirectByVal())
  1440. Attrs.addAttribute(llvm::Attribute::ByVal);
  1441. CharUnits Align = AI.getIndirectAlign();
  1442. // In a byval argument, it is important that the required
  1443. // alignment of the type is honored, as LLVM might be creating a
  1444. // *new* stack object, and needs to know what alignment to give
  1445. // it. (Sometimes it can deduce a sensible alignment on its own,
  1446. // but not if clang decides it must emit a packed struct, or the
  1447. // user specifies increased alignment requirements.)
  1448. //
  1449. // This is different from indirect *not* byval, where the object
  1450. // exists already, and the align attribute is purely
  1451. // informative.
  1452. assert(!Align.isZero());
  1453. // For now, only add this when we have a byval argument.
  1454. // TODO: be less lazy about updating test cases.
  1455. if (AI.getIndirectByVal())
  1456. Attrs.addAlignmentAttr(Align.getQuantity());
  1457. // byval disables readnone and readonly.
  1458. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1459. .removeAttribute(llvm::Attribute::ReadNone);
  1460. break;
  1461. }
  1462. case ABIArgInfo::Ignore:
  1463. case ABIArgInfo::Expand:
  1464. continue;
  1465. case ABIArgInfo::InAlloca:
  1466. // inalloca disables readnone and readonly.
  1467. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1468. .removeAttribute(llvm::Attribute::ReadNone);
  1469. continue;
  1470. }
  1471. if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
  1472. QualType PTy = RefTy->getPointeeType();
  1473. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  1474. Attrs.addDereferenceableAttr(getContext().getTypeSizeInChars(PTy)
  1475. .getQuantity());
  1476. else if (getContext().getTargetAddressSpace(PTy) == 0)
  1477. Attrs.addAttribute(llvm::Attribute::NonNull);
  1478. }
  1479. if (Attrs.hasAttributes()) {
  1480. unsigned FirstIRArg, NumIRArgs;
  1481. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1482. for (unsigned i = 0; i < NumIRArgs; i++)
  1483. PAL.push_back(llvm::AttributeSet::get(getLLVMContext(),
  1484. FirstIRArg + i + 1, Attrs));
  1485. }
  1486. }
  1487. assert(ArgNo == FI.arg_size());
  1488. if (FuncAttrs.hasAttributes())
  1489. PAL.push_back(llvm::
  1490. AttributeSet::get(getLLVMContext(),
  1491. llvm::AttributeSet::FunctionIndex,
  1492. FuncAttrs));
  1493. }
  1494. /// An argument came in as a promoted argument; demote it back to its
  1495. /// declared type.
  1496. static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
  1497. const VarDecl *var,
  1498. llvm::Value *value) {
  1499. llvm::Type *varType = CGF.ConvertType(var->getType());
  1500. // This can happen with promotions that actually don't change the
  1501. // underlying type, like the enum promotions.
  1502. if (value->getType() == varType) return value;
  1503. assert((varType->isIntegerTy() || varType->isFloatingPointTy())
  1504. && "unexpected promotion type");
  1505. if (isa<llvm::IntegerType>(varType))
  1506. return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
  1507. return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
  1508. }
  1509. /// Returns the attribute (either parameter attribute, or function
  1510. /// attribute), which declares argument ArgNo to be non-null.
  1511. static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
  1512. QualType ArgType, unsigned ArgNo) {
  1513. // FIXME: __attribute__((nonnull)) can also be applied to:
  1514. // - references to pointers, where the pointee is known to be
  1515. // nonnull (apparently a Clang extension)
  1516. // - transparent unions containing pointers
  1517. // In the former case, LLVM IR cannot represent the constraint. In
  1518. // the latter case, we have no guarantee that the transparent union
  1519. // is in fact passed as a pointer.
  1520. if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
  1521. return nullptr;
  1522. // First, check attribute on parameter itself.
  1523. if (PVD) {
  1524. if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
  1525. return ParmNNAttr;
  1526. }
  1527. // Check function attributes.
  1528. if (!FD)
  1529. return nullptr;
  1530. for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
  1531. if (NNAttr->isNonNull(ArgNo))
  1532. return NNAttr;
  1533. }
  1534. return nullptr;
  1535. }
  1536. void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
  1537. llvm::Function *Fn,
  1538. const FunctionArgList &Args) {
  1539. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
  1540. // Naked functions don't have prologues.
  1541. return;
  1542. // If this is an implicit-return-zero function, go ahead and
  1543. // initialize the return value. TODO: it might be nice to have
  1544. // a more general mechanism for this that didn't require synthesized
  1545. // return statements.
  1546. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
  1547. if (FD->hasImplicitReturnZero()) {
  1548. QualType RetTy = FD->getReturnType().getUnqualifiedType();
  1549. llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
  1550. llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
  1551. Builder.CreateStore(Zero, ReturnValue);
  1552. }
  1553. }
  1554. // FIXME: We no longer need the types from FunctionArgList; lift up and
  1555. // simplify.
  1556. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
  1557. // Flattened function arguments.
  1558. SmallVector<llvm::Argument *, 16> FnArgs;
  1559. FnArgs.reserve(IRFunctionArgs.totalIRArgs());
  1560. for (auto &Arg : Fn->args()) {
  1561. FnArgs.push_back(&Arg);
  1562. }
  1563. assert(FnArgs.size() == IRFunctionArgs.totalIRArgs());
  1564. // If we're using inalloca, all the memory arguments are GEPs off of the last
  1565. // parameter, which is a pointer to the complete memory area.
  1566. Address ArgStruct = Address::invalid();
  1567. const llvm::StructLayout *ArgStructLayout = nullptr;
  1568. if (IRFunctionArgs.hasInallocaArg()) {
  1569. ArgStructLayout = CGM.getDataLayout().getStructLayout(FI.getArgStruct());
  1570. ArgStruct = Address(FnArgs[IRFunctionArgs.getInallocaArgNo()],
  1571. FI.getArgStructAlignment());
  1572. assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
  1573. }
  1574. // Name the struct return parameter.
  1575. if (IRFunctionArgs.hasSRetArg()) {
  1576. auto AI = FnArgs[IRFunctionArgs.getSRetArgNo()];
  1577. AI->setName("agg.result");
  1578. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(), AI->getArgNo() + 1,
  1579. llvm::Attribute::NoAlias));
  1580. }
  1581. // Track if we received the parameter as a pointer (indirect, byval, or
  1582. // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
  1583. // into a local alloca for us.
  1584. SmallVector<ParamValue, 16> ArgVals;
  1585. ArgVals.reserve(Args.size());
  1586. // Create a pointer value for every parameter declaration. This usually
  1587. // entails copying one or more LLVM IR arguments into an alloca. Don't push
  1588. // any cleanups or do anything that might unwind. We do that separately, so
  1589. // we can push the cleanups in the correct order for the ABI.
  1590. assert(FI.arg_size() == Args.size() &&
  1591. "Mismatch between function signature & arguments.");
  1592. unsigned ArgNo = 0;
  1593. CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
  1594. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  1595. i != e; ++i, ++info_it, ++ArgNo) {
  1596. const VarDecl *Arg = *i;
  1597. QualType Ty = info_it->type;
  1598. const ABIArgInfo &ArgI = info_it->info;
  1599. bool isPromoted =
  1600. isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
  1601. unsigned FirstIRArg, NumIRArgs;
  1602. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1603. switch (ArgI.getKind()) {
  1604. case ABIArgInfo::InAlloca: {
  1605. assert(NumIRArgs == 0);
  1606. auto FieldIndex = ArgI.getInAllocaFieldIndex();
  1607. CharUnits FieldOffset =
  1608. CharUnits::fromQuantity(ArgStructLayout->getElementOffset(FieldIndex));
  1609. Address V = Builder.CreateStructGEP(ArgStruct, FieldIndex, FieldOffset,
  1610. Arg->getName());
  1611. ArgVals.push_back(ParamValue::forIndirect(V));
  1612. break;
  1613. }
  1614. case ABIArgInfo::Indirect: {
  1615. assert(NumIRArgs == 1);
  1616. Address ParamAddr = Address(FnArgs[FirstIRArg], ArgI.getIndirectAlign());
  1617. if (!hasScalarEvaluationKind(Ty)) {
  1618. // Aggregates and complex variables are accessed by reference. All we
  1619. // need to do is realign the value, if requested.
  1620. Address V = ParamAddr;
  1621. if (ArgI.getIndirectRealign()) {
  1622. Address AlignedTemp = CreateMemTemp(Ty, "coerce");
  1623. // Copy from the incoming argument pointer to the temporary with the
  1624. // appropriate alignment.
  1625. //
  1626. // FIXME: We should have a common utility for generating an aggregate
  1627. // copy.
  1628. CharUnits Size = getContext().getTypeSizeInChars(Ty);
  1629. auto SizeVal = llvm::ConstantInt::get(IntPtrTy, Size.getQuantity());
  1630. Address Dst = Builder.CreateBitCast(AlignedTemp, Int8PtrTy);
  1631. Address Src = Builder.CreateBitCast(ParamAddr, Int8PtrTy);
  1632. Builder.CreateMemCpy(Dst, Src, SizeVal, false);
  1633. V = AlignedTemp;
  1634. }
  1635. ArgVals.push_back(ParamValue::forIndirect(V));
  1636. } else {
  1637. // Load scalar value from indirect argument.
  1638. llvm::Value *V =
  1639. EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getLocStart());
  1640. if (isPromoted)
  1641. V = emitArgumentDemotion(*this, Arg, V);
  1642. ArgVals.push_back(ParamValue::forDirect(V));
  1643. }
  1644. break;
  1645. }
  1646. case ABIArgInfo::Extend:
  1647. case ABIArgInfo::Direct: {
  1648. // If we have the trivial case, handle it with no muss and fuss.
  1649. if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
  1650. ArgI.getCoerceToType() == ConvertType(Ty) &&
  1651. ArgI.getDirectOffset() == 0) {
  1652. assert(NumIRArgs == 1);
  1653. auto AI = FnArgs[FirstIRArg];
  1654. llvm::Value *V = AI;
  1655. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
  1656. if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
  1657. PVD->getFunctionScopeIndex()))
  1658. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1659. AI->getArgNo() + 1,
  1660. llvm::Attribute::NonNull));
  1661. QualType OTy = PVD->getOriginalType();
  1662. if (const auto *ArrTy =
  1663. getContext().getAsConstantArrayType(OTy)) {
  1664. // A C99 array parameter declaration with the static keyword also
  1665. // indicates dereferenceability, and if the size is constant we can
  1666. // use the dereferenceable attribute (which requires the size in
  1667. // bytes).
  1668. if (ArrTy->getSizeModifier() == ArrayType::Static) {
  1669. QualType ETy = ArrTy->getElementType();
  1670. uint64_t ArrSize = ArrTy->getSize().getZExtValue();
  1671. if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
  1672. ArrSize) {
  1673. llvm::AttrBuilder Attrs;
  1674. Attrs.addDereferenceableAttr(
  1675. getContext().getTypeSizeInChars(ETy).getQuantity()*ArrSize);
  1676. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1677. AI->getArgNo() + 1, Attrs));
  1678. } else if (getContext().getTargetAddressSpace(ETy) == 0) {
  1679. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1680. AI->getArgNo() + 1,
  1681. llvm::Attribute::NonNull));
  1682. }
  1683. }
  1684. } else if (const auto *ArrTy =
  1685. getContext().getAsVariableArrayType(OTy)) {
  1686. // For C99 VLAs with the static keyword, we don't know the size so
  1687. // we can't use the dereferenceable attribute, but in addrspace(0)
  1688. // we know that it must be nonnull.
  1689. if (ArrTy->getSizeModifier() == VariableArrayType::Static &&
  1690. !getContext().getTargetAddressSpace(ArrTy->getElementType()))
  1691. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1692. AI->getArgNo() + 1,
  1693. llvm::Attribute::NonNull));
  1694. }
  1695. const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
  1696. if (!AVAttr)
  1697. if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
  1698. AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
  1699. if (AVAttr) {
  1700. llvm::Value *AlignmentValue =
  1701. EmitScalarExpr(AVAttr->getAlignment());
  1702. llvm::ConstantInt *AlignmentCI =
  1703. cast<llvm::ConstantInt>(AlignmentValue);
  1704. unsigned Alignment =
  1705. std::min((unsigned) AlignmentCI->getZExtValue(),
  1706. +llvm::Value::MaximumAlignment);
  1707. llvm::AttrBuilder Attrs;
  1708. Attrs.addAlignmentAttr(Alignment);
  1709. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1710. AI->getArgNo() + 1, Attrs));
  1711. }
  1712. }
  1713. if (Arg->getType().isRestrictQualified())
  1714. AI->addAttr(llvm::AttributeSet::get(getLLVMContext(),
  1715. AI->getArgNo() + 1,
  1716. llvm::Attribute::NoAlias));
  1717. // Ensure the argument is the correct type.
  1718. if (V->getType() != ArgI.getCoerceToType())
  1719. V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
  1720. if (isPromoted)
  1721. V = emitArgumentDemotion(*this, Arg, V);
  1722. if (const CXXMethodDecl *MD =
  1723. dyn_cast_or_null<CXXMethodDecl>(CurCodeDecl)) {
  1724. if (MD->isVirtual() && Arg == CXXABIThisDecl)
  1725. V = CGM.getCXXABI().
  1726. adjustThisParameterInVirtualFunctionPrologue(*this, CurGD, V);
  1727. }
  1728. // Because of merging of function types from multiple decls it is
  1729. // possible for the type of an argument to not match the corresponding
  1730. // type in the function type. Since we are codegening the callee
  1731. // in here, add a cast to the argument type.
  1732. llvm::Type *LTy = ConvertType(Arg->getType());
  1733. if (V->getType() != LTy)
  1734. V = Builder.CreateBitCast(V, LTy);
  1735. ArgVals.push_back(ParamValue::forDirect(V));
  1736. break;
  1737. }
  1738. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
  1739. Arg->getName());
  1740. // Pointer to store into.
  1741. Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
  1742. // Fast-isel and the optimizer generally like scalar values better than
  1743. // FCAs, so we flatten them if this is safe to do for this argument.
  1744. llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
  1745. if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
  1746. STy->getNumElements() > 1) {
  1747. auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
  1748. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
  1749. llvm::Type *DstTy = Ptr.getElementType();
  1750. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
  1751. Address AddrToStoreInto = Address::invalid();
  1752. if (SrcSize <= DstSize) {
  1753. AddrToStoreInto =
  1754. Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(STy));
  1755. } else {
  1756. AddrToStoreInto =
  1757. CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
  1758. }
  1759. assert(STy->getNumElements() == NumIRArgs);
  1760. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1761. auto AI = FnArgs[FirstIRArg + i];
  1762. AI->setName(Arg->getName() + ".coerce" + Twine(i));
  1763. auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
  1764. Address EltPtr =
  1765. Builder.CreateStructGEP(AddrToStoreInto, i, Offset);
  1766. Builder.CreateStore(AI, EltPtr);
  1767. }
  1768. if (SrcSize > DstSize) {
  1769. Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
  1770. }
  1771. } else {
  1772. // Simple case, just do a coerced store of the argument into the alloca.
  1773. assert(NumIRArgs == 1);
  1774. auto AI = FnArgs[FirstIRArg];
  1775. AI->setName(Arg->getName() + ".coerce");
  1776. CreateCoercedStore(AI, Ptr, /*DestIsVolatile=*/false, *this);
  1777. }
  1778. // Match to what EmitParmDecl is expecting for this type.
  1779. if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
  1780. llvm::Value *V =
  1781. EmitLoadOfScalar(Alloca, false, Ty, Arg->getLocStart());
  1782. if (isPromoted)
  1783. V = emitArgumentDemotion(*this, Arg, V);
  1784. ArgVals.push_back(ParamValue::forDirect(V));
  1785. } else {
  1786. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  1787. }
  1788. break;
  1789. }
  1790. case ABIArgInfo::Expand: {
  1791. // If this structure was expanded into multiple arguments then
  1792. // we need to create a temporary and reconstruct it from the
  1793. // arguments.
  1794. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
  1795. LValue LV = MakeAddrLValue(Alloca, Ty);
  1796. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  1797. auto FnArgIter = FnArgs.begin() + FirstIRArg;
  1798. ExpandTypeFromArgs(Ty, LV, FnArgIter);
  1799. assert(FnArgIter == FnArgs.begin() + FirstIRArg + NumIRArgs);
  1800. for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
  1801. auto AI = FnArgs[FirstIRArg + i];
  1802. AI->setName(Arg->getName() + "." + Twine(i));
  1803. }
  1804. break;
  1805. }
  1806. case ABIArgInfo::Ignore:
  1807. assert(NumIRArgs == 0);
  1808. // Initialize the local variable appropriately.
  1809. if (!hasScalarEvaluationKind(Ty)) {
  1810. ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
  1811. } else {
  1812. llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
  1813. ArgVals.push_back(ParamValue::forDirect(U));
  1814. }
  1815. break;
  1816. }
  1817. }
  1818. if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  1819. for (int I = Args.size() - 1; I >= 0; --I)
  1820. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  1821. } else {
  1822. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  1823. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  1824. }
  1825. }
  1826. static void eraseUnusedBitCasts(llvm::Instruction *insn) {
  1827. while (insn->use_empty()) {
  1828. llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
  1829. if (!bitcast) return;
  1830. // This is "safe" because we would have used a ConstantExpr otherwise.
  1831. insn = cast<llvm::Instruction>(bitcast->getOperand(0));
  1832. bitcast->eraseFromParent();
  1833. }
  1834. }
  1835. /// Try to emit a fused autorelease of a return result.
  1836. static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
  1837. llvm::Value *result) {
  1838. // We must be immediately followed the cast.
  1839. llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
  1840. if (BB->empty()) return nullptr;
  1841. if (&BB->back() != result) return nullptr;
  1842. llvm::Type *resultType = result->getType();
  1843. // result is in a BasicBlock and is therefore an Instruction.
  1844. llvm::Instruction *generator = cast<llvm::Instruction>(result);
  1845. SmallVector<llvm::Instruction*,4> insnsToKill;
  1846. // Look for:
  1847. // %generator = bitcast %type1* %generator2 to %type2*
  1848. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
  1849. // We would have emitted this as a constant if the operand weren't
  1850. // an Instruction.
  1851. generator = cast<llvm::Instruction>(bitcast->getOperand(0));
  1852. // Require the generator to be immediately followed by the cast.
  1853. if (generator->getNextNode() != bitcast)
  1854. return nullptr;
  1855. insnsToKill.push_back(bitcast);
  1856. }
  1857. // Look for:
  1858. // %generator = call i8* @objc_retain(i8* %originalResult)
  1859. // or
  1860. // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
  1861. llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
  1862. if (!call) return nullptr;
  1863. bool doRetainAutorelease;
  1864. if (call->getCalledValue() == CGF.CGM.getARCEntrypoints().objc_retain) {
  1865. doRetainAutorelease = true;
  1866. } else if (call->getCalledValue() == CGF.CGM.getARCEntrypoints()
  1867. .objc_retainAutoreleasedReturnValue) {
  1868. doRetainAutorelease = false;
  1869. // If we emitted an assembly marker for this call (and the
  1870. // ARCEntrypoints field should have been set if so), go looking
  1871. // for that call. If we can't find it, we can't do this
  1872. // optimization. But it should always be the immediately previous
  1873. // instruction, unless we needed bitcasts around the call.
  1874. if (CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker) {
  1875. llvm::Instruction *prev = call->getPrevNode();
  1876. assert(prev);
  1877. if (isa<llvm::BitCastInst>(prev)) {
  1878. prev = prev->getPrevNode();
  1879. assert(prev);
  1880. }
  1881. assert(isa<llvm::CallInst>(prev));
  1882. assert(cast<llvm::CallInst>(prev)->getCalledValue() ==
  1883. CGF.CGM.getARCEntrypoints().retainAutoreleasedReturnValueMarker);
  1884. insnsToKill.push_back(prev);
  1885. }
  1886. } else {
  1887. return nullptr;
  1888. }
  1889. result = call->getArgOperand(0);
  1890. insnsToKill.push_back(call);
  1891. // Keep killing bitcasts, for sanity. Note that we no longer care
  1892. // about precise ordering as long as there's exactly one use.
  1893. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
  1894. if (!bitcast->hasOneUse()) break;
  1895. insnsToKill.push_back(bitcast);
  1896. result = bitcast->getOperand(0);
  1897. }
  1898. // Delete all the unnecessary instructions, from latest to earliest.
  1899. for (SmallVectorImpl<llvm::Instruction*>::iterator
  1900. i = insnsToKill.begin(), e = insnsToKill.end(); i != e; ++i)
  1901. (*i)->eraseFromParent();
  1902. // Do the fused retain/autorelease if we were asked to.
  1903. if (doRetainAutorelease)
  1904. result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
  1905. // Cast back to the result type.
  1906. return CGF.Builder.CreateBitCast(result, resultType);
  1907. }
  1908. /// If this is a +1 of the value of an immutable 'self', remove it.
  1909. static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
  1910. llvm::Value *result) {
  1911. // This is only applicable to a method with an immutable 'self'.
  1912. const ObjCMethodDecl *method =
  1913. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
  1914. if (!method) return nullptr;
  1915. const VarDecl *self = method->getSelfDecl();
  1916. if (!self->getType().isConstQualified()) return nullptr;
  1917. // Look for a retain call.
  1918. llvm::CallInst *retainCall =
  1919. dyn_cast<llvm::CallInst>(result->stripPointerCasts());
  1920. if (!retainCall ||
  1921. retainCall->getCalledValue() != CGF.CGM.getARCEntrypoints().objc_retain)
  1922. return nullptr;
  1923. // Look for an ordinary load of 'self'.
  1924. llvm::Value *retainedValue = retainCall->getArgOperand(0);
  1925. llvm::LoadInst *load =
  1926. dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
  1927. if (!load || load->isAtomic() || load->isVolatile() ||
  1928. load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
  1929. return nullptr;
  1930. // Okay! Burn it all down. This relies for correctness on the
  1931. // assumption that the retain is emitted as part of the return and
  1932. // that thereafter everything is used "linearly".
  1933. llvm::Type *resultType = result->getType();
  1934. eraseUnusedBitCasts(cast<llvm::Instruction>(result));
  1935. assert(retainCall->use_empty());
  1936. retainCall->eraseFromParent();
  1937. eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
  1938. return CGF.Builder.CreateBitCast(load, resultType);
  1939. }
  1940. /// Emit an ARC autorelease of the result of a function.
  1941. ///
  1942. /// \return the value to actually return from the function
  1943. static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
  1944. llvm::Value *result) {
  1945. // If we're returning 'self', kill the initial retain. This is a
  1946. // heuristic attempt to "encourage correctness" in the really unfortunate
  1947. // case where we have a return of self during a dealloc and we desperately
  1948. // need to avoid the possible autorelease.
  1949. if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
  1950. return self;
  1951. // At -O0, try to emit a fused retain/autorelease.
  1952. if (CGF.shouldUseFusedARCCalls())
  1953. if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
  1954. return fused;
  1955. return CGF.EmitARCAutoreleaseReturnValue(result);
  1956. }
  1957. /// Heuristically search for a dominating store to the return-value slot.
  1958. static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
  1959. // Check if a User is a store which pointerOperand is the ReturnValue.
  1960. // We are looking for stores to the ReturnValue, not for stores of the
  1961. // ReturnValue to some other location.
  1962. auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
  1963. auto *SI = dyn_cast<llvm::StoreInst>(U);
  1964. if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
  1965. return nullptr;
  1966. // These aren't actually possible for non-coerced returns, and we
  1967. // only care about non-coerced returns on this code path.
  1968. assert(!SI->isAtomic() && !SI->isVolatile());
  1969. return SI;
  1970. };
  1971. // If there are multiple uses of the return-value slot, just check
  1972. // for something immediately preceding the IP. Sometimes this can
  1973. // happen with how we generate implicit-returns; it can also happen
  1974. // with noreturn cleanups.
  1975. if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
  1976. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  1977. if (IP->empty()) return nullptr;
  1978. llvm::Instruction *I = &IP->back();
  1979. // Skip lifetime markers
  1980. for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
  1981. IE = IP->rend();
  1982. II != IE; ++II) {
  1983. if (llvm::IntrinsicInst *Intrinsic =
  1984. dyn_cast<llvm::IntrinsicInst>(&*II)) {
  1985. if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
  1986. const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
  1987. ++II;
  1988. if (II == IE)
  1989. break;
  1990. if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
  1991. continue;
  1992. }
  1993. }
  1994. I = &*II;
  1995. break;
  1996. }
  1997. return GetStoreIfValid(I);
  1998. }
  1999. llvm::StoreInst *store =
  2000. GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
  2001. if (!store) return nullptr;
  2002. // Now do a first-and-dirty dominance check: just walk up the
  2003. // single-predecessors chain from the current insertion point.
  2004. llvm::BasicBlock *StoreBB = store->getParent();
  2005. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2006. while (IP != StoreBB) {
  2007. if (!(IP = IP->getSinglePredecessor()))
  2008. return nullptr;
  2009. }
  2010. // Okay, the store's basic block dominates the insertion point; we
  2011. // can do our thing.
  2012. return store;
  2013. }
  2014. void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
  2015. bool EmitRetDbgLoc,
  2016. SourceLocation EndLoc) {
  2017. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
  2018. // Naked functions don't have epilogues.
  2019. Builder.CreateUnreachable();
  2020. return;
  2021. }
  2022. // Functions with no result always return void.
  2023. if (!ReturnValue.isValid()) {
  2024. Builder.CreateRetVoid();
  2025. return;
  2026. }
  2027. llvm::DebugLoc RetDbgLoc;
  2028. llvm::Value *RV = nullptr;
  2029. QualType RetTy = FI.getReturnType();
  2030. const ABIArgInfo &RetAI = FI.getReturnInfo();
  2031. switch (RetAI.getKind()) {
  2032. case ABIArgInfo::InAlloca:
  2033. // Aggregrates get evaluated directly into the destination. Sometimes we
  2034. // need to return the sret value in a register, though.
  2035. assert(hasAggregateEvaluationKind(RetTy));
  2036. if (RetAI.getInAllocaSRet()) {
  2037. llvm::Function::arg_iterator EI = CurFn->arg_end();
  2038. --EI;
  2039. llvm::Value *ArgStruct = EI;
  2040. llvm::Value *SRet = Builder.CreateStructGEP(
  2041. nullptr, ArgStruct, RetAI.getInAllocaFieldIndex());
  2042. RV = Builder.CreateAlignedLoad(SRet, getPointerAlign(), "sret");
  2043. }
  2044. break;
  2045. case ABIArgInfo::Indirect: {
  2046. auto AI = CurFn->arg_begin();
  2047. if (RetAI.isSRetAfterThis())
  2048. ++AI;
  2049. switch (getEvaluationKind(RetTy)) {
  2050. case TEK_Complex: {
  2051. ComplexPairTy RT =
  2052. EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
  2053. EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(AI, RetTy),
  2054. /*isInit*/ true);
  2055. break;
  2056. }
  2057. case TEK_Aggregate:
  2058. // Do nothing; aggregrates get evaluated directly into the destination.
  2059. break;
  2060. case TEK_Scalar:
  2061. EmitStoreOfScalar(Builder.CreateLoad(ReturnValue),
  2062. MakeNaturalAlignAddrLValue(AI, RetTy),
  2063. /*isInit*/ true);
  2064. break;
  2065. }
  2066. break;
  2067. }
  2068. case ABIArgInfo::Extend:
  2069. case ABIArgInfo::Direct:
  2070. if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
  2071. RetAI.getDirectOffset() == 0) {
  2072. // The internal return value temp always will have pointer-to-return-type
  2073. // type, just do a load.
  2074. // If there is a dominating store to ReturnValue, we can elide
  2075. // the load, zap the store, and usually zap the alloca.
  2076. if (llvm::StoreInst *SI =
  2077. findDominatingStoreToReturnValue(*this)) {
  2078. // Reuse the debug location from the store unless there is
  2079. // cleanup code to be emitted between the store and return
  2080. // instruction.
  2081. if (EmitRetDbgLoc && !AutoreleaseResult)
  2082. RetDbgLoc = SI->getDebugLoc();
  2083. // Get the stored value and nuke the now-dead store.
  2084. RV = SI->getValueOperand();
  2085. SI->eraseFromParent();
  2086. // If that was the only use of the return value, nuke it as well now.
  2087. auto returnValueInst = ReturnValue.getPointer();
  2088. if (returnValueInst->use_empty()) {
  2089. if (auto alloca = dyn_cast<llvm::AllocaInst>(returnValueInst)) {
  2090. alloca->eraseFromParent();
  2091. ReturnValue = Address::invalid();
  2092. }
  2093. }
  2094. // Otherwise, we have to do a simple load.
  2095. } else {
  2096. RV = Builder.CreateLoad(ReturnValue);
  2097. }
  2098. } else {
  2099. // If the value is offset in memory, apply the offset now.
  2100. Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
  2101. RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
  2102. }
  2103. // In ARC, end functions that return a retainable type with a call
  2104. // to objc_autoreleaseReturnValue.
  2105. if (AutoreleaseResult) {
  2106. assert(getLangOpts().ObjCAutoRefCount &&
  2107. !FI.isReturnsRetained() &&
  2108. RetTy->isObjCRetainableType());
  2109. RV = emitAutoreleaseOfResult(*this, RV);
  2110. }
  2111. break;
  2112. case ABIArgInfo::Ignore:
  2113. break;
  2114. case ABIArgInfo::Expand:
  2115. llvm_unreachable("Invalid ABI kind for return argument");
  2116. }
  2117. llvm::Instruction *Ret;
  2118. if (RV) {
  2119. if (CurCodeDecl && SanOpts.has(SanitizerKind::ReturnsNonnullAttribute)) {
  2120. if (auto RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>()) {
  2121. SanitizerScope SanScope(this);
  2122. llvm::Value *Cond = Builder.CreateICmpNE(
  2123. RV, llvm::Constant::getNullValue(RV->getType()));
  2124. llvm::Constant *StaticData[] = {
  2125. EmitCheckSourceLocation(EndLoc),
  2126. EmitCheckSourceLocation(RetNNAttr->getLocation()),
  2127. };
  2128. EmitCheck(std::make_pair(Cond, SanitizerKind::ReturnsNonnullAttribute),
  2129. "nonnull_return", StaticData, None);
  2130. }
  2131. }
  2132. Ret = Builder.CreateRet(RV);
  2133. } else {
  2134. Ret = Builder.CreateRetVoid();
  2135. }
  2136. if (RetDbgLoc)
  2137. Ret->setDebugLoc(std::move(RetDbgLoc));
  2138. }
  2139. static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
  2140. const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
  2141. return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
  2142. }
  2143. static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
  2144. QualType Ty) {
  2145. // FIXME: Generate IR in one pass, rather than going back and fixing up these
  2146. // placeholders.
  2147. llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
  2148. llvm::Value *Placeholder =
  2149. llvm::UndefValue::get(IRTy->getPointerTo()->getPointerTo());
  2150. Placeholder = CGF.Builder.CreateDefaultAlignedLoad(Placeholder);
  2151. // FIXME: When we generate this IR in one pass, we shouldn't need
  2152. // this win32-specific alignment hack.
  2153. CharUnits Align = CharUnits::fromQuantity(4);
  2154. return AggValueSlot::forAddr(Address(Placeholder, Align),
  2155. Ty.getQualifiers(),
  2156. AggValueSlot::IsNotDestructed,
  2157. AggValueSlot::DoesNotNeedGCBarriers,
  2158. AggValueSlot::IsNotAliased);
  2159. }
  2160. void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
  2161. const VarDecl *param,
  2162. SourceLocation loc) {
  2163. // StartFunction converted the ABI-lowered parameter(s) into a
  2164. // local alloca. We need to turn that into an r-value suitable
  2165. // for EmitCall.
  2166. Address local = GetAddrOfLocalVar(param);
  2167. QualType type = param->getType();
  2168. // For the most part, we just need to load the alloca, except:
  2169. // 1) aggregate r-values are actually pointers to temporaries, and
  2170. // 2) references to non-scalars are pointers directly to the aggregate.
  2171. // I don't know why references to scalars are different here.
  2172. if (const ReferenceType *ref = type->getAs<ReferenceType>()) {
  2173. if (!hasScalarEvaluationKind(ref->getPointeeType()))
  2174. return args.add(RValue::getAggregate(local), type);
  2175. // Locals which are references to scalars are represented
  2176. // with allocas holding the pointer.
  2177. return args.add(RValue::get(Builder.CreateLoad(local)), type);
  2178. }
  2179. assert(!isInAllocaArgument(CGM.getCXXABI(), type) &&
  2180. "cannot emit delegate call arguments for inalloca arguments!");
  2181. args.add(convertTempToRValue(local, type, loc), type);
  2182. }
  2183. static bool isProvablyNull(llvm::Value *addr) {
  2184. return isa<llvm::ConstantPointerNull>(addr);
  2185. }
  2186. static bool isProvablyNonNull(llvm::Value *addr) {
  2187. return isa<llvm::AllocaInst>(addr);
  2188. }
  2189. /// Emit the actual writing-back of a writeback.
  2190. static void emitWriteback(CodeGenFunction &CGF,
  2191. const CallArgList::Writeback &writeback) {
  2192. const LValue &srcLV = writeback.Source;
  2193. Address srcAddr = srcLV.getAddress();
  2194. assert(!isProvablyNull(srcAddr.getPointer()) &&
  2195. "shouldn't have writeback for provably null argument");
  2196. llvm::BasicBlock *contBB = nullptr;
  2197. // If the argument wasn't provably non-null, we need to null check
  2198. // before doing the store.
  2199. bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
  2200. if (!provablyNonNull) {
  2201. llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
  2202. contBB = CGF.createBasicBlock("icr.done");
  2203. llvm::Value *isNull =
  2204. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  2205. CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
  2206. CGF.EmitBlock(writebackBB);
  2207. }
  2208. // Load the value to writeback.
  2209. llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
  2210. // Cast it back, in case we're writing an id to a Foo* or something.
  2211. value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
  2212. "icr.writeback-cast");
  2213. // Perform the writeback.
  2214. // If we have a "to use" value, it's something we need to emit a use
  2215. // of. This has to be carefully threaded in: if it's done after the
  2216. // release it's potentially undefined behavior (and the optimizer
  2217. // will ignore it), and if it happens before the retain then the
  2218. // optimizer could move the release there.
  2219. if (writeback.ToUse) {
  2220. assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
  2221. // Retain the new value. No need to block-copy here: the block's
  2222. // being passed up the stack.
  2223. value = CGF.EmitARCRetainNonBlock(value);
  2224. // Emit the intrinsic use here.
  2225. CGF.EmitARCIntrinsicUse(writeback.ToUse);
  2226. // Load the old value (primitively).
  2227. llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
  2228. // Put the new value in place (primitively).
  2229. CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
  2230. // Release the old value.
  2231. CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
  2232. // Otherwise, we can just do a normal lvalue store.
  2233. } else {
  2234. CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
  2235. }
  2236. // Jump to the continuation block.
  2237. if (!provablyNonNull)
  2238. CGF.EmitBlock(contBB);
  2239. }
  2240. static void emitWritebacks(CodeGenFunction &CGF,
  2241. const CallArgList &args) {
  2242. for (const auto &I : args.writebacks())
  2243. emitWriteback(CGF, I);
  2244. }
  2245. static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
  2246. const CallArgList &CallArgs) {
  2247. assert(CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee());
  2248. ArrayRef<CallArgList::CallArgCleanup> Cleanups =
  2249. CallArgs.getCleanupsToDeactivate();
  2250. // Iterate in reverse to increase the likelihood of popping the cleanup.
  2251. for (const auto &I : llvm::reverse(Cleanups)) {
  2252. CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
  2253. I.IsActiveIP->eraseFromParent();
  2254. }
  2255. }
  2256. static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
  2257. if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
  2258. if (uop->getOpcode() == UO_AddrOf)
  2259. return uop->getSubExpr();
  2260. return nullptr;
  2261. }
  2262. /// Emit an argument that's being passed call-by-writeback. That is,
  2263. /// we are passing the address of an __autoreleased temporary; it
  2264. /// might be copy-initialized with the current value of the given
  2265. /// address, but it will definitely be copied out of after the call.
  2266. static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
  2267. const ObjCIndirectCopyRestoreExpr *CRE) {
  2268. LValue srcLV;
  2269. // Make an optimistic effort to emit the address as an l-value.
  2270. // This can fail if the argument expression is more complicated.
  2271. if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
  2272. srcLV = CGF.EmitLValue(lvExpr);
  2273. // Otherwise, just emit it as a scalar.
  2274. } else {
  2275. Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
  2276. QualType srcAddrType =
  2277. CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  2278. srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
  2279. }
  2280. Address srcAddr = srcLV.getAddress();
  2281. // The dest and src types don't necessarily match in LLVM terms
  2282. // because of the crazy ObjC compatibility rules.
  2283. llvm::PointerType *destType =
  2284. cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
  2285. // If the address is a constant null, just pass the appropriate null.
  2286. if (isProvablyNull(srcAddr.getPointer())) {
  2287. args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
  2288. CRE->getType());
  2289. return;
  2290. }
  2291. // Create the temporary.
  2292. Address temp = CGF.CreateTempAlloca(destType->getElementType(),
  2293. CGF.getPointerAlign(),
  2294. "icr.temp");
  2295. // Loading an l-value can introduce a cleanup if the l-value is __weak,
  2296. // and that cleanup will be conditional if we can't prove that the l-value
  2297. // isn't null, so we need to register a dominating point so that the cleanups
  2298. // system will make valid IR.
  2299. CodeGenFunction::ConditionalEvaluation condEval(CGF);
  2300. // Zero-initialize it if we're not doing a copy-initialization.
  2301. bool shouldCopy = CRE->shouldCopy();
  2302. if (!shouldCopy) {
  2303. llvm::Value *null =
  2304. llvm::ConstantPointerNull::get(
  2305. cast<llvm::PointerType>(destType->getElementType()));
  2306. CGF.Builder.CreateStore(null, temp);
  2307. }
  2308. llvm::BasicBlock *contBB = nullptr;
  2309. llvm::BasicBlock *originBB = nullptr;
  2310. // If the address is *not* known to be non-null, we need to switch.
  2311. llvm::Value *finalArgument;
  2312. bool provablyNonNull = isProvablyNonNull(srcAddr.getPointer());
  2313. if (provablyNonNull) {
  2314. finalArgument = temp.getPointer();
  2315. } else {
  2316. llvm::Value *isNull =
  2317. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  2318. finalArgument = CGF.Builder.CreateSelect(isNull,
  2319. llvm::ConstantPointerNull::get(destType),
  2320. temp.getPointer(), "icr.argument");
  2321. // If we need to copy, then the load has to be conditional, which
  2322. // means we need control flow.
  2323. if (shouldCopy) {
  2324. originBB = CGF.Builder.GetInsertBlock();
  2325. contBB = CGF.createBasicBlock("icr.cont");
  2326. llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
  2327. CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
  2328. CGF.EmitBlock(copyBB);
  2329. condEval.begin(CGF);
  2330. }
  2331. }
  2332. llvm::Value *valueToUse = nullptr;
  2333. // Perform a copy if necessary.
  2334. if (shouldCopy) {
  2335. RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
  2336. assert(srcRV.isScalar());
  2337. llvm::Value *src = srcRV.getScalarVal();
  2338. src = CGF.Builder.CreateBitCast(src, destType->getElementType(),
  2339. "icr.cast");
  2340. // Use an ordinary store, not a store-to-lvalue.
  2341. CGF.Builder.CreateStore(src, temp);
  2342. // If optimization is enabled, and the value was held in a
  2343. // __strong variable, we need to tell the optimizer that this
  2344. // value has to stay alive until we're doing the store back.
  2345. // This is because the temporary is effectively unretained,
  2346. // and so otherwise we can violate the high-level semantics.
  2347. if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  2348. srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
  2349. valueToUse = src;
  2350. }
  2351. }
  2352. // Finish the control flow if we needed it.
  2353. if (shouldCopy && !provablyNonNull) {
  2354. llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
  2355. CGF.EmitBlock(contBB);
  2356. // Make a phi for the value to intrinsically use.
  2357. if (valueToUse) {
  2358. llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
  2359. "icr.to-use");
  2360. phiToUse->addIncoming(valueToUse, copyBB);
  2361. phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
  2362. originBB);
  2363. valueToUse = phiToUse;
  2364. }
  2365. condEval.end(CGF);
  2366. }
  2367. args.addWriteback(srcLV, temp, valueToUse);
  2368. args.add(RValue::get(finalArgument), CRE->getType());
  2369. }
  2370. void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
  2371. assert(!StackBase && !StackCleanup.isValid());
  2372. // Save the stack.
  2373. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  2374. StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
  2375. }
  2376. void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
  2377. if (StackBase) {
  2378. // Restore the stack after the call.
  2379. llvm::Value *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  2380. CGF.Builder.CreateCall(F, StackBase);
  2381. }
  2382. }
  2383. void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
  2384. SourceLocation ArgLoc,
  2385. const FunctionDecl *FD,
  2386. unsigned ParmNum) {
  2387. if (!SanOpts.has(SanitizerKind::NonnullAttribute) || !FD)
  2388. return;
  2389. auto PVD = ParmNum < FD->getNumParams() ? FD->getParamDecl(ParmNum) : nullptr;
  2390. unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
  2391. auto NNAttr = getNonNullAttr(FD, PVD, ArgType, ArgNo);
  2392. if (!NNAttr)
  2393. return;
  2394. SanitizerScope SanScope(this);
  2395. assert(RV.isScalar());
  2396. llvm::Value *V = RV.getScalarVal();
  2397. llvm::Value *Cond =
  2398. Builder.CreateICmpNE(V, llvm::Constant::getNullValue(V->getType()));
  2399. llvm::Constant *StaticData[] = {
  2400. EmitCheckSourceLocation(ArgLoc),
  2401. EmitCheckSourceLocation(NNAttr->getLocation()),
  2402. llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
  2403. };
  2404. EmitCheck(std::make_pair(Cond, SanitizerKind::NonnullAttribute),
  2405. "nonnull_arg", StaticData, None);
  2406. }
  2407. void CodeGenFunction::EmitCallArgs(
  2408. CallArgList &Args, ArrayRef<QualType> ArgTypes,
  2409. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  2410. const FunctionDecl *CalleeDecl, unsigned ParamsToSkip) {
  2411. assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
  2412. // We *have* to evaluate arguments from right to left in the MS C++ ABI,
  2413. // because arguments are destroyed left to right in the callee.
  2414. if (CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  2415. // Insert a stack save if we're going to need any inalloca args.
  2416. bool HasInAllocaArgs = false;
  2417. for (ArrayRef<QualType>::iterator I = ArgTypes.begin(), E = ArgTypes.end();
  2418. I != E && !HasInAllocaArgs; ++I)
  2419. HasInAllocaArgs = isInAllocaArgument(CGM.getCXXABI(), *I);
  2420. if (HasInAllocaArgs) {
  2421. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  2422. Args.allocateArgumentMemory(*this);
  2423. }
  2424. // Evaluate each argument.
  2425. size_t CallArgsStart = Args.size();
  2426. for (int I = ArgTypes.size() - 1; I >= 0; --I) {
  2427. CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
  2428. EmitCallArg(Args, *Arg, ArgTypes[I]);
  2429. EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
  2430. CalleeDecl, ParamsToSkip + I);
  2431. }
  2432. // Un-reverse the arguments we just evaluated so they match up with the LLVM
  2433. // IR function.
  2434. std::reverse(Args.begin() + CallArgsStart, Args.end());
  2435. return;
  2436. }
  2437. for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
  2438. CallExpr::const_arg_iterator Arg = ArgRange.begin() + I;
  2439. assert(Arg != ArgRange.end());
  2440. EmitCallArg(Args, *Arg, ArgTypes[I]);
  2441. EmitNonNullArgCheck(Args.back().RV, ArgTypes[I], (*Arg)->getExprLoc(),
  2442. CalleeDecl, ParamsToSkip + I);
  2443. }
  2444. }
  2445. namespace {
  2446. struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
  2447. DestroyUnpassedArg(Address Addr, QualType Ty)
  2448. : Addr(Addr), Ty(Ty) {}
  2449. Address Addr;
  2450. QualType Ty;
  2451. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2452. const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
  2453. assert(!Dtor->isTrivial());
  2454. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
  2455. /*Delegating=*/false, Addr);
  2456. }
  2457. };
  2458. }
  2459. struct DisableDebugLocationUpdates {
  2460. CodeGenFunction &CGF;
  2461. bool disabledDebugInfo;
  2462. DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
  2463. if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
  2464. CGF.disableDebugInfo();
  2465. }
  2466. ~DisableDebugLocationUpdates() {
  2467. if (disabledDebugInfo)
  2468. CGF.enableDebugInfo();
  2469. }
  2470. };
  2471. void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
  2472. QualType type) {
  2473. DisableDebugLocationUpdates Dis(*this, E);
  2474. if (const ObjCIndirectCopyRestoreExpr *CRE
  2475. = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
  2476. assert(getLangOpts().ObjCAutoRefCount);
  2477. assert(getContext().hasSameType(E->getType(), type));
  2478. return emitWritebackArg(*this, args, CRE);
  2479. }
  2480. assert(type->isReferenceType() == E->isGLValue() &&
  2481. "reference binding to unmaterialized r-value!");
  2482. if (E->isGLValue()) {
  2483. assert(E->getObjectKind() == OK_Ordinary);
  2484. return args.add(EmitReferenceBindingToExpr(E), type);
  2485. }
  2486. bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
  2487. // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
  2488. // However, we still have to push an EH-only cleanup in case we unwind before
  2489. // we make it to the call.
  2490. if (HasAggregateEvalKind &&
  2491. CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  2492. // If we're using inalloca, use the argument memory. Otherwise, use a
  2493. // temporary.
  2494. AggValueSlot Slot;
  2495. if (args.isUsingInAlloca())
  2496. Slot = createPlaceholderSlot(*this, type);
  2497. else
  2498. Slot = CreateAggTemp(type, "agg.tmp");
  2499. const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
  2500. bool DestroyedInCallee =
  2501. RD && RD->hasNonTrivialDestructor() &&
  2502. CGM.getCXXABI().getRecordArgABI(RD) != CGCXXABI::RAA_Default;
  2503. if (DestroyedInCallee)
  2504. Slot.setExternallyDestructed();
  2505. EmitAggExpr(E, Slot);
  2506. RValue RV = Slot.asRValue();
  2507. args.add(RV, type);
  2508. if (DestroyedInCallee) {
  2509. // Create a no-op GEP between the placeholder and the cleanup so we can
  2510. // RAUW it successfully. It also serves as a marker of the first
  2511. // instruction where the cleanup is active.
  2512. pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
  2513. type);
  2514. // This unreachable is a temporary marker which will be removed later.
  2515. llvm::Instruction *IsActive = Builder.CreateUnreachable();
  2516. args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
  2517. }
  2518. return;
  2519. }
  2520. if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
  2521. cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
  2522. LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
  2523. assert(L.isSimple());
  2524. if (L.getAlignment() >= getContext().getTypeAlignInChars(type)) {
  2525. args.add(L.asAggregateRValue(), type, /*NeedsCopy*/true);
  2526. } else {
  2527. // We can't represent a misaligned lvalue in the CallArgList, so copy
  2528. // to an aligned temporary now.
  2529. Address tmp = CreateMemTemp(type);
  2530. EmitAggregateCopy(tmp, L.getAddress(), type, L.isVolatile());
  2531. args.add(RValue::getAggregate(tmp), type);
  2532. }
  2533. return;
  2534. }
  2535. args.add(EmitAnyExprToTemp(E), type);
  2536. }
  2537. QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
  2538. // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
  2539. // implicitly widens null pointer constants that are arguments to varargs
  2540. // functions to pointer-sized ints.
  2541. if (!getTarget().getTriple().isOSWindows())
  2542. return Arg->getType();
  2543. if (Arg->getType()->isIntegerType() &&
  2544. getContext().getTypeSize(Arg->getType()) <
  2545. getContext().getTargetInfo().getPointerWidth(0) &&
  2546. Arg->isNullPointerConstant(getContext(),
  2547. Expr::NPC_ValueDependentIsNotNull)) {
  2548. return getContext().getIntPtrType();
  2549. }
  2550. return Arg->getType();
  2551. }
  2552. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  2553. // optimizer it can aggressively ignore unwind edges.
  2554. void
  2555. CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
  2556. if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  2557. !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
  2558. Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
  2559. CGM.getNoObjCARCExceptionsMetadata());
  2560. }
  2561. /// Emits a call to the given no-arguments nounwind runtime function.
  2562. llvm::CallInst *
  2563. CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
  2564. const llvm::Twine &name) {
  2565. return EmitNounwindRuntimeCall(callee, None, name);
  2566. }
  2567. /// Emits a call to the given nounwind runtime function.
  2568. llvm::CallInst *
  2569. CodeGenFunction::EmitNounwindRuntimeCall(llvm::Value *callee,
  2570. ArrayRef<llvm::Value*> args,
  2571. const llvm::Twine &name) {
  2572. llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
  2573. call->setDoesNotThrow();
  2574. return call;
  2575. }
  2576. /// Emits a simple call (never an invoke) to the given no-arguments
  2577. /// runtime function.
  2578. llvm::CallInst *
  2579. CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
  2580. const llvm::Twine &name) {
  2581. return EmitRuntimeCall(callee, None, name);
  2582. }
  2583. /// Emits a simple call (never an invoke) to the given runtime
  2584. /// function.
  2585. llvm::CallInst *
  2586. CodeGenFunction::EmitRuntimeCall(llvm::Value *callee,
  2587. ArrayRef<llvm::Value*> args,
  2588. const llvm::Twine &name) {
  2589. llvm::CallInst *call = Builder.CreateCall(callee, args, name);
  2590. call->setCallingConv(getRuntimeCC());
  2591. return call;
  2592. }
  2593. /// Emits a call or invoke to the given noreturn runtime function.
  2594. void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(llvm::Value *callee,
  2595. ArrayRef<llvm::Value*> args) {
  2596. if (getInvokeDest()) {
  2597. llvm::InvokeInst *invoke =
  2598. Builder.CreateInvoke(callee,
  2599. getUnreachableBlock(),
  2600. getInvokeDest(),
  2601. args);
  2602. invoke->setDoesNotReturn();
  2603. invoke->setCallingConv(getRuntimeCC());
  2604. } else {
  2605. llvm::CallInst *call = Builder.CreateCall(callee, args);
  2606. call->setDoesNotReturn();
  2607. call->setCallingConv(getRuntimeCC());
  2608. Builder.CreateUnreachable();
  2609. }
  2610. }
  2611. /// Emits a call or invoke instruction to the given nullary runtime
  2612. /// function.
  2613. llvm::CallSite
  2614. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2615. const Twine &name) {
  2616. return EmitRuntimeCallOrInvoke(callee, None, name);
  2617. }
  2618. /// Emits a call or invoke instruction to the given runtime function.
  2619. llvm::CallSite
  2620. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::Value *callee,
  2621. ArrayRef<llvm::Value*> args,
  2622. const Twine &name) {
  2623. llvm::CallSite callSite = EmitCallOrInvoke(callee, args, name);
  2624. callSite.setCallingConv(getRuntimeCC());
  2625. return callSite;
  2626. }
  2627. /// Emits a call or invoke instruction to the given function, depending
  2628. /// on the current state of the EH stack.
  2629. llvm::CallSite
  2630. CodeGenFunction::EmitCallOrInvoke(llvm::Value *Callee,
  2631. ArrayRef<llvm::Value *> Args,
  2632. const Twine &Name) {
  2633. llvm::BasicBlock *InvokeDest = getInvokeDest();
  2634. llvm::Instruction *Inst;
  2635. if (!InvokeDest)
  2636. Inst = Builder.CreateCall(Callee, Args, Name);
  2637. else {
  2638. llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
  2639. Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, Name);
  2640. EmitBlock(ContBB);
  2641. }
  2642. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  2643. // optimizer it can aggressively ignore unwind edges.
  2644. if (CGM.getLangOpts().ObjCAutoRefCount)
  2645. AddObjCARCExceptionMetadata(Inst);
  2646. return llvm::CallSite(Inst);
  2647. }
  2648. /// \brief Store a non-aggregate value to an address to initialize it. For
  2649. /// initialization, a non-atomic store will be used.
  2650. static void EmitInitStoreOfNonAggregate(CodeGenFunction &CGF, RValue Src,
  2651. LValue Dst) {
  2652. if (Src.isScalar())
  2653. CGF.EmitStoreOfScalar(Src.getScalarVal(), Dst, /*init=*/true);
  2654. else
  2655. CGF.EmitStoreOfComplex(Src.getComplexVal(), Dst, /*init=*/true);
  2656. }
  2657. void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
  2658. llvm::Value *New) {
  2659. DeferredReplacements.push_back(std::make_pair(Old, New));
  2660. }
  2661. RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
  2662. llvm::Value *Callee,
  2663. ReturnValueSlot ReturnValue,
  2664. const CallArgList &CallArgs,
  2665. const Decl *TargetDecl,
  2666. llvm::Instruction **callOrInvoke) {
  2667. // FIXME: We no longer need the types from CallArgs; lift up and simplify.
  2668. // Handle struct-return functions by passing a pointer to the
  2669. // location that we would like to return into.
  2670. QualType RetTy = CallInfo.getReturnType();
  2671. const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
  2672. llvm::FunctionType *IRFuncTy =
  2673. cast<llvm::FunctionType>(
  2674. cast<llvm::PointerType>(Callee->getType())->getElementType());
  2675. // If we're using inalloca, insert the allocation after the stack save.
  2676. // FIXME: Do this earlier rather than hacking it in here!
  2677. Address ArgMemory = Address::invalid();
  2678. const llvm::StructLayout *ArgMemoryLayout = nullptr;
  2679. if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
  2680. ArgMemoryLayout = CGM.getDataLayout().getStructLayout(ArgStruct);
  2681. llvm::Instruction *IP = CallArgs.getStackBase();
  2682. llvm::AllocaInst *AI;
  2683. if (IP) {
  2684. IP = IP->getNextNode();
  2685. AI = new llvm::AllocaInst(ArgStruct, "argmem", IP);
  2686. } else {
  2687. AI = CreateTempAlloca(ArgStruct, "argmem");
  2688. }
  2689. auto Align = CallInfo.getArgStructAlignment();
  2690. AI->setAlignment(Align.getQuantity());
  2691. AI->setUsedWithInAlloca(true);
  2692. assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
  2693. ArgMemory = Address(AI, Align);
  2694. }
  2695. // Helper function to drill into the inalloca allocation.
  2696. auto createInAllocaStructGEP = [&](unsigned FieldIndex) -> Address {
  2697. auto FieldOffset =
  2698. CharUnits::fromQuantity(ArgMemoryLayout->getElementOffset(FieldIndex));
  2699. return Builder.CreateStructGEP(ArgMemory, FieldIndex, FieldOffset);
  2700. };
  2701. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
  2702. SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
  2703. // If the call returns a temporary with struct return, create a temporary
  2704. // alloca to hold the result, unless one is given to us.
  2705. Address SRetPtr = Address::invalid();
  2706. size_t UnusedReturnSize = 0;
  2707. if (RetAI.isIndirect() || RetAI.isInAlloca()) {
  2708. if (!ReturnValue.isNull()) {
  2709. SRetPtr = ReturnValue.getValue();
  2710. } else {
  2711. SRetPtr = CreateMemTemp(RetTy);
  2712. if (HaveInsertPoint() && ReturnValue.isUnused()) {
  2713. uint64_t size =
  2714. CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
  2715. if (EmitLifetimeStart(size, SRetPtr.getPointer()))
  2716. UnusedReturnSize = size;
  2717. }
  2718. }
  2719. if (IRFunctionArgs.hasSRetArg()) {
  2720. IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
  2721. } else {
  2722. Address Addr = createInAllocaStructGEP(RetAI.getInAllocaFieldIndex());
  2723. Builder.CreateStore(SRetPtr.getPointer(), Addr);
  2724. }
  2725. }
  2726. assert(CallInfo.arg_size() == CallArgs.size() &&
  2727. "Mismatch between function signature & arguments.");
  2728. unsigned ArgNo = 0;
  2729. CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
  2730. for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
  2731. I != E; ++I, ++info_it, ++ArgNo) {
  2732. const ABIArgInfo &ArgInfo = info_it->info;
  2733. RValue RV = I->RV;
  2734. // Insert a padding argument to ensure proper alignment.
  2735. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  2736. IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  2737. llvm::UndefValue::get(ArgInfo.getPaddingType());
  2738. unsigned FirstIRArg, NumIRArgs;
  2739. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  2740. switch (ArgInfo.getKind()) {
  2741. case ABIArgInfo::InAlloca: {
  2742. assert(NumIRArgs == 0);
  2743. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  2744. if (RV.isAggregate()) {
  2745. // Replace the placeholder with the appropriate argument slot GEP.
  2746. llvm::Instruction *Placeholder =
  2747. cast<llvm::Instruction>(RV.getAggregatePointer());
  2748. CGBuilderTy::InsertPoint IP = Builder.saveIP();
  2749. Builder.SetInsertPoint(Placeholder);
  2750. Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
  2751. Builder.restoreIP(IP);
  2752. deferPlaceholderReplacement(Placeholder, Addr.getPointer());
  2753. } else {
  2754. // Store the RValue into the argument struct.
  2755. Address Addr = createInAllocaStructGEP(ArgInfo.getInAllocaFieldIndex());
  2756. unsigned AS = Addr.getType()->getPointerAddressSpace();
  2757. llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
  2758. // There are some cases where a trivial bitcast is not avoidable. The
  2759. // definition of a type later in a translation unit may change it's type
  2760. // from {}* to (%struct.foo*)*.
  2761. if (Addr.getType() != MemType)
  2762. Addr = Builder.CreateBitCast(Addr, MemType);
  2763. LValue argLV = MakeAddrLValue(Addr, I->Ty);
  2764. EmitInitStoreOfNonAggregate(*this, RV, argLV);
  2765. }
  2766. break;
  2767. }
  2768. case ABIArgInfo::Indirect: {
  2769. assert(NumIRArgs == 1);
  2770. if (RV.isScalar() || RV.isComplex()) {
  2771. // Make a temporary alloca to pass the argument.
  2772. Address Addr = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
  2773. IRCallArgs[FirstIRArg] = Addr.getPointer();
  2774. LValue argLV = MakeAddrLValue(Addr, I->Ty);
  2775. EmitInitStoreOfNonAggregate(*this, RV, argLV);
  2776. } else {
  2777. // We want to avoid creating an unnecessary temporary+copy here;
  2778. // however, we need one in three cases:
  2779. // 1. If the argument is not byval, and we are required to copy the
  2780. // source. (This case doesn't occur on any common architecture.)
  2781. // 2. If the argument is byval, RV is not sufficiently aligned, and
  2782. // we cannot force it to be sufficiently aligned.
  2783. // 3. If the argument is byval, but RV is located in an address space
  2784. // different than that of the argument (0).
  2785. Address Addr = RV.getAggregateAddress();
  2786. CharUnits Align = ArgInfo.getIndirectAlign();
  2787. const llvm::DataLayout *TD = &CGM.getDataLayout();
  2788. const unsigned RVAddrSpace = Addr.getType()->getAddressSpace();
  2789. const unsigned ArgAddrSpace =
  2790. (FirstIRArg < IRFuncTy->getNumParams()
  2791. ? IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace()
  2792. : 0);
  2793. if ((!ArgInfo.getIndirectByVal() && I->NeedsCopy) ||
  2794. (ArgInfo.getIndirectByVal() && Addr.getAlignment() < Align &&
  2795. llvm::getOrEnforceKnownAlignment(Addr.getPointer(),
  2796. Align.getQuantity(), *TD)
  2797. < Align.getQuantity()) ||
  2798. (ArgInfo.getIndirectByVal() && (RVAddrSpace != ArgAddrSpace))) {
  2799. // Create an aligned temporary, and copy to it.
  2800. Address AI = CreateMemTemp(I->Ty, ArgInfo.getIndirectAlign());
  2801. IRCallArgs[FirstIRArg] = AI.getPointer();
  2802. EmitAggregateCopy(AI, Addr, I->Ty, RV.isVolatileQualified());
  2803. } else {
  2804. // Skip the extra memcpy call.
  2805. IRCallArgs[FirstIRArg] = Addr.getPointer();
  2806. }
  2807. }
  2808. break;
  2809. }
  2810. case ABIArgInfo::Ignore:
  2811. assert(NumIRArgs == 0);
  2812. break;
  2813. case ABIArgInfo::Extend:
  2814. case ABIArgInfo::Direct: {
  2815. if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
  2816. ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
  2817. ArgInfo.getDirectOffset() == 0) {
  2818. assert(NumIRArgs == 1);
  2819. llvm::Value *V;
  2820. if (RV.isScalar())
  2821. V = RV.getScalarVal();
  2822. else
  2823. V = Builder.CreateLoad(RV.getAggregateAddress());
  2824. // We might have to widen integers, but we should never truncate.
  2825. if (ArgInfo.getCoerceToType() != V->getType() &&
  2826. V->getType()->isIntegerTy())
  2827. V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
  2828. // If the argument doesn't match, perform a bitcast to coerce it. This
  2829. // can happen due to trivial type mismatches.
  2830. if (FirstIRArg < IRFuncTy->getNumParams() &&
  2831. V->getType() != IRFuncTy->getParamType(FirstIRArg))
  2832. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
  2833. IRCallArgs[FirstIRArg] = V;
  2834. break;
  2835. }
  2836. // FIXME: Avoid the conversion through memory if possible.
  2837. Address Src = Address::invalid();
  2838. if (RV.isScalar() || RV.isComplex()) {
  2839. Src = CreateMemTemp(I->Ty, "coerce");
  2840. LValue SrcLV = MakeAddrLValue(Src, I->Ty);
  2841. EmitInitStoreOfNonAggregate(*this, RV, SrcLV);
  2842. } else {
  2843. Src = RV.getAggregateAddress();
  2844. }
  2845. // If the value is offset in memory, apply the offset now.
  2846. Src = emitAddressAtOffset(*this, Src, ArgInfo);
  2847. // Fast-isel and the optimizer generally like scalar values better than
  2848. // FCAs, so we flatten them if this is safe to do for this argument.
  2849. llvm::StructType *STy =
  2850. dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
  2851. if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  2852. llvm::Type *SrcTy = Src.getType()->getElementType();
  2853. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  2854. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
  2855. // If the source type is smaller than the destination type of the
  2856. // coerce-to logic, copy the source value into a temp alloca the size
  2857. // of the destination type to allow loading all of it. The bits past
  2858. // the source value are left undef.
  2859. if (SrcSize < DstSize) {
  2860. Address TempAlloca
  2861. = CreateTempAlloca(STy, Src.getAlignment(),
  2862. Src.getName() + ".coerce");
  2863. Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
  2864. Src = TempAlloca;
  2865. } else {
  2866. Src = Builder.CreateBitCast(Src, llvm::PointerType::getUnqual(STy));
  2867. }
  2868. auto SrcLayout = CGM.getDataLayout().getStructLayout(STy);
  2869. assert(NumIRArgs == STy->getNumElements());
  2870. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  2871. auto Offset = CharUnits::fromQuantity(SrcLayout->getElementOffset(i));
  2872. Address EltPtr = Builder.CreateStructGEP(Src, i, Offset);
  2873. llvm::Value *LI = Builder.CreateLoad(EltPtr);
  2874. IRCallArgs[FirstIRArg + i] = LI;
  2875. }
  2876. } else {
  2877. // In the simple case, just pass the coerced loaded value.
  2878. assert(NumIRArgs == 1);
  2879. IRCallArgs[FirstIRArg] =
  2880. CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
  2881. }
  2882. break;
  2883. }
  2884. case ABIArgInfo::Expand:
  2885. unsigned IRArgPos = FirstIRArg;
  2886. ExpandTypeToArgs(I->Ty, RV, IRFuncTy, IRCallArgs, IRArgPos);
  2887. assert(IRArgPos == FirstIRArg + NumIRArgs);
  2888. break;
  2889. }
  2890. }
  2891. if (ArgMemory.isValid()) {
  2892. llvm::Value *Arg = ArgMemory.getPointer();
  2893. if (CallInfo.isVariadic()) {
  2894. // When passing non-POD arguments by value to variadic functions, we will
  2895. // end up with a variadic prototype and an inalloca call site. In such
  2896. // cases, we can't do any parameter mismatch checks. Give up and bitcast
  2897. // the callee.
  2898. unsigned CalleeAS =
  2899. cast<llvm::PointerType>(Callee->getType())->getAddressSpace();
  2900. Callee = Builder.CreateBitCast(
  2901. Callee, getTypes().GetFunctionType(CallInfo)->getPointerTo(CalleeAS));
  2902. } else {
  2903. llvm::Type *LastParamTy =
  2904. IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
  2905. if (Arg->getType() != LastParamTy) {
  2906. #ifndef NDEBUG
  2907. // Assert that these structs have equivalent element types.
  2908. llvm::StructType *FullTy = CallInfo.getArgStruct();
  2909. llvm::StructType *DeclaredTy = cast<llvm::StructType>(
  2910. cast<llvm::PointerType>(LastParamTy)->getElementType());
  2911. assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
  2912. for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
  2913. DE = DeclaredTy->element_end(),
  2914. FI = FullTy->element_begin();
  2915. DI != DE; ++DI, ++FI)
  2916. assert(*DI == *FI);
  2917. #endif
  2918. Arg = Builder.CreateBitCast(Arg, LastParamTy);
  2919. }
  2920. }
  2921. assert(IRFunctionArgs.hasInallocaArg());
  2922. IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
  2923. }
  2924. if (!CallArgs.getCleanupsToDeactivate().empty())
  2925. deactivateArgCleanupsBeforeCall(*this, CallArgs);
  2926. // If the callee is a bitcast of a function to a varargs pointer to function
  2927. // type, check to see if we can remove the bitcast. This handles some cases
  2928. // with unprototyped functions.
  2929. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Callee))
  2930. if (llvm::Function *CalleeF = dyn_cast<llvm::Function>(CE->getOperand(0))) {
  2931. llvm::PointerType *CurPT=cast<llvm::PointerType>(Callee->getType());
  2932. llvm::FunctionType *CurFT =
  2933. cast<llvm::FunctionType>(CurPT->getElementType());
  2934. llvm::FunctionType *ActualFT = CalleeF->getFunctionType();
  2935. if (CE->getOpcode() == llvm::Instruction::BitCast &&
  2936. ActualFT->getReturnType() == CurFT->getReturnType() &&
  2937. ActualFT->getNumParams() == CurFT->getNumParams() &&
  2938. ActualFT->getNumParams() == IRCallArgs.size() &&
  2939. (CurFT->isVarArg() || !ActualFT->isVarArg())) {
  2940. bool ArgsMatch = true;
  2941. for (unsigned i = 0, e = ActualFT->getNumParams(); i != e; ++i)
  2942. if (ActualFT->getParamType(i) != CurFT->getParamType(i)) {
  2943. ArgsMatch = false;
  2944. break;
  2945. }
  2946. // Strip the cast if we can get away with it. This is a nice cleanup,
  2947. // but also allows us to inline the function at -O0 if it is marked
  2948. // always_inline.
  2949. if (ArgsMatch)
  2950. Callee = CalleeF;
  2951. }
  2952. }
  2953. assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
  2954. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  2955. // Inalloca argument can have different type.
  2956. if (IRFunctionArgs.hasInallocaArg() &&
  2957. i == IRFunctionArgs.getInallocaArgNo())
  2958. continue;
  2959. if (i < IRFuncTy->getNumParams())
  2960. assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
  2961. }
  2962. unsigned CallingConv;
  2963. CodeGen::AttributeListType AttributeList;
  2964. CGM.ConstructAttributeList(CallInfo, TargetDecl, AttributeList,
  2965. CallingConv, true);
  2966. llvm::AttributeSet Attrs = llvm::AttributeSet::get(getLLVMContext(),
  2967. AttributeList);
  2968. llvm::BasicBlock *InvokeDest = nullptr;
  2969. if (!Attrs.hasAttribute(llvm::AttributeSet::FunctionIndex,
  2970. llvm::Attribute::NoUnwind) ||
  2971. currentFunctionUsesSEHTry())
  2972. InvokeDest = getInvokeDest();
  2973. llvm::CallSite CS;
  2974. if (!InvokeDest) {
  2975. CS = Builder.CreateCall(Callee, IRCallArgs);
  2976. } else {
  2977. llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
  2978. CS = Builder.CreateInvoke(Callee, Cont, InvokeDest, IRCallArgs);
  2979. EmitBlock(Cont);
  2980. }
  2981. if (callOrInvoke)
  2982. *callOrInvoke = CS.getInstruction();
  2983. if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
  2984. !CS.hasFnAttr(llvm::Attribute::NoInline))
  2985. Attrs =
  2986. Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
  2987. llvm::Attribute::AlwaysInline);
  2988. // Disable inlining inside SEH __try blocks.
  2989. if (isSEHTryScope())
  2990. Attrs =
  2991. Attrs.addAttribute(getLLVMContext(), llvm::AttributeSet::FunctionIndex,
  2992. llvm::Attribute::NoInline);
  2993. CS.setAttributes(Attrs);
  2994. CS.setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  2995. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  2996. // optimizer it can aggressively ignore unwind edges.
  2997. if (CGM.getLangOpts().ObjCAutoRefCount)
  2998. AddObjCARCExceptionMetadata(CS.getInstruction());
  2999. // If the call doesn't return, finish the basic block and clear the
  3000. // insertion point; this allows the rest of IRgen to discard
  3001. // unreachable code.
  3002. if (CS.doesNotReturn()) {
  3003. if (UnusedReturnSize)
  3004. EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
  3005. SRetPtr.getPointer());
  3006. Builder.CreateUnreachable();
  3007. Builder.ClearInsertionPoint();
  3008. // FIXME: For now, emit a dummy basic block because expr emitters in
  3009. // generally are not ready to handle emitting expressions at unreachable
  3010. // points.
  3011. EnsureInsertPoint();
  3012. // Return a reasonable RValue.
  3013. return GetUndefRValue(RetTy);
  3014. }
  3015. llvm::Instruction *CI = CS.getInstruction();
  3016. if (Builder.isNamePreserving() && !CI->getType()->isVoidTy())
  3017. CI->setName("call");
  3018. // Emit any writebacks immediately. Arguably this should happen
  3019. // after any return-value munging.
  3020. if (CallArgs.hasWritebacks())
  3021. emitWritebacks(*this, CallArgs);
  3022. // The stack cleanup for inalloca arguments has to run out of the normal
  3023. // lexical order, so deactivate it and run it manually here.
  3024. CallArgs.freeArgumentMemory(*this);
  3025. RValue Ret = [&] {
  3026. switch (RetAI.getKind()) {
  3027. case ABIArgInfo::InAlloca:
  3028. case ABIArgInfo::Indirect: {
  3029. RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
  3030. if (UnusedReturnSize)
  3031. EmitLifetimeEnd(llvm::ConstantInt::get(Int64Ty, UnusedReturnSize),
  3032. SRetPtr.getPointer());
  3033. return ret;
  3034. }
  3035. case ABIArgInfo::Ignore:
  3036. // If we are ignoring an argument that had a result, make sure to
  3037. // construct the appropriate return value for our caller.
  3038. return GetUndefRValue(RetTy);
  3039. case ABIArgInfo::Extend:
  3040. case ABIArgInfo::Direct: {
  3041. llvm::Type *RetIRTy = ConvertType(RetTy);
  3042. if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
  3043. switch (getEvaluationKind(RetTy)) {
  3044. case TEK_Complex: {
  3045. llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
  3046. llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
  3047. return RValue::getComplex(std::make_pair(Real, Imag));
  3048. }
  3049. case TEK_Aggregate: {
  3050. Address DestPtr = ReturnValue.getValue();
  3051. bool DestIsVolatile = ReturnValue.isVolatile();
  3052. if (!DestPtr.isValid()) {
  3053. DestPtr = CreateMemTemp(RetTy, "agg.tmp");
  3054. DestIsVolatile = false;
  3055. }
  3056. BuildAggStore(*this, CI, DestPtr, DestIsVolatile);
  3057. return RValue::getAggregate(DestPtr);
  3058. }
  3059. case TEK_Scalar: {
  3060. // If the argument doesn't match, perform a bitcast to coerce it. This
  3061. // can happen due to trivial type mismatches.
  3062. llvm::Value *V = CI;
  3063. if (V->getType() != RetIRTy)
  3064. V = Builder.CreateBitCast(V, RetIRTy);
  3065. return RValue::get(V);
  3066. }
  3067. }
  3068. llvm_unreachable("bad evaluation kind");
  3069. }
  3070. Address DestPtr = ReturnValue.getValue();
  3071. bool DestIsVolatile = ReturnValue.isVolatile();
  3072. if (!DestPtr.isValid()) {
  3073. DestPtr = CreateMemTemp(RetTy, "coerce");
  3074. DestIsVolatile = false;
  3075. }
  3076. // If the value is offset in memory, apply the offset now.
  3077. Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
  3078. CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
  3079. return convertTempToRValue(DestPtr, RetTy, SourceLocation());
  3080. }
  3081. case ABIArgInfo::Expand:
  3082. llvm_unreachable("Invalid ABI kind for return argument");
  3083. }
  3084. llvm_unreachable("Unhandled ABIArgInfo::Kind");
  3085. } ();
  3086. if (Ret.isScalar() && TargetDecl) {
  3087. if (const auto *AA = TargetDecl->getAttr<AssumeAlignedAttr>()) {
  3088. llvm::Value *OffsetValue = nullptr;
  3089. if (const auto *Offset = AA->getOffset())
  3090. OffsetValue = EmitScalarExpr(Offset);
  3091. llvm::Value *Alignment = EmitScalarExpr(AA->getAlignment());
  3092. llvm::ConstantInt *AlignmentCI = cast<llvm::ConstantInt>(Alignment);
  3093. EmitAlignmentAssumption(Ret.getScalarVal(), AlignmentCI->getZExtValue(),
  3094. OffsetValue);
  3095. }
  3096. }
  3097. return Ret;
  3098. }
  3099. /* VarArg handling */
  3100. Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
  3101. VAListAddr = VE->isMicrosoftABI()
  3102. ? EmitMSVAListRef(VE->getSubExpr())
  3103. : EmitVAListRef(VE->getSubExpr());
  3104. QualType Ty = VE->getType();
  3105. if (VE->isMicrosoftABI())
  3106. return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
  3107. return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
  3108. }