CGCall.cpp 144 KB

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