CGCall.cpp 215 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539
  1. //===--- CGCall.cpp - Encapsulate calling convention details --------------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // These classes wrap the information about a call or function
  10. // definition used to handle ABI compliancy.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "CGCall.h"
  14. #include "ABIInfo.h"
  15. #include "CGBlocks.h"
  16. #include "CGCXXABI.h"
  17. #include "CGCleanup.h"
  18. #include "CGRecordLayout.h"
  19. #include "CodeGenFunction.h"
  20. #include "CodeGenModule.h"
  21. #include "TargetInfo.h"
  22. #include "clang/AST/Attr.h"
  23. #include "clang/AST/Decl.h"
  24. #include "clang/AST/DeclCXX.h"
  25. #include "clang/AST/DeclObjC.h"
  26. #include "clang/Basic/CodeGenOptions.h"
  27. #include "clang/Basic/TargetBuiltins.h"
  28. #include "clang/Basic/TargetInfo.h"
  29. #include "clang/CodeGen/CGFunctionInfo.h"
  30. #include "clang/CodeGen/SwiftCallingConv.h"
  31. #include "llvm/ADT/StringExtras.h"
  32. #include "llvm/Analysis/ValueTracking.h"
  33. #include "llvm/IR/Assumptions.h"
  34. #include "llvm/IR/Attributes.h"
  35. #include "llvm/IR/CallingConv.h"
  36. #include "llvm/IR/DataLayout.h"
  37. #include "llvm/IR/InlineAsm.h"
  38. #include "llvm/IR/IntrinsicInst.h"
  39. #include "llvm/IR/Intrinsics.h"
  40. #include "llvm/IR/Type.h"
  41. #include "llvm/Transforms/Utils/Local.h"
  42. using namespace clang;
  43. using namespace CodeGen;
  44. /***/
  45. unsigned CodeGenTypes::ClangCallConvToLLVMCallConv(CallingConv CC) {
  46. switch (CC) {
  47. default: return llvm::CallingConv::C;
  48. case CC_X86StdCall: return llvm::CallingConv::X86_StdCall;
  49. case CC_X86FastCall: return llvm::CallingConv::X86_FastCall;
  50. case CC_X86RegCall: return llvm::CallingConv::X86_RegCall;
  51. case CC_X86ThisCall: return llvm::CallingConv::X86_ThisCall;
  52. case CC_Win64: return llvm::CallingConv::Win64;
  53. case CC_X86_64SysV: return llvm::CallingConv::X86_64_SysV;
  54. case CC_AAPCS: return llvm::CallingConv::ARM_AAPCS;
  55. case CC_AAPCS_VFP: return llvm::CallingConv::ARM_AAPCS_VFP;
  56. case CC_IntelOclBicc: return llvm::CallingConv::Intel_OCL_BI;
  57. // TODO: Add support for __pascal to LLVM.
  58. case CC_X86Pascal: return llvm::CallingConv::C;
  59. // TODO: Add support for __vectorcall to LLVM.
  60. case CC_X86VectorCall: return llvm::CallingConv::X86_VectorCall;
  61. case CC_AArch64VectorCall: return llvm::CallingConv::AArch64_VectorCall;
  62. case CC_SpirFunction: return llvm::CallingConv::SPIR_FUNC;
  63. case CC_OpenCLKernel: return CGM.getTargetCodeGenInfo().getOpenCLKernelCallingConv();
  64. case CC_PreserveMost: return llvm::CallingConv::PreserveMost;
  65. case CC_PreserveAll: return llvm::CallingConv::PreserveAll;
  66. case CC_Swift: return llvm::CallingConv::Swift;
  67. case CC_SwiftAsync: return llvm::CallingConv::SwiftTail;
  68. }
  69. }
  70. /// Derives the 'this' type for codegen purposes, i.e. ignoring method CVR
  71. /// qualification. Either or both of RD and MD may be null. A null RD indicates
  72. /// that there is no meaningful 'this' type, and a null MD can occur when
  73. /// calling a method pointer.
  74. CanQualType CodeGenTypes::DeriveThisType(const CXXRecordDecl *RD,
  75. const CXXMethodDecl *MD) {
  76. QualType RecTy;
  77. if (RD)
  78. RecTy = Context.getTagDeclType(RD)->getCanonicalTypeInternal();
  79. else
  80. RecTy = Context.VoidTy;
  81. if (MD)
  82. RecTy = Context.getAddrSpaceQualType(RecTy, MD->getMethodQualifiers().getAddressSpace());
  83. return Context.getPointerType(CanQualType::CreateUnsafe(RecTy));
  84. }
  85. /// Returns the canonical formal type of the given C++ method.
  86. static CanQual<FunctionProtoType> GetFormalType(const CXXMethodDecl *MD) {
  87. return MD->getType()->getCanonicalTypeUnqualified()
  88. .getAs<FunctionProtoType>();
  89. }
  90. /// Returns the "extra-canonicalized" return type, which discards
  91. /// qualifiers on the return type. Codegen doesn't care about them,
  92. /// and it makes ABI code a little easier to be able to assume that
  93. /// all parameter and return types are top-level unqualified.
  94. static CanQualType GetReturnType(QualType RetTy) {
  95. return RetTy->getCanonicalTypeUnqualified().getUnqualifiedType();
  96. }
  97. /// Arrange the argument and result information for a value of the given
  98. /// unprototyped freestanding function type.
  99. const CGFunctionInfo &
  100. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
  101. // When translating an unprototyped function type, always use a
  102. // variadic type.
  103. return arrangeLLVMFunctionInfo(FTNP->getReturnType().getUnqualifiedType(),
  104. /*instanceMethod=*/false,
  105. /*chainCall=*/false, None,
  106. FTNP->getExtInfo(), {}, RequiredArgs(0));
  107. }
  108. static void addExtParameterInfosForCall(
  109. llvm::SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
  110. const FunctionProtoType *proto,
  111. unsigned prefixArgs,
  112. unsigned totalArgs) {
  113. assert(proto->hasExtParameterInfos());
  114. assert(paramInfos.size() <= prefixArgs);
  115. assert(proto->getNumParams() + prefixArgs <= totalArgs);
  116. paramInfos.reserve(totalArgs);
  117. // Add default infos for any prefix args that don't already have infos.
  118. paramInfos.resize(prefixArgs);
  119. // Add infos for the prototype.
  120. for (const auto &ParamInfo : proto->getExtParameterInfos()) {
  121. paramInfos.push_back(ParamInfo);
  122. // pass_object_size params have no parameter info.
  123. if (ParamInfo.hasPassObjectSize())
  124. paramInfos.emplace_back();
  125. }
  126. assert(paramInfos.size() <= totalArgs &&
  127. "Did we forget to insert pass_object_size args?");
  128. // Add default infos for the variadic and/or suffix arguments.
  129. paramInfos.resize(totalArgs);
  130. }
  131. /// Adds the formal parameters in FPT to the given prefix. If any parameter in
  132. /// FPT has pass_object_size attrs, then we'll add parameters for those, too.
  133. static void appendParameterTypes(const CodeGenTypes &CGT,
  134. SmallVectorImpl<CanQualType> &prefix,
  135. SmallVectorImpl<FunctionProtoType::ExtParameterInfo> &paramInfos,
  136. CanQual<FunctionProtoType> FPT) {
  137. // Fast path: don't touch param info if we don't need to.
  138. if (!FPT->hasExtParameterInfos()) {
  139. assert(paramInfos.empty() &&
  140. "We have paramInfos, but the prototype doesn't?");
  141. prefix.append(FPT->param_type_begin(), FPT->param_type_end());
  142. return;
  143. }
  144. unsigned PrefixSize = prefix.size();
  145. // In the vast majority of cases, we'll have precisely FPT->getNumParams()
  146. // parameters; the only thing that can change this is the presence of
  147. // pass_object_size. So, we preallocate for the common case.
  148. prefix.reserve(prefix.size() + FPT->getNumParams());
  149. auto ExtInfos = FPT->getExtParameterInfos();
  150. assert(ExtInfos.size() == FPT->getNumParams());
  151. for (unsigned I = 0, E = FPT->getNumParams(); I != E; ++I) {
  152. prefix.push_back(FPT->getParamType(I));
  153. if (ExtInfos[I].hasPassObjectSize())
  154. prefix.push_back(CGT.getContext().getSizeType());
  155. }
  156. addExtParameterInfosForCall(paramInfos, FPT.getTypePtr(), PrefixSize,
  157. prefix.size());
  158. }
  159. /// Arrange the LLVM function layout for a value of the given function
  160. /// type, on top of any implicit parameters already stored.
  161. static const CGFunctionInfo &
  162. arrangeLLVMFunctionInfo(CodeGenTypes &CGT, bool instanceMethod,
  163. SmallVectorImpl<CanQualType> &prefix,
  164. CanQual<FunctionProtoType> FTP) {
  165. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  166. RequiredArgs Required = RequiredArgs::forPrototypePlus(FTP, prefix.size());
  167. // FIXME: Kill copy.
  168. appendParameterTypes(CGT, prefix, paramInfos, FTP);
  169. CanQualType resultType = FTP->getReturnType().getUnqualifiedType();
  170. return CGT.arrangeLLVMFunctionInfo(resultType, instanceMethod,
  171. /*chainCall=*/false, prefix,
  172. FTP->getExtInfo(), paramInfos,
  173. Required);
  174. }
  175. /// Arrange the argument and result information for a value of the
  176. /// given freestanding function type.
  177. const CGFunctionInfo &
  178. CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionProtoType> FTP) {
  179. SmallVector<CanQualType, 16> argTypes;
  180. return ::arrangeLLVMFunctionInfo(*this, /*instanceMethod=*/false, argTypes,
  181. FTP);
  182. }
  183. static CallingConv getCallingConventionForDecl(const ObjCMethodDecl *D,
  184. bool IsWindows) {
  185. // Set the appropriate calling convention for the Function.
  186. if (D->hasAttr<StdCallAttr>())
  187. return CC_X86StdCall;
  188. if (D->hasAttr<FastCallAttr>())
  189. return CC_X86FastCall;
  190. if (D->hasAttr<RegCallAttr>())
  191. return CC_X86RegCall;
  192. if (D->hasAttr<ThisCallAttr>())
  193. return CC_X86ThisCall;
  194. if (D->hasAttr<VectorCallAttr>())
  195. return CC_X86VectorCall;
  196. if (D->hasAttr<PascalAttr>())
  197. return CC_X86Pascal;
  198. if (PcsAttr *PCS = D->getAttr<PcsAttr>())
  199. return (PCS->getPCS() == PcsAttr::AAPCS ? CC_AAPCS : CC_AAPCS_VFP);
  200. if (D->hasAttr<AArch64VectorPcsAttr>())
  201. return CC_AArch64VectorCall;
  202. if (D->hasAttr<IntelOclBiccAttr>())
  203. return CC_IntelOclBicc;
  204. if (D->hasAttr<MSABIAttr>())
  205. return IsWindows ? CC_C : CC_Win64;
  206. if (D->hasAttr<SysVABIAttr>())
  207. return IsWindows ? CC_X86_64SysV : CC_C;
  208. if (D->hasAttr<PreserveMostAttr>())
  209. return CC_PreserveMost;
  210. if (D->hasAttr<PreserveAllAttr>())
  211. return CC_PreserveAll;
  212. return CC_C;
  213. }
  214. /// Arrange the argument and result information for a call to an
  215. /// unknown C++ non-static member function of the given abstract type.
  216. /// (A null RD means we don't have any meaningful "this" argument type,
  217. /// so fall back to a generic pointer type).
  218. /// The member function must be an ordinary function, i.e. not a
  219. /// constructor or destructor.
  220. const CGFunctionInfo &
  221. CodeGenTypes::arrangeCXXMethodType(const CXXRecordDecl *RD,
  222. const FunctionProtoType *FTP,
  223. const CXXMethodDecl *MD) {
  224. SmallVector<CanQualType, 16> argTypes;
  225. // Add the 'this' pointer.
  226. argTypes.push_back(DeriveThisType(RD, MD));
  227. return ::arrangeLLVMFunctionInfo(
  228. *this, true, argTypes,
  229. FTP->getCanonicalTypeUnqualified().getAs<FunctionProtoType>());
  230. }
  231. /// Set calling convention for CUDA/HIP kernel.
  232. static void setCUDAKernelCallingConvention(CanQualType &FTy, CodeGenModule &CGM,
  233. const FunctionDecl *FD) {
  234. if (FD->hasAttr<CUDAGlobalAttr>()) {
  235. const FunctionType *FT = FTy->getAs<FunctionType>();
  236. CGM.getTargetCodeGenInfo().setCUDAKernelCallingConvention(FT);
  237. FTy = FT->getCanonicalTypeUnqualified();
  238. }
  239. }
  240. /// Arrange the argument and result information for a declaration or
  241. /// definition of the given C++ non-static member function. The
  242. /// member function must be an ordinary function, i.e. not a
  243. /// constructor or destructor.
  244. const CGFunctionInfo &
  245. CodeGenTypes::arrangeCXXMethodDeclaration(const CXXMethodDecl *MD) {
  246. assert(!isa<CXXConstructorDecl>(MD) && "wrong method for constructors!");
  247. assert(!isa<CXXDestructorDecl>(MD) && "wrong method for destructors!");
  248. CanQualType FT = GetFormalType(MD).getAs<Type>();
  249. setCUDAKernelCallingConvention(FT, CGM, MD);
  250. auto prototype = FT.getAs<FunctionProtoType>();
  251. if (MD->isInstance()) {
  252. // The abstract case is perfectly fine.
  253. const CXXRecordDecl *ThisType = TheCXXABI.getThisArgumentTypeForMethod(MD);
  254. return arrangeCXXMethodType(ThisType, prototype.getTypePtr(), MD);
  255. }
  256. return arrangeFreeFunctionType(prototype);
  257. }
  258. bool CodeGenTypes::inheritingCtorHasParams(
  259. const InheritedConstructor &Inherited, CXXCtorType Type) {
  260. // Parameters are unnecessary if we're constructing a base class subobject
  261. // and the inherited constructor lives in a virtual base.
  262. return Type == Ctor_Complete ||
  263. !Inherited.getShadowDecl()->constructsVirtualBase() ||
  264. !Target.getCXXABI().hasConstructorVariants();
  265. }
  266. const CGFunctionInfo &
  267. CodeGenTypes::arrangeCXXStructorDeclaration(GlobalDecl GD) {
  268. auto *MD = cast<CXXMethodDecl>(GD.getDecl());
  269. SmallVector<CanQualType, 16> argTypes;
  270. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  271. argTypes.push_back(DeriveThisType(MD->getParent(), MD));
  272. bool PassParams = true;
  273. if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
  274. // A base class inheriting constructor doesn't get forwarded arguments
  275. // needed to construct a virtual base (or base class thereof).
  276. if (auto Inherited = CD->getInheritedConstructor())
  277. PassParams = inheritingCtorHasParams(Inherited, GD.getCtorType());
  278. }
  279. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  280. // Add the formal parameters.
  281. if (PassParams)
  282. appendParameterTypes(*this, argTypes, paramInfos, FTP);
  283. CGCXXABI::AddedStructorArgCounts AddedArgs =
  284. TheCXXABI.buildStructorSignature(GD, argTypes);
  285. if (!paramInfos.empty()) {
  286. // Note: prefix implies after the first param.
  287. if (AddedArgs.Prefix)
  288. paramInfos.insert(paramInfos.begin() + 1, AddedArgs.Prefix,
  289. FunctionProtoType::ExtParameterInfo{});
  290. if (AddedArgs.Suffix)
  291. paramInfos.append(AddedArgs.Suffix,
  292. FunctionProtoType::ExtParameterInfo{});
  293. }
  294. RequiredArgs required =
  295. (PassParams && MD->isVariadic() ? RequiredArgs(argTypes.size())
  296. : RequiredArgs::All);
  297. FunctionType::ExtInfo extInfo = FTP->getExtInfo();
  298. CanQualType resultType = TheCXXABI.HasThisReturn(GD)
  299. ? argTypes.front()
  300. : TheCXXABI.hasMostDerivedReturn(GD)
  301. ? CGM.getContext().VoidPtrTy
  302. : Context.VoidTy;
  303. return arrangeLLVMFunctionInfo(resultType, /*instanceMethod=*/true,
  304. /*chainCall=*/false, argTypes, extInfo,
  305. paramInfos, required);
  306. }
  307. static SmallVector<CanQualType, 16>
  308. getArgTypesForCall(ASTContext &ctx, const CallArgList &args) {
  309. SmallVector<CanQualType, 16> argTypes;
  310. for (auto &arg : args)
  311. argTypes.push_back(ctx.getCanonicalParamType(arg.Ty));
  312. return argTypes;
  313. }
  314. static SmallVector<CanQualType, 16>
  315. getArgTypesForDeclaration(ASTContext &ctx, const FunctionArgList &args) {
  316. SmallVector<CanQualType, 16> argTypes;
  317. for (auto &arg : args)
  318. argTypes.push_back(ctx.getCanonicalParamType(arg->getType()));
  319. return argTypes;
  320. }
  321. static llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16>
  322. getExtParameterInfosForCall(const FunctionProtoType *proto,
  323. unsigned prefixArgs, unsigned totalArgs) {
  324. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> result;
  325. if (proto->hasExtParameterInfos()) {
  326. addExtParameterInfosForCall(result, proto, prefixArgs, totalArgs);
  327. }
  328. return result;
  329. }
  330. /// Arrange a call to a C++ method, passing the given arguments.
  331. ///
  332. /// ExtraPrefixArgs is the number of ABI-specific args passed after the `this`
  333. /// parameter.
  334. /// ExtraSuffixArgs is the number of ABI-specific args passed at the end of
  335. /// args.
  336. /// PassProtoArgs indicates whether `args` has args for the parameters in the
  337. /// given CXXConstructorDecl.
  338. const CGFunctionInfo &
  339. CodeGenTypes::arrangeCXXConstructorCall(const CallArgList &args,
  340. const CXXConstructorDecl *D,
  341. CXXCtorType CtorKind,
  342. unsigned ExtraPrefixArgs,
  343. unsigned ExtraSuffixArgs,
  344. bool PassProtoArgs) {
  345. // FIXME: Kill copy.
  346. SmallVector<CanQualType, 16> ArgTypes;
  347. for (const auto &Arg : args)
  348. ArgTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  349. // +1 for implicit this, which should always be args[0].
  350. unsigned TotalPrefixArgs = 1 + ExtraPrefixArgs;
  351. CanQual<FunctionProtoType> FPT = GetFormalType(D);
  352. RequiredArgs Required = PassProtoArgs
  353. ? RequiredArgs::forPrototypePlus(
  354. FPT, TotalPrefixArgs + ExtraSuffixArgs)
  355. : RequiredArgs::All;
  356. GlobalDecl GD(D, CtorKind);
  357. CanQualType ResultType = TheCXXABI.HasThisReturn(GD)
  358. ? ArgTypes.front()
  359. : TheCXXABI.hasMostDerivedReturn(GD)
  360. ? CGM.getContext().VoidPtrTy
  361. : Context.VoidTy;
  362. FunctionType::ExtInfo Info = FPT->getExtInfo();
  363. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> ParamInfos;
  364. // If the prototype args are elided, we should only have ABI-specific args,
  365. // which never have param info.
  366. if (PassProtoArgs && FPT->hasExtParameterInfos()) {
  367. // ABI-specific suffix arguments are treated the same as variadic arguments.
  368. addExtParameterInfosForCall(ParamInfos, FPT.getTypePtr(), TotalPrefixArgs,
  369. ArgTypes.size());
  370. }
  371. return arrangeLLVMFunctionInfo(ResultType, /*instanceMethod=*/true,
  372. /*chainCall=*/false, ArgTypes, Info,
  373. ParamInfos, Required);
  374. }
  375. /// Arrange the argument and result information for the declaration or
  376. /// definition of the given function.
  377. const CGFunctionInfo &
  378. CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
  379. if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(FD))
  380. if (MD->isInstance())
  381. return arrangeCXXMethodDeclaration(MD);
  382. CanQualType FTy = FD->getType()->getCanonicalTypeUnqualified();
  383. assert(isa<FunctionType>(FTy));
  384. setCUDAKernelCallingConvention(FTy, CGM, FD);
  385. // When declaring a function without a prototype, always use a
  386. // non-variadic type.
  387. if (CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>()) {
  388. return arrangeLLVMFunctionInfo(
  389. noProto->getReturnType(), /*instanceMethod=*/false,
  390. /*chainCall=*/false, None, noProto->getExtInfo(), {},RequiredArgs::All);
  391. }
  392. return arrangeFreeFunctionType(FTy.castAs<FunctionProtoType>());
  393. }
  394. /// Arrange the argument and result information for the declaration or
  395. /// definition of an Objective-C method.
  396. const CGFunctionInfo &
  397. CodeGenTypes::arrangeObjCMethodDeclaration(const ObjCMethodDecl *MD) {
  398. // It happens that this is the same as a call with no optional
  399. // arguments, except also using the formal 'self' type.
  400. return arrangeObjCMessageSendSignature(MD, MD->getSelfDecl()->getType());
  401. }
  402. /// Arrange the argument and result information for the function type
  403. /// through which to perform a send to the given Objective-C method,
  404. /// using the given receiver type. The receiver type is not always
  405. /// the 'self' type of the method or even an Objective-C pointer type.
  406. /// This is *not* the right method for actually performing such a
  407. /// message send, due to the possibility of optional arguments.
  408. const CGFunctionInfo &
  409. CodeGenTypes::arrangeObjCMessageSendSignature(const ObjCMethodDecl *MD,
  410. QualType receiverType) {
  411. SmallVector<CanQualType, 16> argTys;
  412. SmallVector<FunctionProtoType::ExtParameterInfo, 4> extParamInfos(2);
  413. argTys.push_back(Context.getCanonicalParamType(receiverType));
  414. argTys.push_back(Context.getCanonicalParamType(Context.getObjCSelType()));
  415. // FIXME: Kill copy?
  416. for (const auto *I : MD->parameters()) {
  417. argTys.push_back(Context.getCanonicalParamType(I->getType()));
  418. auto extParamInfo = FunctionProtoType::ExtParameterInfo().withIsNoEscape(
  419. I->hasAttr<NoEscapeAttr>());
  420. extParamInfos.push_back(extParamInfo);
  421. }
  422. FunctionType::ExtInfo einfo;
  423. bool IsWindows = getContext().getTargetInfo().getTriple().isOSWindows();
  424. einfo = einfo.withCallingConv(getCallingConventionForDecl(MD, IsWindows));
  425. if (getContext().getLangOpts().ObjCAutoRefCount &&
  426. MD->hasAttr<NSReturnsRetainedAttr>())
  427. einfo = einfo.withProducesResult(true);
  428. RequiredArgs required =
  429. (MD->isVariadic() ? RequiredArgs(argTys.size()) : RequiredArgs::All);
  430. return arrangeLLVMFunctionInfo(
  431. GetReturnType(MD->getReturnType()), /*instanceMethod=*/false,
  432. /*chainCall=*/false, argTys, einfo, extParamInfos, required);
  433. }
  434. const CGFunctionInfo &
  435. CodeGenTypes::arrangeUnprototypedObjCMessageSend(QualType returnType,
  436. const CallArgList &args) {
  437. auto argTypes = getArgTypesForCall(Context, args);
  438. FunctionType::ExtInfo einfo;
  439. return arrangeLLVMFunctionInfo(
  440. GetReturnType(returnType), /*instanceMethod=*/false,
  441. /*chainCall=*/false, argTypes, einfo, {}, RequiredArgs::All);
  442. }
  443. const CGFunctionInfo &
  444. CodeGenTypes::arrangeGlobalDeclaration(GlobalDecl GD) {
  445. // FIXME: Do we need to handle ObjCMethodDecl?
  446. const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
  447. if (isa<CXXConstructorDecl>(GD.getDecl()) ||
  448. isa<CXXDestructorDecl>(GD.getDecl()))
  449. return arrangeCXXStructorDeclaration(GD);
  450. return arrangeFunctionDeclaration(FD);
  451. }
  452. /// Arrange a thunk that takes 'this' as the first parameter followed by
  453. /// varargs. Return a void pointer, regardless of the actual return type.
  454. /// The body of the thunk will end in a musttail call to a function of the
  455. /// correct type, and the caller will bitcast the function to the correct
  456. /// prototype.
  457. const CGFunctionInfo &
  458. CodeGenTypes::arrangeUnprototypedMustTailThunk(const CXXMethodDecl *MD) {
  459. assert(MD->isVirtual() && "only methods have thunks");
  460. CanQual<FunctionProtoType> FTP = GetFormalType(MD);
  461. CanQualType ArgTys[] = {DeriveThisType(MD->getParent(), MD)};
  462. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/false,
  463. /*chainCall=*/false, ArgTys,
  464. FTP->getExtInfo(), {}, RequiredArgs(1));
  465. }
  466. const CGFunctionInfo &
  467. CodeGenTypes::arrangeMSCtorClosure(const CXXConstructorDecl *CD,
  468. CXXCtorType CT) {
  469. assert(CT == Ctor_CopyingClosure || CT == Ctor_DefaultClosure);
  470. CanQual<FunctionProtoType> FTP = GetFormalType(CD);
  471. SmallVector<CanQualType, 2> ArgTys;
  472. const CXXRecordDecl *RD = CD->getParent();
  473. ArgTys.push_back(DeriveThisType(RD, CD));
  474. if (CT == Ctor_CopyingClosure)
  475. ArgTys.push_back(*FTP->param_type_begin());
  476. if (RD->getNumVBases() > 0)
  477. ArgTys.push_back(Context.IntTy);
  478. CallingConv CC = Context.getDefaultCallingConvention(
  479. /*IsVariadic=*/false, /*IsCXXMethod=*/true);
  480. return arrangeLLVMFunctionInfo(Context.VoidTy, /*instanceMethod=*/true,
  481. /*chainCall=*/false, ArgTys,
  482. FunctionType::ExtInfo(CC), {},
  483. RequiredArgs::All);
  484. }
  485. /// Arrange a call as unto a free function, except possibly with an
  486. /// additional number of formal parameters considered required.
  487. static const CGFunctionInfo &
  488. arrangeFreeFunctionLikeCall(CodeGenTypes &CGT,
  489. CodeGenModule &CGM,
  490. const CallArgList &args,
  491. const FunctionType *fnType,
  492. unsigned numExtraRequiredArgs,
  493. bool chainCall) {
  494. assert(args.size() >= numExtraRequiredArgs);
  495. llvm::SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  496. // In most cases, there are no optional arguments.
  497. RequiredArgs required = RequiredArgs::All;
  498. // If we have a variadic prototype, the required arguments are the
  499. // extra prefix plus the arguments in the prototype.
  500. if (const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(fnType)) {
  501. if (proto->isVariadic())
  502. required = RequiredArgs::forPrototypePlus(proto, numExtraRequiredArgs);
  503. if (proto->hasExtParameterInfos())
  504. addExtParameterInfosForCall(paramInfos, proto, numExtraRequiredArgs,
  505. args.size());
  506. // If we don't have a prototype at all, but we're supposed to
  507. // explicitly use the variadic convention for unprototyped calls,
  508. // treat all of the arguments as required but preserve the nominal
  509. // possibility of variadics.
  510. } else if (CGM.getTargetCodeGenInfo()
  511. .isNoProtoCallVariadic(args,
  512. cast<FunctionNoProtoType>(fnType))) {
  513. required = RequiredArgs(args.size());
  514. }
  515. // FIXME: Kill copy.
  516. SmallVector<CanQualType, 16> argTypes;
  517. for (const auto &arg : args)
  518. argTypes.push_back(CGT.getContext().getCanonicalParamType(arg.Ty));
  519. return CGT.arrangeLLVMFunctionInfo(GetReturnType(fnType->getReturnType()),
  520. /*instanceMethod=*/false, chainCall,
  521. argTypes, fnType->getExtInfo(), paramInfos,
  522. required);
  523. }
  524. /// Figure out the rules for calling a function with the given formal
  525. /// type using the given arguments. The arguments are necessary
  526. /// because the function might be unprototyped, in which case it's
  527. /// target-dependent in crazy ways.
  528. const CGFunctionInfo &
  529. CodeGenTypes::arrangeFreeFunctionCall(const CallArgList &args,
  530. const FunctionType *fnType,
  531. bool chainCall) {
  532. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType,
  533. chainCall ? 1 : 0, chainCall);
  534. }
  535. /// A block function is essentially a free function with an
  536. /// extra implicit argument.
  537. const CGFunctionInfo &
  538. CodeGenTypes::arrangeBlockFunctionCall(const CallArgList &args,
  539. const FunctionType *fnType) {
  540. return arrangeFreeFunctionLikeCall(*this, CGM, args, fnType, 1,
  541. /*chainCall=*/false);
  542. }
  543. const CGFunctionInfo &
  544. CodeGenTypes::arrangeBlockFunctionDeclaration(const FunctionProtoType *proto,
  545. const FunctionArgList &params) {
  546. auto paramInfos = getExtParameterInfosForCall(proto, 1, params.size());
  547. auto argTypes = getArgTypesForDeclaration(Context, params);
  548. return arrangeLLVMFunctionInfo(GetReturnType(proto->getReturnType()),
  549. /*instanceMethod*/ false, /*chainCall*/ false,
  550. argTypes, proto->getExtInfo(), paramInfos,
  551. RequiredArgs::forPrototypePlus(proto, 1));
  552. }
  553. const CGFunctionInfo &
  554. CodeGenTypes::arrangeBuiltinFunctionCall(QualType resultType,
  555. const CallArgList &args) {
  556. // FIXME: Kill copy.
  557. SmallVector<CanQualType, 16> argTypes;
  558. for (const auto &Arg : args)
  559. argTypes.push_back(Context.getCanonicalParamType(Arg.Ty));
  560. return arrangeLLVMFunctionInfo(
  561. GetReturnType(resultType), /*instanceMethod=*/false,
  562. /*chainCall=*/false, argTypes, FunctionType::ExtInfo(),
  563. /*paramInfos=*/ {}, RequiredArgs::All);
  564. }
  565. const CGFunctionInfo &
  566. CodeGenTypes::arrangeBuiltinFunctionDeclaration(QualType resultType,
  567. const FunctionArgList &args) {
  568. auto argTypes = getArgTypesForDeclaration(Context, args);
  569. return arrangeLLVMFunctionInfo(
  570. GetReturnType(resultType), /*instanceMethod=*/false, /*chainCall=*/false,
  571. argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  572. }
  573. const CGFunctionInfo &
  574. CodeGenTypes::arrangeBuiltinFunctionDeclaration(CanQualType resultType,
  575. ArrayRef<CanQualType> argTypes) {
  576. return arrangeLLVMFunctionInfo(
  577. resultType, /*instanceMethod=*/false, /*chainCall=*/false,
  578. argTypes, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  579. }
  580. /// Arrange a call to a C++ method, passing the given arguments.
  581. ///
  582. /// numPrefixArgs is the number of ABI-specific prefix arguments we have. It
  583. /// does not count `this`.
  584. const CGFunctionInfo &
  585. CodeGenTypes::arrangeCXXMethodCall(const CallArgList &args,
  586. const FunctionProtoType *proto,
  587. RequiredArgs required,
  588. unsigned numPrefixArgs) {
  589. assert(numPrefixArgs + 1 <= args.size() &&
  590. "Emitting a call with less args than the required prefix?");
  591. // Add one to account for `this`. It's a bit awkward here, but we don't count
  592. // `this` in similar places elsewhere.
  593. auto paramInfos =
  594. getExtParameterInfosForCall(proto, numPrefixArgs + 1, args.size());
  595. // FIXME: Kill copy.
  596. auto argTypes = getArgTypesForCall(Context, args);
  597. FunctionType::ExtInfo info = proto->getExtInfo();
  598. return arrangeLLVMFunctionInfo(
  599. GetReturnType(proto->getReturnType()), /*instanceMethod=*/true,
  600. /*chainCall=*/false, argTypes, info, paramInfos, required);
  601. }
  602. const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
  603. return arrangeLLVMFunctionInfo(
  604. getContext().VoidTy, /*instanceMethod=*/false, /*chainCall=*/false,
  605. None, FunctionType::ExtInfo(), {}, RequiredArgs::All);
  606. }
  607. const CGFunctionInfo &
  608. CodeGenTypes::arrangeCall(const CGFunctionInfo &signature,
  609. const CallArgList &args) {
  610. assert(signature.arg_size() <= args.size());
  611. if (signature.arg_size() == args.size())
  612. return signature;
  613. SmallVector<FunctionProtoType::ExtParameterInfo, 16> paramInfos;
  614. auto sigParamInfos = signature.getExtParameterInfos();
  615. if (!sigParamInfos.empty()) {
  616. paramInfos.append(sigParamInfos.begin(), sigParamInfos.end());
  617. paramInfos.resize(args.size());
  618. }
  619. auto argTypes = getArgTypesForCall(Context, args);
  620. assert(signature.getRequiredArgs().allowsOptionalArgs());
  621. return arrangeLLVMFunctionInfo(signature.getReturnType(),
  622. signature.isInstanceMethod(),
  623. signature.isChainCall(),
  624. argTypes,
  625. signature.getExtInfo(),
  626. paramInfos,
  627. signature.getRequiredArgs());
  628. }
  629. namespace clang {
  630. namespace CodeGen {
  631. void computeSPIRKernelABIInfo(CodeGenModule &CGM, CGFunctionInfo &FI);
  632. }
  633. }
  634. /// Arrange the argument and result information for an abstract value
  635. /// of a given function type. This is the method which all of the
  636. /// above functions ultimately defer to.
  637. const CGFunctionInfo &
  638. CodeGenTypes::arrangeLLVMFunctionInfo(CanQualType resultType,
  639. bool instanceMethod,
  640. bool chainCall,
  641. ArrayRef<CanQualType> argTypes,
  642. FunctionType::ExtInfo info,
  643. ArrayRef<FunctionProtoType::ExtParameterInfo> paramInfos,
  644. RequiredArgs required) {
  645. assert(llvm::all_of(argTypes,
  646. [](CanQualType T) { return T.isCanonicalAsParam(); }));
  647. // Lookup or create unique function info.
  648. llvm::FoldingSetNodeID ID;
  649. CGFunctionInfo::Profile(ID, instanceMethod, chainCall, info, paramInfos,
  650. required, resultType, argTypes);
  651. void *insertPos = nullptr;
  652. CGFunctionInfo *FI = FunctionInfos.FindNodeOrInsertPos(ID, insertPos);
  653. if (FI)
  654. return *FI;
  655. unsigned CC = ClangCallConvToLLVMCallConv(info.getCC());
  656. // Construct the function info. We co-allocate the ArgInfos.
  657. FI = CGFunctionInfo::create(CC, instanceMethod, chainCall, info,
  658. paramInfos, resultType, argTypes, required);
  659. FunctionInfos.InsertNode(FI, insertPos);
  660. bool inserted = FunctionsBeingProcessed.insert(FI).second;
  661. (void)inserted;
  662. assert(inserted && "Recursively being processed?");
  663. // Compute ABI information.
  664. if (CC == llvm::CallingConv::SPIR_KERNEL) {
  665. // Force target independent argument handling for the host visible
  666. // kernel functions.
  667. computeSPIRKernelABIInfo(CGM, *FI);
  668. } else if (info.getCC() == CC_Swift || info.getCC() == CC_SwiftAsync) {
  669. swiftcall::computeABIInfo(CGM, *FI);
  670. } else {
  671. getABIInfo().computeInfo(*FI);
  672. }
  673. // Loop over all of the computed argument and return value info. If any of
  674. // them are direct or extend without a specified coerce type, specify the
  675. // default now.
  676. ABIArgInfo &retInfo = FI->getReturnInfo();
  677. if (retInfo.canHaveCoerceToType() && retInfo.getCoerceToType() == nullptr)
  678. retInfo.setCoerceToType(ConvertType(FI->getReturnType()));
  679. for (auto &I : FI->arguments())
  680. if (I.info.canHaveCoerceToType() && I.info.getCoerceToType() == nullptr)
  681. I.info.setCoerceToType(ConvertType(I.type));
  682. bool erased = FunctionsBeingProcessed.erase(FI); (void)erased;
  683. assert(erased && "Not in set?");
  684. return *FI;
  685. }
  686. CGFunctionInfo *CGFunctionInfo::create(unsigned llvmCC,
  687. bool instanceMethod,
  688. bool chainCall,
  689. const FunctionType::ExtInfo &info,
  690. ArrayRef<ExtParameterInfo> paramInfos,
  691. CanQualType resultType,
  692. ArrayRef<CanQualType> argTypes,
  693. RequiredArgs required) {
  694. assert(paramInfos.empty() || paramInfos.size() == argTypes.size());
  695. assert(!required.allowsOptionalArgs() ||
  696. required.getNumRequiredArgs() <= argTypes.size());
  697. void *buffer =
  698. operator new(totalSizeToAlloc<ArgInfo, ExtParameterInfo>(
  699. argTypes.size() + 1, paramInfos.size()));
  700. CGFunctionInfo *FI = new(buffer) CGFunctionInfo();
  701. FI->CallingConvention = llvmCC;
  702. FI->EffectiveCallingConvention = llvmCC;
  703. FI->ASTCallingConvention = info.getCC();
  704. FI->InstanceMethod = instanceMethod;
  705. FI->ChainCall = chainCall;
  706. FI->CmseNSCall = info.getCmseNSCall();
  707. FI->NoReturn = info.getNoReturn();
  708. FI->ReturnsRetained = info.getProducesResult();
  709. FI->NoCallerSavedRegs = info.getNoCallerSavedRegs();
  710. FI->NoCfCheck = info.getNoCfCheck();
  711. FI->Required = required;
  712. FI->HasRegParm = info.getHasRegParm();
  713. FI->RegParm = info.getRegParm();
  714. FI->ArgStruct = nullptr;
  715. FI->ArgStructAlign = 0;
  716. FI->NumArgs = argTypes.size();
  717. FI->HasExtParameterInfos = !paramInfos.empty();
  718. FI->getArgsBuffer()[0].type = resultType;
  719. for (unsigned i = 0, e = argTypes.size(); i != e; ++i)
  720. FI->getArgsBuffer()[i + 1].type = argTypes[i];
  721. for (unsigned i = 0, e = paramInfos.size(); i != e; ++i)
  722. FI->getExtParameterInfosBuffer()[i] = paramInfos[i];
  723. return FI;
  724. }
  725. /***/
  726. namespace {
  727. // ABIArgInfo::Expand implementation.
  728. // Specifies the way QualType passed as ABIArgInfo::Expand is expanded.
  729. struct TypeExpansion {
  730. enum TypeExpansionKind {
  731. // Elements of constant arrays are expanded recursively.
  732. TEK_ConstantArray,
  733. // Record fields are expanded recursively (but if record is a union, only
  734. // the field with the largest size is expanded).
  735. TEK_Record,
  736. // For complex types, real and imaginary parts are expanded recursively.
  737. TEK_Complex,
  738. // All other types are not expandable.
  739. TEK_None
  740. };
  741. const TypeExpansionKind Kind;
  742. TypeExpansion(TypeExpansionKind K) : Kind(K) {}
  743. virtual ~TypeExpansion() {}
  744. };
  745. struct ConstantArrayExpansion : TypeExpansion {
  746. QualType EltTy;
  747. uint64_t NumElts;
  748. ConstantArrayExpansion(QualType EltTy, uint64_t NumElts)
  749. : TypeExpansion(TEK_ConstantArray), EltTy(EltTy), NumElts(NumElts) {}
  750. static bool classof(const TypeExpansion *TE) {
  751. return TE->Kind == TEK_ConstantArray;
  752. }
  753. };
  754. struct RecordExpansion : TypeExpansion {
  755. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  756. SmallVector<const FieldDecl *, 1> Fields;
  757. RecordExpansion(SmallVector<const CXXBaseSpecifier *, 1> &&Bases,
  758. SmallVector<const FieldDecl *, 1> &&Fields)
  759. : TypeExpansion(TEK_Record), Bases(std::move(Bases)),
  760. Fields(std::move(Fields)) {}
  761. static bool classof(const TypeExpansion *TE) {
  762. return TE->Kind == TEK_Record;
  763. }
  764. };
  765. struct ComplexExpansion : TypeExpansion {
  766. QualType EltTy;
  767. ComplexExpansion(QualType EltTy) : TypeExpansion(TEK_Complex), EltTy(EltTy) {}
  768. static bool classof(const TypeExpansion *TE) {
  769. return TE->Kind == TEK_Complex;
  770. }
  771. };
  772. struct NoExpansion : TypeExpansion {
  773. NoExpansion() : TypeExpansion(TEK_None) {}
  774. static bool classof(const TypeExpansion *TE) {
  775. return TE->Kind == TEK_None;
  776. }
  777. };
  778. } // namespace
  779. static std::unique_ptr<TypeExpansion>
  780. getTypeExpansion(QualType Ty, const ASTContext &Context) {
  781. if (const ConstantArrayType *AT = Context.getAsConstantArrayType(Ty)) {
  782. return std::make_unique<ConstantArrayExpansion>(
  783. AT->getElementType(), AT->getSize().getZExtValue());
  784. }
  785. if (const RecordType *RT = Ty->getAs<RecordType>()) {
  786. SmallVector<const CXXBaseSpecifier *, 1> Bases;
  787. SmallVector<const FieldDecl *, 1> Fields;
  788. const RecordDecl *RD = RT->getDecl();
  789. assert(!RD->hasFlexibleArrayMember() &&
  790. "Cannot expand structure with flexible array.");
  791. if (RD->isUnion()) {
  792. // Unions can be here only in degenerative cases - all the fields are same
  793. // after flattening. Thus we have to use the "largest" field.
  794. const FieldDecl *LargestFD = nullptr;
  795. CharUnits UnionSize = CharUnits::Zero();
  796. for (const auto *FD : RD->fields()) {
  797. if (FD->isZeroLengthBitField(Context))
  798. continue;
  799. assert(!FD->isBitField() &&
  800. "Cannot expand structure with bit-field members.");
  801. CharUnits FieldSize = Context.getTypeSizeInChars(FD->getType());
  802. if (UnionSize < FieldSize) {
  803. UnionSize = FieldSize;
  804. LargestFD = FD;
  805. }
  806. }
  807. if (LargestFD)
  808. Fields.push_back(LargestFD);
  809. } else {
  810. if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) {
  811. assert(!CXXRD->isDynamicClass() &&
  812. "cannot expand vtable pointers in dynamic classes");
  813. for (const CXXBaseSpecifier &BS : CXXRD->bases())
  814. Bases.push_back(&BS);
  815. }
  816. for (const auto *FD : RD->fields()) {
  817. if (FD->isZeroLengthBitField(Context))
  818. continue;
  819. assert(!FD->isBitField() &&
  820. "Cannot expand structure with bit-field members.");
  821. Fields.push_back(FD);
  822. }
  823. }
  824. return std::make_unique<RecordExpansion>(std::move(Bases),
  825. std::move(Fields));
  826. }
  827. if (const ComplexType *CT = Ty->getAs<ComplexType>()) {
  828. return std::make_unique<ComplexExpansion>(CT->getElementType());
  829. }
  830. return std::make_unique<NoExpansion>();
  831. }
  832. static int getExpansionSize(QualType Ty, const ASTContext &Context) {
  833. auto Exp = getTypeExpansion(Ty, Context);
  834. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  835. return CAExp->NumElts * getExpansionSize(CAExp->EltTy, Context);
  836. }
  837. if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  838. int Res = 0;
  839. for (auto BS : RExp->Bases)
  840. Res += getExpansionSize(BS->getType(), Context);
  841. for (auto FD : RExp->Fields)
  842. Res += getExpansionSize(FD->getType(), Context);
  843. return Res;
  844. }
  845. if (isa<ComplexExpansion>(Exp.get()))
  846. return 2;
  847. assert(isa<NoExpansion>(Exp.get()));
  848. return 1;
  849. }
  850. void
  851. CodeGenTypes::getExpandedTypes(QualType Ty,
  852. SmallVectorImpl<llvm::Type *>::iterator &TI) {
  853. auto Exp = getTypeExpansion(Ty, Context);
  854. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  855. for (int i = 0, n = CAExp->NumElts; i < n; i++) {
  856. getExpandedTypes(CAExp->EltTy, TI);
  857. }
  858. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  859. for (auto BS : RExp->Bases)
  860. getExpandedTypes(BS->getType(), TI);
  861. for (auto FD : RExp->Fields)
  862. getExpandedTypes(FD->getType(), TI);
  863. } else if (auto CExp = dyn_cast<ComplexExpansion>(Exp.get())) {
  864. llvm::Type *EltTy = ConvertType(CExp->EltTy);
  865. *TI++ = EltTy;
  866. *TI++ = EltTy;
  867. } else {
  868. assert(isa<NoExpansion>(Exp.get()));
  869. *TI++ = ConvertType(Ty);
  870. }
  871. }
  872. static void forConstantArrayExpansion(CodeGenFunction &CGF,
  873. ConstantArrayExpansion *CAE,
  874. Address BaseAddr,
  875. llvm::function_ref<void(Address)> Fn) {
  876. CharUnits EltSize = CGF.getContext().getTypeSizeInChars(CAE->EltTy);
  877. CharUnits EltAlign =
  878. BaseAddr.getAlignment().alignmentOfArrayElement(EltSize);
  879. for (int i = 0, n = CAE->NumElts; i < n; i++) {
  880. llvm::Value *EltAddr = CGF.Builder.CreateConstGEP2_32(
  881. BaseAddr.getElementType(), BaseAddr.getPointer(), 0, i);
  882. Fn(Address(EltAddr, EltAlign));
  883. }
  884. }
  885. void CodeGenFunction::ExpandTypeFromArgs(QualType Ty, LValue LV,
  886. llvm::Function::arg_iterator &AI) {
  887. assert(LV.isSimple() &&
  888. "Unexpected non-simple lvalue during struct expansion.");
  889. auto Exp = getTypeExpansion(Ty, getContext());
  890. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  891. forConstantArrayExpansion(
  892. *this, CAExp, LV.getAddress(*this), [&](Address EltAddr) {
  893. LValue LV = MakeAddrLValue(EltAddr, CAExp->EltTy);
  894. ExpandTypeFromArgs(CAExp->EltTy, LV, AI);
  895. });
  896. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  897. Address This = LV.getAddress(*this);
  898. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  899. // Perform a single step derived-to-base conversion.
  900. Address Base =
  901. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  902. /*NullCheckValue=*/false, SourceLocation());
  903. LValue SubLV = MakeAddrLValue(Base, BS->getType());
  904. // Recurse onto bases.
  905. ExpandTypeFromArgs(BS->getType(), SubLV, AI);
  906. }
  907. for (auto FD : RExp->Fields) {
  908. // FIXME: What are the right qualifiers here?
  909. LValue SubLV = EmitLValueForFieldInitialization(LV, FD);
  910. ExpandTypeFromArgs(FD->getType(), SubLV, AI);
  911. }
  912. } else if (isa<ComplexExpansion>(Exp.get())) {
  913. auto realValue = &*AI++;
  914. auto imagValue = &*AI++;
  915. EmitStoreOfComplex(ComplexPairTy(realValue, imagValue), LV, /*init*/ true);
  916. } else {
  917. // Call EmitStoreOfScalar except when the lvalue is a bitfield to emit a
  918. // primitive store.
  919. assert(isa<NoExpansion>(Exp.get()));
  920. llvm::Value *Arg = &*AI++;
  921. if (LV.isBitField()) {
  922. EmitStoreThroughLValue(RValue::get(Arg), LV);
  923. } else {
  924. // TODO: currently there are some places are inconsistent in what LLVM
  925. // pointer type they use (see D118744). Once clang uses opaque pointers
  926. // all LLVM pointer types will be the same and we can remove this check.
  927. if (Arg->getType()->isPointerTy()) {
  928. Address Addr = LV.getAddress(*this);
  929. Arg = Builder.CreateBitCast(Arg, Addr.getElementType());
  930. }
  931. EmitStoreOfScalar(Arg, LV);
  932. }
  933. }
  934. }
  935. void CodeGenFunction::ExpandTypeToArgs(
  936. QualType Ty, CallArg Arg, llvm::FunctionType *IRFuncTy,
  937. SmallVectorImpl<llvm::Value *> &IRCallArgs, unsigned &IRCallArgPos) {
  938. auto Exp = getTypeExpansion(Ty, getContext());
  939. if (auto CAExp = dyn_cast<ConstantArrayExpansion>(Exp.get())) {
  940. Address Addr = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
  941. : Arg.getKnownRValue().getAggregateAddress();
  942. forConstantArrayExpansion(
  943. *this, CAExp, Addr, [&](Address EltAddr) {
  944. CallArg EltArg = CallArg(
  945. convertTempToRValue(EltAddr, CAExp->EltTy, SourceLocation()),
  946. CAExp->EltTy);
  947. ExpandTypeToArgs(CAExp->EltTy, EltArg, IRFuncTy, IRCallArgs,
  948. IRCallArgPos);
  949. });
  950. } else if (auto RExp = dyn_cast<RecordExpansion>(Exp.get())) {
  951. Address This = Arg.hasLValue() ? Arg.getKnownLValue().getAddress(*this)
  952. : Arg.getKnownRValue().getAggregateAddress();
  953. for (const CXXBaseSpecifier *BS : RExp->Bases) {
  954. // Perform a single step derived-to-base conversion.
  955. Address Base =
  956. GetAddressOfBaseClass(This, Ty->getAsCXXRecordDecl(), &BS, &BS + 1,
  957. /*NullCheckValue=*/false, SourceLocation());
  958. CallArg BaseArg = CallArg(RValue::getAggregate(Base), BS->getType());
  959. // Recurse onto bases.
  960. ExpandTypeToArgs(BS->getType(), BaseArg, IRFuncTy, IRCallArgs,
  961. IRCallArgPos);
  962. }
  963. LValue LV = MakeAddrLValue(This, Ty);
  964. for (auto FD : RExp->Fields) {
  965. CallArg FldArg =
  966. CallArg(EmitRValueForField(LV, FD, SourceLocation()), FD->getType());
  967. ExpandTypeToArgs(FD->getType(), FldArg, IRFuncTy, IRCallArgs,
  968. IRCallArgPos);
  969. }
  970. } else if (isa<ComplexExpansion>(Exp.get())) {
  971. ComplexPairTy CV = Arg.getKnownRValue().getComplexVal();
  972. IRCallArgs[IRCallArgPos++] = CV.first;
  973. IRCallArgs[IRCallArgPos++] = CV.second;
  974. } else {
  975. assert(isa<NoExpansion>(Exp.get()));
  976. auto RV = Arg.getKnownRValue();
  977. assert(RV.isScalar() &&
  978. "Unexpected non-scalar rvalue during struct expansion.");
  979. // Insert a bitcast as needed.
  980. llvm::Value *V = RV.getScalarVal();
  981. if (IRCallArgPos < IRFuncTy->getNumParams() &&
  982. V->getType() != IRFuncTy->getParamType(IRCallArgPos))
  983. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(IRCallArgPos));
  984. IRCallArgs[IRCallArgPos++] = V;
  985. }
  986. }
  987. /// Create a temporary allocation for the purposes of coercion.
  988. static Address CreateTempAllocaForCoercion(CodeGenFunction &CGF, llvm::Type *Ty,
  989. CharUnits MinAlign,
  990. const Twine &Name = "tmp") {
  991. // Don't use an alignment that's worse than what LLVM would prefer.
  992. auto PrefAlign = CGF.CGM.getDataLayout().getPrefTypeAlignment(Ty);
  993. CharUnits Align = std::max(MinAlign, CharUnits::fromQuantity(PrefAlign));
  994. return CGF.CreateTempAlloca(Ty, Align, Name + ".coerce");
  995. }
  996. /// EnterStructPointerForCoercedAccess - Given a struct pointer that we are
  997. /// accessing some number of bytes out of it, try to gep into the struct to get
  998. /// at its inner goodness. Dive as deep as possible without entering an element
  999. /// with an in-memory size smaller than DstSize.
  1000. static Address
  1001. EnterStructPointerForCoercedAccess(Address SrcPtr,
  1002. llvm::StructType *SrcSTy,
  1003. uint64_t DstSize, CodeGenFunction &CGF) {
  1004. // We can't dive into a zero-element struct.
  1005. if (SrcSTy->getNumElements() == 0) return SrcPtr;
  1006. llvm::Type *FirstElt = SrcSTy->getElementType(0);
  1007. // If the first elt is at least as large as what we're looking for, or if the
  1008. // first element is the same size as the whole struct, we can enter it. The
  1009. // comparison must be made on the store size and not the alloca size. Using
  1010. // the alloca size may overstate the size of the load.
  1011. uint64_t FirstEltSize =
  1012. CGF.CGM.getDataLayout().getTypeStoreSize(FirstElt);
  1013. if (FirstEltSize < DstSize &&
  1014. FirstEltSize < CGF.CGM.getDataLayout().getTypeStoreSize(SrcSTy))
  1015. return SrcPtr;
  1016. // GEP into the first element.
  1017. SrcPtr = CGF.Builder.CreateStructGEP(SrcPtr, 0, "coerce.dive");
  1018. // If the first element is a struct, recurse.
  1019. llvm::Type *SrcTy = SrcPtr.getElementType();
  1020. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy))
  1021. return EnterStructPointerForCoercedAccess(SrcPtr, SrcSTy, DstSize, CGF);
  1022. return SrcPtr;
  1023. }
  1024. /// CoerceIntOrPtrToIntOrPtr - Convert a value Val to the specific Ty where both
  1025. /// are either integers or pointers. This does a truncation of the value if it
  1026. /// is too large or a zero extension if it is too small.
  1027. ///
  1028. /// This behaves as if the value were coerced through memory, so on big-endian
  1029. /// targets the high bits are preserved in a truncation, while little-endian
  1030. /// targets preserve the low bits.
  1031. static llvm::Value *CoerceIntOrPtrToIntOrPtr(llvm::Value *Val,
  1032. llvm::Type *Ty,
  1033. CodeGenFunction &CGF) {
  1034. if (Val->getType() == Ty)
  1035. return Val;
  1036. if (isa<llvm::PointerType>(Val->getType())) {
  1037. // If this is Pointer->Pointer avoid conversion to and from int.
  1038. if (isa<llvm::PointerType>(Ty))
  1039. return CGF.Builder.CreateBitCast(Val, Ty, "coerce.val");
  1040. // Convert the pointer to an integer so we can play with its width.
  1041. Val = CGF.Builder.CreatePtrToInt(Val, CGF.IntPtrTy, "coerce.val.pi");
  1042. }
  1043. llvm::Type *DestIntTy = Ty;
  1044. if (isa<llvm::PointerType>(DestIntTy))
  1045. DestIntTy = CGF.IntPtrTy;
  1046. if (Val->getType() != DestIntTy) {
  1047. const llvm::DataLayout &DL = CGF.CGM.getDataLayout();
  1048. if (DL.isBigEndian()) {
  1049. // Preserve the high bits on big-endian targets.
  1050. // That is what memory coercion does.
  1051. uint64_t SrcSize = DL.getTypeSizeInBits(Val->getType());
  1052. uint64_t DstSize = DL.getTypeSizeInBits(DestIntTy);
  1053. if (SrcSize > DstSize) {
  1054. Val = CGF.Builder.CreateLShr(Val, SrcSize - DstSize, "coerce.highbits");
  1055. Val = CGF.Builder.CreateTrunc(Val, DestIntTy, "coerce.val.ii");
  1056. } else {
  1057. Val = CGF.Builder.CreateZExt(Val, DestIntTy, "coerce.val.ii");
  1058. Val = CGF.Builder.CreateShl(Val, DstSize - SrcSize, "coerce.highbits");
  1059. }
  1060. } else {
  1061. // Little-endian targets preserve the low bits. No shifts required.
  1062. Val = CGF.Builder.CreateIntCast(Val, DestIntTy, false, "coerce.val.ii");
  1063. }
  1064. }
  1065. if (isa<llvm::PointerType>(Ty))
  1066. Val = CGF.Builder.CreateIntToPtr(Val, Ty, "coerce.val.ip");
  1067. return Val;
  1068. }
  1069. /// CreateCoercedLoad - Create a load from \arg SrcPtr interpreted as
  1070. /// a pointer to an object of type \arg Ty, known to be aligned to
  1071. /// \arg SrcAlign bytes.
  1072. ///
  1073. /// This safely handles the case when the src type is smaller than the
  1074. /// destination type; in this situation the values of bits which not
  1075. /// present in the src are undefined.
  1076. static llvm::Value *CreateCoercedLoad(Address Src, llvm::Type *Ty,
  1077. CodeGenFunction &CGF) {
  1078. llvm::Type *SrcTy = Src.getElementType();
  1079. // If SrcTy and Ty are the same, just do a load.
  1080. if (SrcTy == Ty)
  1081. return CGF.Builder.CreateLoad(Src);
  1082. llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(Ty);
  1083. if (llvm::StructType *SrcSTy = dyn_cast<llvm::StructType>(SrcTy)) {
  1084. Src = EnterStructPointerForCoercedAccess(Src, SrcSTy,
  1085. DstSize.getFixedSize(), CGF);
  1086. SrcTy = Src.getElementType();
  1087. }
  1088. llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  1089. // If the source and destination are integer or pointer types, just do an
  1090. // extension or truncation to the desired type.
  1091. if ((isa<llvm::IntegerType>(Ty) || isa<llvm::PointerType>(Ty)) &&
  1092. (isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy))) {
  1093. llvm::Value *Load = CGF.Builder.CreateLoad(Src);
  1094. return CoerceIntOrPtrToIntOrPtr(Load, Ty, CGF);
  1095. }
  1096. // If load is legal, just bitcast the src pointer.
  1097. if (!SrcSize.isScalable() && !DstSize.isScalable() &&
  1098. SrcSize.getFixedSize() >= DstSize.getFixedSize()) {
  1099. // Generally SrcSize is never greater than DstSize, since this means we are
  1100. // losing bits. However, this can happen in cases where the structure has
  1101. // additional padding, for example due to a user specified alignment.
  1102. //
  1103. // FIXME: Assert that we aren't truncating non-padding bits when have access
  1104. // to that information.
  1105. Src = CGF.Builder.CreateElementBitCast(Src, Ty);
  1106. return CGF.Builder.CreateLoad(Src);
  1107. }
  1108. // If coercing a fixed vector to a scalable vector for ABI compatibility, and
  1109. // the types match, use the llvm.experimental.vector.insert intrinsic to
  1110. // perform the conversion.
  1111. if (auto *ScalableDst = dyn_cast<llvm::ScalableVectorType>(Ty)) {
  1112. if (auto *FixedSrc = dyn_cast<llvm::FixedVectorType>(SrcTy)) {
  1113. // If we are casting a fixed i8 vector to a scalable 16 x i1 predicate
  1114. // vector, use a vector insert and bitcast the result.
  1115. bool NeedsBitcast = false;
  1116. auto PredType =
  1117. llvm::ScalableVectorType::get(CGF.Builder.getInt1Ty(), 16);
  1118. llvm::Type *OrigType = Ty;
  1119. if (ScalableDst == PredType &&
  1120. FixedSrc->getElementType() == CGF.Builder.getInt8Ty()) {
  1121. ScalableDst = llvm::ScalableVectorType::get(CGF.Builder.getInt8Ty(), 2);
  1122. NeedsBitcast = true;
  1123. }
  1124. if (ScalableDst->getElementType() == FixedSrc->getElementType()) {
  1125. auto *Load = CGF.Builder.CreateLoad(Src);
  1126. auto *UndefVec = llvm::UndefValue::get(ScalableDst);
  1127. auto *Zero = llvm::Constant::getNullValue(CGF.CGM.Int64Ty);
  1128. llvm::Value *Result = CGF.Builder.CreateInsertVector(
  1129. ScalableDst, UndefVec, Load, Zero, "castScalableSve");
  1130. if (NeedsBitcast)
  1131. Result = CGF.Builder.CreateBitCast(Result, OrigType);
  1132. return Result;
  1133. }
  1134. }
  1135. }
  1136. // Otherwise do coercion through memory. This is stupid, but simple.
  1137. Address Tmp =
  1138. CreateTempAllocaForCoercion(CGF, Ty, Src.getAlignment(), Src.getName());
  1139. CGF.Builder.CreateMemCpy(
  1140. Tmp.getPointer(), Tmp.getAlignment().getAsAlign(), Src.getPointer(),
  1141. Src.getAlignment().getAsAlign(),
  1142. llvm::ConstantInt::get(CGF.IntPtrTy, SrcSize.getKnownMinSize()));
  1143. return CGF.Builder.CreateLoad(Tmp);
  1144. }
  1145. // Function to store a first-class aggregate into memory. We prefer to
  1146. // store the elements rather than the aggregate to be more friendly to
  1147. // fast-isel.
  1148. // FIXME: Do we need to recurse here?
  1149. void CodeGenFunction::EmitAggregateStore(llvm::Value *Val, Address Dest,
  1150. bool DestIsVolatile) {
  1151. // Prefer scalar stores to first-class aggregate stores.
  1152. if (llvm::StructType *STy = dyn_cast<llvm::StructType>(Val->getType())) {
  1153. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  1154. Address EltPtr = Builder.CreateStructGEP(Dest, i);
  1155. llvm::Value *Elt = Builder.CreateExtractValue(Val, i);
  1156. Builder.CreateStore(Elt, EltPtr, DestIsVolatile);
  1157. }
  1158. } else {
  1159. Builder.CreateStore(Val, Dest, DestIsVolatile);
  1160. }
  1161. }
  1162. /// CreateCoercedStore - Create a store to \arg DstPtr from \arg Src,
  1163. /// where the source and destination may have different types. The
  1164. /// destination is known to be aligned to \arg DstAlign bytes.
  1165. ///
  1166. /// This safely handles the case when the src type is larger than the
  1167. /// destination type; the upper bits of the src will be lost.
  1168. static void CreateCoercedStore(llvm::Value *Src,
  1169. Address Dst,
  1170. bool DstIsVolatile,
  1171. CodeGenFunction &CGF) {
  1172. llvm::Type *SrcTy = Src->getType();
  1173. llvm::Type *DstTy = Dst.getElementType();
  1174. if (SrcTy == DstTy) {
  1175. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  1176. return;
  1177. }
  1178. llvm::TypeSize SrcSize = CGF.CGM.getDataLayout().getTypeAllocSize(SrcTy);
  1179. if (llvm::StructType *DstSTy = dyn_cast<llvm::StructType>(DstTy)) {
  1180. Dst = EnterStructPointerForCoercedAccess(Dst, DstSTy,
  1181. SrcSize.getFixedSize(), CGF);
  1182. DstTy = Dst.getElementType();
  1183. }
  1184. llvm::PointerType *SrcPtrTy = llvm::dyn_cast<llvm::PointerType>(SrcTy);
  1185. llvm::PointerType *DstPtrTy = llvm::dyn_cast<llvm::PointerType>(DstTy);
  1186. if (SrcPtrTy && DstPtrTy &&
  1187. SrcPtrTy->getAddressSpace() != DstPtrTy->getAddressSpace()) {
  1188. Src = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(Src, DstTy);
  1189. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  1190. return;
  1191. }
  1192. // If the source and destination are integer or pointer types, just do an
  1193. // extension or truncation to the desired type.
  1194. if ((isa<llvm::IntegerType>(SrcTy) || isa<llvm::PointerType>(SrcTy)) &&
  1195. (isa<llvm::IntegerType>(DstTy) || isa<llvm::PointerType>(DstTy))) {
  1196. Src = CoerceIntOrPtrToIntOrPtr(Src, DstTy, CGF);
  1197. CGF.Builder.CreateStore(Src, Dst, DstIsVolatile);
  1198. return;
  1199. }
  1200. llvm::TypeSize DstSize = CGF.CGM.getDataLayout().getTypeAllocSize(DstTy);
  1201. // If store is legal, just bitcast the src pointer.
  1202. if (isa<llvm::ScalableVectorType>(SrcTy) ||
  1203. isa<llvm::ScalableVectorType>(DstTy) ||
  1204. SrcSize.getFixedSize() <= DstSize.getFixedSize()) {
  1205. Dst = CGF.Builder.CreateElementBitCast(Dst, SrcTy);
  1206. CGF.EmitAggregateStore(Src, Dst, DstIsVolatile);
  1207. } else {
  1208. // Otherwise do coercion through memory. This is stupid, but
  1209. // simple.
  1210. // Generally SrcSize is never greater than DstSize, since this means we are
  1211. // losing bits. However, this can happen in cases where the structure has
  1212. // additional padding, for example due to a user specified alignment.
  1213. //
  1214. // FIXME: Assert that we aren't truncating non-padding bits when have access
  1215. // to that information.
  1216. Address Tmp = CreateTempAllocaForCoercion(CGF, SrcTy, Dst.getAlignment());
  1217. CGF.Builder.CreateStore(Src, Tmp);
  1218. CGF.Builder.CreateMemCpy(
  1219. Dst.getPointer(), Dst.getAlignment().getAsAlign(), Tmp.getPointer(),
  1220. Tmp.getAlignment().getAsAlign(),
  1221. llvm::ConstantInt::get(CGF.IntPtrTy, DstSize.getFixedSize()));
  1222. }
  1223. }
  1224. static Address emitAddressAtOffset(CodeGenFunction &CGF, Address addr,
  1225. const ABIArgInfo &info) {
  1226. if (unsigned offset = info.getDirectOffset()) {
  1227. addr = CGF.Builder.CreateElementBitCast(addr, CGF.Int8Ty);
  1228. addr = CGF.Builder.CreateConstInBoundsByteGEP(addr,
  1229. CharUnits::fromQuantity(offset));
  1230. addr = CGF.Builder.CreateElementBitCast(addr, info.getCoerceToType());
  1231. }
  1232. return addr;
  1233. }
  1234. namespace {
  1235. /// Encapsulates information about the way function arguments from
  1236. /// CGFunctionInfo should be passed to actual LLVM IR function.
  1237. class ClangToLLVMArgMapping {
  1238. static const unsigned InvalidIndex = ~0U;
  1239. unsigned InallocaArgNo;
  1240. unsigned SRetArgNo;
  1241. unsigned TotalIRArgs;
  1242. /// Arguments of LLVM IR function corresponding to single Clang argument.
  1243. struct IRArgs {
  1244. unsigned PaddingArgIndex;
  1245. // Argument is expanded to IR arguments at positions
  1246. // [FirstArgIndex, FirstArgIndex + NumberOfArgs).
  1247. unsigned FirstArgIndex;
  1248. unsigned NumberOfArgs;
  1249. IRArgs()
  1250. : PaddingArgIndex(InvalidIndex), FirstArgIndex(InvalidIndex),
  1251. NumberOfArgs(0) {}
  1252. };
  1253. SmallVector<IRArgs, 8> ArgInfo;
  1254. public:
  1255. ClangToLLVMArgMapping(const ASTContext &Context, const CGFunctionInfo &FI,
  1256. bool OnlyRequiredArgs = false)
  1257. : InallocaArgNo(InvalidIndex), SRetArgNo(InvalidIndex), TotalIRArgs(0),
  1258. ArgInfo(OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size()) {
  1259. construct(Context, FI, OnlyRequiredArgs);
  1260. }
  1261. bool hasInallocaArg() const { return InallocaArgNo != InvalidIndex; }
  1262. unsigned getInallocaArgNo() const {
  1263. assert(hasInallocaArg());
  1264. return InallocaArgNo;
  1265. }
  1266. bool hasSRetArg() const { return SRetArgNo != InvalidIndex; }
  1267. unsigned getSRetArgNo() const {
  1268. assert(hasSRetArg());
  1269. return SRetArgNo;
  1270. }
  1271. unsigned totalIRArgs() const { return TotalIRArgs; }
  1272. bool hasPaddingArg(unsigned ArgNo) const {
  1273. assert(ArgNo < ArgInfo.size());
  1274. return ArgInfo[ArgNo].PaddingArgIndex != InvalidIndex;
  1275. }
  1276. unsigned getPaddingArgNo(unsigned ArgNo) const {
  1277. assert(hasPaddingArg(ArgNo));
  1278. return ArgInfo[ArgNo].PaddingArgIndex;
  1279. }
  1280. /// Returns index of first IR argument corresponding to ArgNo, and their
  1281. /// quantity.
  1282. std::pair<unsigned, unsigned> getIRArgs(unsigned ArgNo) const {
  1283. assert(ArgNo < ArgInfo.size());
  1284. return std::make_pair(ArgInfo[ArgNo].FirstArgIndex,
  1285. ArgInfo[ArgNo].NumberOfArgs);
  1286. }
  1287. private:
  1288. void construct(const ASTContext &Context, const CGFunctionInfo &FI,
  1289. bool OnlyRequiredArgs);
  1290. };
  1291. void ClangToLLVMArgMapping::construct(const ASTContext &Context,
  1292. const CGFunctionInfo &FI,
  1293. bool OnlyRequiredArgs) {
  1294. unsigned IRArgNo = 0;
  1295. bool SwapThisWithSRet = false;
  1296. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1297. if (RetAI.getKind() == ABIArgInfo::Indirect) {
  1298. SwapThisWithSRet = RetAI.isSRetAfterThis();
  1299. SRetArgNo = SwapThisWithSRet ? 1 : IRArgNo++;
  1300. }
  1301. unsigned ArgNo = 0;
  1302. unsigned NumArgs = OnlyRequiredArgs ? FI.getNumRequiredArgs() : FI.arg_size();
  1303. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(); ArgNo < NumArgs;
  1304. ++I, ++ArgNo) {
  1305. assert(I != FI.arg_end());
  1306. QualType ArgType = I->type;
  1307. const ABIArgInfo &AI = I->info;
  1308. // Collect data about IR arguments corresponding to Clang argument ArgNo.
  1309. auto &IRArgs = ArgInfo[ArgNo];
  1310. if (AI.getPaddingType())
  1311. IRArgs.PaddingArgIndex = IRArgNo++;
  1312. switch (AI.getKind()) {
  1313. case ABIArgInfo::Extend:
  1314. case ABIArgInfo::Direct: {
  1315. // FIXME: handle sseregparm someday...
  1316. llvm::StructType *STy = dyn_cast<llvm::StructType>(AI.getCoerceToType());
  1317. if (AI.isDirect() && AI.getCanBeFlattened() && STy) {
  1318. IRArgs.NumberOfArgs = STy->getNumElements();
  1319. } else {
  1320. IRArgs.NumberOfArgs = 1;
  1321. }
  1322. break;
  1323. }
  1324. case ABIArgInfo::Indirect:
  1325. case ABIArgInfo::IndirectAliased:
  1326. IRArgs.NumberOfArgs = 1;
  1327. break;
  1328. case ABIArgInfo::Ignore:
  1329. case ABIArgInfo::InAlloca:
  1330. // ignore and inalloca doesn't have matching LLVM parameters.
  1331. IRArgs.NumberOfArgs = 0;
  1332. break;
  1333. case ABIArgInfo::CoerceAndExpand:
  1334. IRArgs.NumberOfArgs = AI.getCoerceAndExpandTypeSequence().size();
  1335. break;
  1336. case ABIArgInfo::Expand:
  1337. IRArgs.NumberOfArgs = getExpansionSize(ArgType, Context);
  1338. break;
  1339. }
  1340. if (IRArgs.NumberOfArgs > 0) {
  1341. IRArgs.FirstArgIndex = IRArgNo;
  1342. IRArgNo += IRArgs.NumberOfArgs;
  1343. }
  1344. // Skip over the sret parameter when it comes second. We already handled it
  1345. // above.
  1346. if (IRArgNo == 1 && SwapThisWithSRet)
  1347. IRArgNo++;
  1348. }
  1349. assert(ArgNo == ArgInfo.size());
  1350. if (FI.usesInAlloca())
  1351. InallocaArgNo = IRArgNo++;
  1352. TotalIRArgs = IRArgNo;
  1353. }
  1354. } // namespace
  1355. /***/
  1356. bool CodeGenModule::ReturnTypeUsesSRet(const CGFunctionInfo &FI) {
  1357. const auto &RI = FI.getReturnInfo();
  1358. return RI.isIndirect() || (RI.isInAlloca() && RI.getInAllocaSRet());
  1359. }
  1360. bool CodeGenModule::ReturnSlotInterferesWithArgs(const CGFunctionInfo &FI) {
  1361. return ReturnTypeUsesSRet(FI) &&
  1362. getTargetCodeGenInfo().doesReturnSlotInterfereWithArgs();
  1363. }
  1364. bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
  1365. if (const BuiltinType *BT = ResultType->getAs<BuiltinType>()) {
  1366. switch (BT->getKind()) {
  1367. default:
  1368. return false;
  1369. case BuiltinType::Float:
  1370. return getTarget().useObjCFPRetForRealType(FloatModeKind::Float);
  1371. case BuiltinType::Double:
  1372. return getTarget().useObjCFPRetForRealType(FloatModeKind::Double);
  1373. case BuiltinType::LongDouble:
  1374. return getTarget().useObjCFPRetForRealType(FloatModeKind::LongDouble);
  1375. }
  1376. }
  1377. return false;
  1378. }
  1379. bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
  1380. if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
  1381. if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
  1382. if (BT->getKind() == BuiltinType::LongDouble)
  1383. return getTarget().useObjCFP2RetForComplexLongDouble();
  1384. }
  1385. }
  1386. return false;
  1387. }
  1388. llvm::FunctionType *CodeGenTypes::GetFunctionType(GlobalDecl GD) {
  1389. const CGFunctionInfo &FI = arrangeGlobalDeclaration(GD);
  1390. return GetFunctionType(FI);
  1391. }
  1392. llvm::FunctionType *
  1393. CodeGenTypes::GetFunctionType(const CGFunctionInfo &FI) {
  1394. bool Inserted = FunctionsBeingProcessed.insert(&FI).second;
  1395. (void)Inserted;
  1396. assert(Inserted && "Recursively being processed?");
  1397. llvm::Type *resultType = nullptr;
  1398. const ABIArgInfo &retAI = FI.getReturnInfo();
  1399. switch (retAI.getKind()) {
  1400. case ABIArgInfo::Expand:
  1401. case ABIArgInfo::IndirectAliased:
  1402. llvm_unreachable("Invalid ABI kind for return argument");
  1403. case ABIArgInfo::Extend:
  1404. case ABIArgInfo::Direct:
  1405. resultType = retAI.getCoerceToType();
  1406. break;
  1407. case ABIArgInfo::InAlloca:
  1408. if (retAI.getInAllocaSRet()) {
  1409. // sret things on win32 aren't void, they return the sret pointer.
  1410. QualType ret = FI.getReturnType();
  1411. llvm::Type *ty = ConvertType(ret);
  1412. unsigned addressSpace = Context.getTargetAddressSpace(ret);
  1413. resultType = llvm::PointerType::get(ty, addressSpace);
  1414. } else {
  1415. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1416. }
  1417. break;
  1418. case ABIArgInfo::Indirect:
  1419. case ABIArgInfo::Ignore:
  1420. resultType = llvm::Type::getVoidTy(getLLVMContext());
  1421. break;
  1422. case ABIArgInfo::CoerceAndExpand:
  1423. resultType = retAI.getUnpaddedCoerceAndExpandType();
  1424. break;
  1425. }
  1426. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI, true);
  1427. SmallVector<llvm::Type*, 8> ArgTypes(IRFunctionArgs.totalIRArgs());
  1428. // Add type for sret argument.
  1429. if (IRFunctionArgs.hasSRetArg()) {
  1430. QualType Ret = FI.getReturnType();
  1431. llvm::Type *Ty = ConvertType(Ret);
  1432. unsigned AddressSpace = Context.getTargetAddressSpace(Ret);
  1433. ArgTypes[IRFunctionArgs.getSRetArgNo()] =
  1434. llvm::PointerType::get(Ty, AddressSpace);
  1435. }
  1436. // Add type for inalloca argument.
  1437. if (IRFunctionArgs.hasInallocaArg()) {
  1438. auto ArgStruct = FI.getArgStruct();
  1439. assert(ArgStruct);
  1440. ArgTypes[IRFunctionArgs.getInallocaArgNo()] = ArgStruct->getPointerTo();
  1441. }
  1442. // Add in all of the required arguments.
  1443. unsigned ArgNo = 0;
  1444. CGFunctionInfo::const_arg_iterator it = FI.arg_begin(),
  1445. ie = it + FI.getNumRequiredArgs();
  1446. for (; it != ie; ++it, ++ArgNo) {
  1447. const ABIArgInfo &ArgInfo = it->info;
  1448. // Insert a padding type to ensure proper alignment.
  1449. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  1450. ArgTypes[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  1451. ArgInfo.getPaddingType();
  1452. unsigned FirstIRArg, NumIRArgs;
  1453. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  1454. switch (ArgInfo.getKind()) {
  1455. case ABIArgInfo::Ignore:
  1456. case ABIArgInfo::InAlloca:
  1457. assert(NumIRArgs == 0);
  1458. break;
  1459. case ABIArgInfo::Indirect: {
  1460. assert(NumIRArgs == 1);
  1461. // indirect arguments are always on the stack, which is alloca addr space.
  1462. llvm::Type *LTy = ConvertTypeForMem(it->type);
  1463. ArgTypes[FirstIRArg] = LTy->getPointerTo(
  1464. CGM.getDataLayout().getAllocaAddrSpace());
  1465. break;
  1466. }
  1467. case ABIArgInfo::IndirectAliased: {
  1468. assert(NumIRArgs == 1);
  1469. llvm::Type *LTy = ConvertTypeForMem(it->type);
  1470. ArgTypes[FirstIRArg] = LTy->getPointerTo(ArgInfo.getIndirectAddrSpace());
  1471. break;
  1472. }
  1473. case ABIArgInfo::Extend:
  1474. case ABIArgInfo::Direct: {
  1475. // Fast-isel and the optimizer generally like scalar values better than
  1476. // FCAs, so we flatten them if this is safe to do for this argument.
  1477. llvm::Type *argType = ArgInfo.getCoerceToType();
  1478. llvm::StructType *st = dyn_cast<llvm::StructType>(argType);
  1479. if (st && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  1480. assert(NumIRArgs == st->getNumElements());
  1481. for (unsigned i = 0, e = st->getNumElements(); i != e; ++i)
  1482. ArgTypes[FirstIRArg + i] = st->getElementType(i);
  1483. } else {
  1484. assert(NumIRArgs == 1);
  1485. ArgTypes[FirstIRArg] = argType;
  1486. }
  1487. break;
  1488. }
  1489. case ABIArgInfo::CoerceAndExpand: {
  1490. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1491. for (auto EltTy : ArgInfo.getCoerceAndExpandTypeSequence()) {
  1492. *ArgTypesIter++ = EltTy;
  1493. }
  1494. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1495. break;
  1496. }
  1497. case ABIArgInfo::Expand:
  1498. auto ArgTypesIter = ArgTypes.begin() + FirstIRArg;
  1499. getExpandedTypes(it->type, ArgTypesIter);
  1500. assert(ArgTypesIter == ArgTypes.begin() + FirstIRArg + NumIRArgs);
  1501. break;
  1502. }
  1503. }
  1504. bool Erased = FunctionsBeingProcessed.erase(&FI); (void)Erased;
  1505. assert(Erased && "Not in set?");
  1506. return llvm::FunctionType::get(resultType, ArgTypes, FI.isVariadic());
  1507. }
  1508. llvm::Type *CodeGenTypes::GetFunctionTypeForVTable(GlobalDecl GD) {
  1509. const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl());
  1510. const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
  1511. if (!isFuncTypeConvertible(FPT))
  1512. return llvm::StructType::get(getLLVMContext());
  1513. return GetFunctionType(GD);
  1514. }
  1515. static void AddAttributesFromFunctionProtoType(ASTContext &Ctx,
  1516. llvm::AttrBuilder &FuncAttrs,
  1517. const FunctionProtoType *FPT) {
  1518. if (!FPT)
  1519. return;
  1520. if (!isUnresolvedExceptionSpec(FPT->getExceptionSpecType()) &&
  1521. FPT->isNothrow())
  1522. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1523. }
  1524. static void AddAttributesFromAssumes(llvm::AttrBuilder &FuncAttrs,
  1525. const Decl *Callee) {
  1526. if (!Callee)
  1527. return;
  1528. SmallVector<StringRef, 4> Attrs;
  1529. for (const AssumptionAttr *AA : Callee->specific_attrs<AssumptionAttr>())
  1530. AA->getAssumption().split(Attrs, ",");
  1531. if (!Attrs.empty())
  1532. FuncAttrs.addAttribute(llvm::AssumptionAttrKey,
  1533. llvm::join(Attrs.begin(), Attrs.end(), ","));
  1534. }
  1535. bool CodeGenModule::MayDropFunctionReturn(const ASTContext &Context,
  1536. QualType ReturnType) {
  1537. // We can't just discard the return value for a record type with a
  1538. // complex destructor or a non-trivially copyable type.
  1539. if (const RecordType *RT =
  1540. ReturnType.getCanonicalType()->getAs<RecordType>()) {
  1541. if (const auto *ClassDecl = dyn_cast<CXXRecordDecl>(RT->getDecl()))
  1542. return ClassDecl->hasTrivialDestructor();
  1543. }
  1544. return ReturnType.isTriviallyCopyableType(Context);
  1545. }
  1546. void CodeGenModule::getDefaultFunctionAttributes(StringRef Name,
  1547. bool HasOptnone,
  1548. bool AttrOnCallSite,
  1549. llvm::AttrBuilder &FuncAttrs) {
  1550. // OptimizeNoneAttr takes precedence over -Os or -Oz. No warning needed.
  1551. if (!HasOptnone) {
  1552. if (CodeGenOpts.OptimizeSize)
  1553. FuncAttrs.addAttribute(llvm::Attribute::OptimizeForSize);
  1554. if (CodeGenOpts.OptimizeSize == 2)
  1555. FuncAttrs.addAttribute(llvm::Attribute::MinSize);
  1556. }
  1557. if (CodeGenOpts.DisableRedZone)
  1558. FuncAttrs.addAttribute(llvm::Attribute::NoRedZone);
  1559. if (CodeGenOpts.IndirectTlsSegRefs)
  1560. FuncAttrs.addAttribute("indirect-tls-seg-refs");
  1561. if (CodeGenOpts.NoImplicitFloat)
  1562. FuncAttrs.addAttribute(llvm::Attribute::NoImplicitFloat);
  1563. if (AttrOnCallSite) {
  1564. // Attributes that should go on the call site only.
  1565. if (!CodeGenOpts.SimplifyLibCalls || LangOpts.isNoBuiltinFunc(Name))
  1566. FuncAttrs.addAttribute(llvm::Attribute::NoBuiltin);
  1567. if (!CodeGenOpts.TrapFuncName.empty())
  1568. FuncAttrs.addAttribute("trap-func-name", CodeGenOpts.TrapFuncName);
  1569. } else {
  1570. StringRef FpKind;
  1571. switch (CodeGenOpts.getFramePointer()) {
  1572. case CodeGenOptions::FramePointerKind::None:
  1573. FpKind = "none";
  1574. break;
  1575. case CodeGenOptions::FramePointerKind::NonLeaf:
  1576. FpKind = "non-leaf";
  1577. break;
  1578. case CodeGenOptions::FramePointerKind::All:
  1579. FpKind = "all";
  1580. break;
  1581. }
  1582. FuncAttrs.addAttribute("frame-pointer", FpKind);
  1583. if (CodeGenOpts.LessPreciseFPMAD)
  1584. FuncAttrs.addAttribute("less-precise-fpmad", "true");
  1585. if (CodeGenOpts.NullPointerIsValid)
  1586. FuncAttrs.addAttribute(llvm::Attribute::NullPointerIsValid);
  1587. if (CodeGenOpts.FPDenormalMode != llvm::DenormalMode::getIEEE())
  1588. FuncAttrs.addAttribute("denormal-fp-math",
  1589. CodeGenOpts.FPDenormalMode.str());
  1590. if (CodeGenOpts.FP32DenormalMode != CodeGenOpts.FPDenormalMode) {
  1591. FuncAttrs.addAttribute(
  1592. "denormal-fp-math-f32",
  1593. CodeGenOpts.FP32DenormalMode.str());
  1594. }
  1595. if (LangOpts.getFPExceptionMode() == LangOptions::FPE_Ignore)
  1596. FuncAttrs.addAttribute("no-trapping-math", "true");
  1597. // TODO: Are these all needed?
  1598. // unsafe/inf/nan/nsz are handled by instruction-level FastMathFlags.
  1599. if (LangOpts.NoHonorInfs)
  1600. FuncAttrs.addAttribute("no-infs-fp-math", "true");
  1601. if (LangOpts.NoHonorNaNs)
  1602. FuncAttrs.addAttribute("no-nans-fp-math", "true");
  1603. if (LangOpts.ApproxFunc)
  1604. FuncAttrs.addAttribute("approx-func-fp-math", "true");
  1605. if (LangOpts.UnsafeFPMath)
  1606. FuncAttrs.addAttribute("unsafe-fp-math", "true");
  1607. if (CodeGenOpts.SoftFloat)
  1608. FuncAttrs.addAttribute("use-soft-float", "true");
  1609. FuncAttrs.addAttribute("stack-protector-buffer-size",
  1610. llvm::utostr(CodeGenOpts.SSPBufferSize));
  1611. if (LangOpts.NoSignedZero)
  1612. FuncAttrs.addAttribute("no-signed-zeros-fp-math", "true");
  1613. // TODO: Reciprocal estimate codegen options should apply to instructions?
  1614. const std::vector<std::string> &Recips = CodeGenOpts.Reciprocals;
  1615. if (!Recips.empty())
  1616. FuncAttrs.addAttribute("reciprocal-estimates",
  1617. llvm::join(Recips, ","));
  1618. if (!CodeGenOpts.PreferVectorWidth.empty() &&
  1619. CodeGenOpts.PreferVectorWidth != "none")
  1620. FuncAttrs.addAttribute("prefer-vector-width",
  1621. CodeGenOpts.PreferVectorWidth);
  1622. if (CodeGenOpts.StackRealignment)
  1623. FuncAttrs.addAttribute("stackrealign");
  1624. if (CodeGenOpts.Backchain)
  1625. FuncAttrs.addAttribute("backchain");
  1626. if (CodeGenOpts.EnableSegmentedStacks)
  1627. FuncAttrs.addAttribute("split-stack");
  1628. if (CodeGenOpts.SpeculativeLoadHardening)
  1629. FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1630. }
  1631. if (getLangOpts().assumeFunctionsAreConvergent()) {
  1632. // Conservatively, mark all functions and calls in CUDA and OpenCL as
  1633. // convergent (meaning, they may call an intrinsically convergent op, such
  1634. // as __syncthreads() / barrier(), and so can't have certain optimizations
  1635. // applied around them). LLVM will remove this attribute where it safely
  1636. // can.
  1637. FuncAttrs.addAttribute(llvm::Attribute::Convergent);
  1638. }
  1639. if (getLangOpts().CUDA && getLangOpts().CUDAIsDevice) {
  1640. // Exceptions aren't supported in CUDA device code.
  1641. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1642. }
  1643. for (StringRef Attr : CodeGenOpts.DefaultFunctionAttrs) {
  1644. StringRef Var, Value;
  1645. std::tie(Var, Value) = Attr.split('=');
  1646. FuncAttrs.addAttribute(Var, Value);
  1647. }
  1648. }
  1649. void CodeGenModule::addDefaultFunctionDefinitionAttributes(llvm::Function &F) {
  1650. llvm::AttrBuilder FuncAttrs(F.getContext());
  1651. getDefaultFunctionAttributes(F.getName(), F.hasOptNone(),
  1652. /* AttrOnCallSite = */ false, FuncAttrs);
  1653. // TODO: call GetCPUAndFeaturesAttributes?
  1654. F.addFnAttrs(FuncAttrs);
  1655. }
  1656. void CodeGenModule::addDefaultFunctionDefinitionAttributes(
  1657. llvm::AttrBuilder &attrs) {
  1658. getDefaultFunctionAttributes(/*function name*/ "", /*optnone*/ false,
  1659. /*for call*/ false, attrs);
  1660. GetCPUAndFeaturesAttributes(GlobalDecl(), attrs);
  1661. }
  1662. static void addNoBuiltinAttributes(llvm::AttrBuilder &FuncAttrs,
  1663. const LangOptions &LangOpts,
  1664. const NoBuiltinAttr *NBA = nullptr) {
  1665. auto AddNoBuiltinAttr = [&FuncAttrs](StringRef BuiltinName) {
  1666. SmallString<32> AttributeName;
  1667. AttributeName += "no-builtin-";
  1668. AttributeName += BuiltinName;
  1669. FuncAttrs.addAttribute(AttributeName);
  1670. };
  1671. // First, handle the language options passed through -fno-builtin.
  1672. if (LangOpts.NoBuiltin) {
  1673. // -fno-builtin disables them all.
  1674. FuncAttrs.addAttribute("no-builtins");
  1675. return;
  1676. }
  1677. // Then, add attributes for builtins specified through -fno-builtin-<name>.
  1678. llvm::for_each(LangOpts.NoBuiltinFuncs, AddNoBuiltinAttr);
  1679. // Now, let's check the __attribute__((no_builtin("...")) attribute added to
  1680. // the source.
  1681. if (!NBA)
  1682. return;
  1683. // If there is a wildcard in the builtin names specified through the
  1684. // attribute, disable them all.
  1685. if (llvm::is_contained(NBA->builtinNames(), "*")) {
  1686. FuncAttrs.addAttribute("no-builtins");
  1687. return;
  1688. }
  1689. // And last, add the rest of the builtin names.
  1690. llvm::for_each(NBA->builtinNames(), AddNoBuiltinAttr);
  1691. }
  1692. static bool DetermineNoUndef(QualType QTy, CodeGenTypes &Types,
  1693. const llvm::DataLayout &DL, const ABIArgInfo &AI,
  1694. bool CheckCoerce = true) {
  1695. llvm::Type *Ty = Types.ConvertTypeForMem(QTy);
  1696. if (AI.getKind() == ABIArgInfo::Indirect)
  1697. return true;
  1698. if (AI.getKind() == ABIArgInfo::Extend)
  1699. return true;
  1700. if (!DL.typeSizeEqualsStoreSize(Ty))
  1701. // TODO: This will result in a modest amount of values not marked noundef
  1702. // when they could be. We care about values that *invisibly* contain undef
  1703. // bits from the perspective of LLVM IR.
  1704. return false;
  1705. if (CheckCoerce && AI.canHaveCoerceToType()) {
  1706. llvm::Type *CoerceTy = AI.getCoerceToType();
  1707. if (llvm::TypeSize::isKnownGT(DL.getTypeSizeInBits(CoerceTy),
  1708. DL.getTypeSizeInBits(Ty)))
  1709. // If we're coercing to a type with a greater size than the canonical one,
  1710. // we're introducing new undef bits.
  1711. // Coercing to a type of smaller or equal size is ok, as we know that
  1712. // there's no internal padding (typeSizeEqualsStoreSize).
  1713. return false;
  1714. }
  1715. if (QTy->isBitIntType())
  1716. return true;
  1717. if (QTy->isReferenceType())
  1718. return true;
  1719. if (QTy->isNullPtrType())
  1720. return false;
  1721. if (QTy->isMemberPointerType())
  1722. // TODO: Some member pointers are `noundef`, but it depends on the ABI. For
  1723. // now, never mark them.
  1724. return false;
  1725. if (QTy->isScalarType()) {
  1726. if (const ComplexType *Complex = dyn_cast<ComplexType>(QTy))
  1727. return DetermineNoUndef(Complex->getElementType(), Types, DL, AI, false);
  1728. return true;
  1729. }
  1730. if (const VectorType *Vector = dyn_cast<VectorType>(QTy))
  1731. return DetermineNoUndef(Vector->getElementType(), Types, DL, AI, false);
  1732. if (const MatrixType *Matrix = dyn_cast<MatrixType>(QTy))
  1733. return DetermineNoUndef(Matrix->getElementType(), Types, DL, AI, false);
  1734. if (const ArrayType *Array = dyn_cast<ArrayType>(QTy))
  1735. return DetermineNoUndef(Array->getElementType(), Types, DL, AI, false);
  1736. // TODO: Some structs may be `noundef`, in specific situations.
  1737. return false;
  1738. }
  1739. /// Construct the IR attribute list of a function or call.
  1740. ///
  1741. /// When adding an attribute, please consider where it should be handled:
  1742. ///
  1743. /// - getDefaultFunctionAttributes is for attributes that are essentially
  1744. /// part of the global target configuration (but perhaps can be
  1745. /// overridden on a per-function basis). Adding attributes there
  1746. /// will cause them to also be set in frontends that build on Clang's
  1747. /// target-configuration logic, as well as for code defined in library
  1748. /// modules such as CUDA's libdevice.
  1749. ///
  1750. /// - ConstructAttributeList builds on top of getDefaultFunctionAttributes
  1751. /// and adds declaration-specific, convention-specific, and
  1752. /// frontend-specific logic. The last is of particular importance:
  1753. /// attributes that restrict how the frontend generates code must be
  1754. /// added here rather than getDefaultFunctionAttributes.
  1755. ///
  1756. void CodeGenModule::ConstructAttributeList(StringRef Name,
  1757. const CGFunctionInfo &FI,
  1758. CGCalleeInfo CalleeInfo,
  1759. llvm::AttributeList &AttrList,
  1760. unsigned &CallingConv,
  1761. bool AttrOnCallSite, bool IsThunk) {
  1762. llvm::AttrBuilder FuncAttrs(getLLVMContext());
  1763. llvm::AttrBuilder RetAttrs(getLLVMContext());
  1764. // Collect function IR attributes from the CC lowering.
  1765. // We'll collect the paramete and result attributes later.
  1766. CallingConv = FI.getEffectiveCallingConvention();
  1767. if (FI.isNoReturn())
  1768. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1769. if (FI.isCmseNSCall())
  1770. FuncAttrs.addAttribute("cmse_nonsecure_call");
  1771. // Collect function IR attributes from the callee prototype if we have one.
  1772. AddAttributesFromFunctionProtoType(getContext(), FuncAttrs,
  1773. CalleeInfo.getCalleeFunctionProtoType());
  1774. const Decl *TargetDecl = CalleeInfo.getCalleeDecl().getDecl();
  1775. // Attach assumption attributes to the declaration. If this is a call
  1776. // site, attach assumptions from the caller to the call as well.
  1777. AddAttributesFromAssumes(FuncAttrs, TargetDecl);
  1778. bool HasOptnone = false;
  1779. // The NoBuiltinAttr attached to the target FunctionDecl.
  1780. const NoBuiltinAttr *NBA = nullptr;
  1781. // Collect function IR attributes based on declaration-specific
  1782. // information.
  1783. // FIXME: handle sseregparm someday...
  1784. if (TargetDecl) {
  1785. if (TargetDecl->hasAttr<ReturnsTwiceAttr>())
  1786. FuncAttrs.addAttribute(llvm::Attribute::ReturnsTwice);
  1787. if (TargetDecl->hasAttr<NoThrowAttr>())
  1788. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1789. if (TargetDecl->hasAttr<NoReturnAttr>())
  1790. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1791. if (TargetDecl->hasAttr<ColdAttr>())
  1792. FuncAttrs.addAttribute(llvm::Attribute::Cold);
  1793. if (TargetDecl->hasAttr<HotAttr>())
  1794. FuncAttrs.addAttribute(llvm::Attribute::Hot);
  1795. if (TargetDecl->hasAttr<NoDuplicateAttr>())
  1796. FuncAttrs.addAttribute(llvm::Attribute::NoDuplicate);
  1797. if (TargetDecl->hasAttr<ConvergentAttr>())
  1798. FuncAttrs.addAttribute(llvm::Attribute::Convergent);
  1799. if (const FunctionDecl *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1800. AddAttributesFromFunctionProtoType(
  1801. getContext(), FuncAttrs, Fn->getType()->getAs<FunctionProtoType>());
  1802. if (AttrOnCallSite && Fn->isReplaceableGlobalAllocationFunction()) {
  1803. // A sane operator new returns a non-aliasing pointer.
  1804. auto Kind = Fn->getDeclName().getCXXOverloadedOperator();
  1805. if (getCodeGenOpts().AssumeSaneOperatorNew &&
  1806. (Kind == OO_New || Kind == OO_Array_New))
  1807. RetAttrs.addAttribute(llvm::Attribute::NoAlias);
  1808. }
  1809. const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn);
  1810. const bool IsVirtualCall = MD && MD->isVirtual();
  1811. // Don't use [[noreturn]], _Noreturn or [[no_builtin]] for a call to a
  1812. // virtual function. These attributes are not inherited by overloads.
  1813. if (!(AttrOnCallSite && IsVirtualCall)) {
  1814. if (Fn->isNoReturn())
  1815. FuncAttrs.addAttribute(llvm::Attribute::NoReturn);
  1816. NBA = Fn->getAttr<NoBuiltinAttr>();
  1817. }
  1818. // Only place nomerge attribute on call sites, never functions. This
  1819. // allows it to work on indirect virtual function calls.
  1820. if (AttrOnCallSite && TargetDecl->hasAttr<NoMergeAttr>())
  1821. FuncAttrs.addAttribute(llvm::Attribute::NoMerge);
  1822. }
  1823. // 'const', 'pure' and 'noalias' attributed functions are also nounwind.
  1824. if (TargetDecl->hasAttr<ConstAttr>()) {
  1825. FuncAttrs.addAttribute(llvm::Attribute::ReadNone);
  1826. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1827. // gcc specifies that 'const' functions have greater restrictions than
  1828. // 'pure' functions, so they also cannot have infinite loops.
  1829. FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
  1830. } else if (TargetDecl->hasAttr<PureAttr>()) {
  1831. FuncAttrs.addAttribute(llvm::Attribute::ReadOnly);
  1832. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1833. // gcc specifies that 'pure' functions cannot have infinite loops.
  1834. FuncAttrs.addAttribute(llvm::Attribute::WillReturn);
  1835. } else if (TargetDecl->hasAttr<NoAliasAttr>()) {
  1836. FuncAttrs.addAttribute(llvm::Attribute::ArgMemOnly);
  1837. FuncAttrs.addAttribute(llvm::Attribute::NoUnwind);
  1838. }
  1839. if (TargetDecl->hasAttr<RestrictAttr>())
  1840. RetAttrs.addAttribute(llvm::Attribute::NoAlias);
  1841. if (TargetDecl->hasAttr<ReturnsNonNullAttr>() &&
  1842. !CodeGenOpts.NullPointerIsValid)
  1843. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  1844. if (TargetDecl->hasAttr<AnyX86NoCallerSavedRegistersAttr>())
  1845. FuncAttrs.addAttribute("no_caller_saved_registers");
  1846. if (TargetDecl->hasAttr<AnyX86NoCfCheckAttr>())
  1847. FuncAttrs.addAttribute(llvm::Attribute::NoCfCheck);
  1848. if (TargetDecl->hasAttr<LeafAttr>())
  1849. FuncAttrs.addAttribute(llvm::Attribute::NoCallback);
  1850. HasOptnone = TargetDecl->hasAttr<OptimizeNoneAttr>();
  1851. if (auto *AllocSize = TargetDecl->getAttr<AllocSizeAttr>()) {
  1852. Optional<unsigned> NumElemsParam;
  1853. if (AllocSize->getNumElemsParam().isValid())
  1854. NumElemsParam = AllocSize->getNumElemsParam().getLLVMIndex();
  1855. FuncAttrs.addAllocSizeAttr(AllocSize->getElemSizeParam().getLLVMIndex(),
  1856. NumElemsParam);
  1857. }
  1858. if (TargetDecl->hasAttr<OpenCLKernelAttr>()) {
  1859. if (getLangOpts().OpenCLVersion <= 120) {
  1860. // OpenCL v1.2 Work groups are always uniform
  1861. FuncAttrs.addAttribute("uniform-work-group-size", "true");
  1862. } else {
  1863. // OpenCL v2.0 Work groups may be whether uniform or not.
  1864. // '-cl-uniform-work-group-size' compile option gets a hint
  1865. // to the compiler that the global work-size be a multiple of
  1866. // the work-group size specified to clEnqueueNDRangeKernel
  1867. // (i.e. work groups are uniform).
  1868. FuncAttrs.addAttribute("uniform-work-group-size",
  1869. llvm::toStringRef(CodeGenOpts.UniformWGSize));
  1870. }
  1871. }
  1872. }
  1873. // Attach "no-builtins" attributes to:
  1874. // * call sites: both `nobuiltin` and "no-builtins" or "no-builtin-<name>".
  1875. // * definitions: "no-builtins" or "no-builtin-<name>" only.
  1876. // The attributes can come from:
  1877. // * LangOpts: -ffreestanding, -fno-builtin, -fno-builtin-<name>
  1878. // * FunctionDecl attributes: __attribute__((no_builtin(...)))
  1879. addNoBuiltinAttributes(FuncAttrs, getLangOpts(), NBA);
  1880. // Collect function IR attributes based on global settiings.
  1881. getDefaultFunctionAttributes(Name, HasOptnone, AttrOnCallSite, FuncAttrs);
  1882. // Override some default IR attributes based on declaration-specific
  1883. // information.
  1884. if (TargetDecl) {
  1885. if (TargetDecl->hasAttr<NoSpeculativeLoadHardeningAttr>())
  1886. FuncAttrs.removeAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1887. if (TargetDecl->hasAttr<SpeculativeLoadHardeningAttr>())
  1888. FuncAttrs.addAttribute(llvm::Attribute::SpeculativeLoadHardening);
  1889. if (TargetDecl->hasAttr<NoSplitStackAttr>())
  1890. FuncAttrs.removeAttribute("split-stack");
  1891. // Add NonLazyBind attribute to function declarations when -fno-plt
  1892. // is used.
  1893. // FIXME: what if we just haven't processed the function definition
  1894. // yet, or if it's an external definition like C99 inline?
  1895. if (CodeGenOpts.NoPLT) {
  1896. if (auto *Fn = dyn_cast<FunctionDecl>(TargetDecl)) {
  1897. if (!Fn->isDefined() && !AttrOnCallSite) {
  1898. FuncAttrs.addAttribute(llvm::Attribute::NonLazyBind);
  1899. }
  1900. }
  1901. }
  1902. }
  1903. // Add "sample-profile-suffix-elision-policy" attribute for internal linkage
  1904. // functions with -funique-internal-linkage-names.
  1905. if (TargetDecl && CodeGenOpts.UniqueInternalLinkageNames) {
  1906. if (isa<FunctionDecl>(TargetDecl)) {
  1907. if (this->getFunctionLinkage(CalleeInfo.getCalleeDecl()) ==
  1908. llvm::GlobalValue::InternalLinkage)
  1909. FuncAttrs.addAttribute("sample-profile-suffix-elision-policy",
  1910. "selected");
  1911. }
  1912. }
  1913. // Collect non-call-site function IR attributes from declaration-specific
  1914. // information.
  1915. if (!AttrOnCallSite) {
  1916. if (TargetDecl && TargetDecl->hasAttr<CmseNSEntryAttr>())
  1917. FuncAttrs.addAttribute("cmse_nonsecure_entry");
  1918. // Whether tail calls are enabled.
  1919. auto shouldDisableTailCalls = [&] {
  1920. // Should this be honored in getDefaultFunctionAttributes?
  1921. if (CodeGenOpts.DisableTailCalls)
  1922. return true;
  1923. if (!TargetDecl)
  1924. return false;
  1925. if (TargetDecl->hasAttr<DisableTailCallsAttr>() ||
  1926. TargetDecl->hasAttr<AnyX86InterruptAttr>())
  1927. return true;
  1928. if (CodeGenOpts.NoEscapingBlockTailCalls) {
  1929. if (const auto *BD = dyn_cast<BlockDecl>(TargetDecl))
  1930. if (!BD->doesNotEscape())
  1931. return true;
  1932. }
  1933. return false;
  1934. };
  1935. if (shouldDisableTailCalls())
  1936. FuncAttrs.addAttribute("disable-tail-calls", "true");
  1937. // CPU/feature overrides. addDefaultFunctionDefinitionAttributes
  1938. // handles these separately to set them based on the global defaults.
  1939. GetCPUAndFeaturesAttributes(CalleeInfo.getCalleeDecl(), FuncAttrs);
  1940. }
  1941. // Collect attributes from arguments and return values.
  1942. ClangToLLVMArgMapping IRFunctionArgs(getContext(), FI);
  1943. QualType RetTy = FI.getReturnType();
  1944. const ABIArgInfo &RetAI = FI.getReturnInfo();
  1945. const llvm::DataLayout &DL = getDataLayout();
  1946. // C++ explicitly makes returning undefined values UB. C's rule only applies
  1947. // to used values, so we never mark them noundef for now.
  1948. bool HasStrictReturn = getLangOpts().CPlusPlus;
  1949. if (TargetDecl && HasStrictReturn) {
  1950. if (const FunctionDecl *FDecl = dyn_cast<FunctionDecl>(TargetDecl))
  1951. HasStrictReturn &= !FDecl->isExternC();
  1952. else if (const VarDecl *VDecl = dyn_cast<VarDecl>(TargetDecl))
  1953. // Function pointer
  1954. HasStrictReturn &= !VDecl->isExternC();
  1955. }
  1956. // We don't want to be too aggressive with the return checking, unless
  1957. // it's explicit in the code opts or we're using an appropriate sanitizer.
  1958. // Try to respect what the programmer intended.
  1959. HasStrictReturn &= getCodeGenOpts().StrictReturn ||
  1960. !MayDropFunctionReturn(getContext(), RetTy) ||
  1961. getLangOpts().Sanitize.has(SanitizerKind::Memory) ||
  1962. getLangOpts().Sanitize.has(SanitizerKind::Return);
  1963. // Determine if the return type could be partially undef
  1964. if (!CodeGenOpts.DisableNoundefAttrs && HasStrictReturn) {
  1965. if (!RetTy->isVoidType() && RetAI.getKind() != ABIArgInfo::Indirect &&
  1966. DetermineNoUndef(RetTy, getTypes(), DL, RetAI))
  1967. RetAttrs.addAttribute(llvm::Attribute::NoUndef);
  1968. }
  1969. switch (RetAI.getKind()) {
  1970. case ABIArgInfo::Extend:
  1971. if (RetAI.isSignExt())
  1972. RetAttrs.addAttribute(llvm::Attribute::SExt);
  1973. else
  1974. RetAttrs.addAttribute(llvm::Attribute::ZExt);
  1975. LLVM_FALLTHROUGH;
  1976. case ABIArgInfo::Direct:
  1977. if (RetAI.getInReg())
  1978. RetAttrs.addAttribute(llvm::Attribute::InReg);
  1979. break;
  1980. case ABIArgInfo::Ignore:
  1981. break;
  1982. case ABIArgInfo::InAlloca:
  1983. case ABIArgInfo::Indirect: {
  1984. // inalloca and sret disable readnone and readonly
  1985. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  1986. .removeAttribute(llvm::Attribute::ReadNone);
  1987. break;
  1988. }
  1989. case ABIArgInfo::CoerceAndExpand:
  1990. break;
  1991. case ABIArgInfo::Expand:
  1992. case ABIArgInfo::IndirectAliased:
  1993. llvm_unreachable("Invalid ABI kind for return argument");
  1994. }
  1995. if (!IsThunk) {
  1996. // FIXME: fix this properly, https://reviews.llvm.org/D100388
  1997. if (const auto *RefTy = RetTy->getAs<ReferenceType>()) {
  1998. QualType PTy = RefTy->getPointeeType();
  1999. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  2000. RetAttrs.addDereferenceableAttr(
  2001. getMinimumObjectSize(PTy).getQuantity());
  2002. if (getContext().getTargetAddressSpace(PTy) == 0 &&
  2003. !CodeGenOpts.NullPointerIsValid)
  2004. RetAttrs.addAttribute(llvm::Attribute::NonNull);
  2005. if (PTy->isObjectType()) {
  2006. llvm::Align Alignment =
  2007. getNaturalPointeeTypeAlignment(RetTy).getAsAlign();
  2008. RetAttrs.addAlignmentAttr(Alignment);
  2009. }
  2010. }
  2011. }
  2012. bool hasUsedSRet = false;
  2013. SmallVector<llvm::AttributeSet, 4> ArgAttrs(IRFunctionArgs.totalIRArgs());
  2014. // Attach attributes to sret.
  2015. if (IRFunctionArgs.hasSRetArg()) {
  2016. llvm::AttrBuilder SRETAttrs(getLLVMContext());
  2017. SRETAttrs.addStructRetAttr(getTypes().ConvertTypeForMem(RetTy));
  2018. hasUsedSRet = true;
  2019. if (RetAI.getInReg())
  2020. SRETAttrs.addAttribute(llvm::Attribute::InReg);
  2021. SRETAttrs.addAlignmentAttr(RetAI.getIndirectAlign().getQuantity());
  2022. ArgAttrs[IRFunctionArgs.getSRetArgNo()] =
  2023. llvm::AttributeSet::get(getLLVMContext(), SRETAttrs);
  2024. }
  2025. // Attach attributes to inalloca argument.
  2026. if (IRFunctionArgs.hasInallocaArg()) {
  2027. llvm::AttrBuilder Attrs(getLLVMContext());
  2028. Attrs.addInAllocaAttr(FI.getArgStruct());
  2029. ArgAttrs[IRFunctionArgs.getInallocaArgNo()] =
  2030. llvm::AttributeSet::get(getLLVMContext(), Attrs);
  2031. }
  2032. // Apply `nonnull`, `dereferencable(N)` and `align N` to the `this` argument,
  2033. // unless this is a thunk function.
  2034. // FIXME: fix this properly, https://reviews.llvm.org/D100388
  2035. if (FI.isInstanceMethod() && !IRFunctionArgs.hasInallocaArg() &&
  2036. !FI.arg_begin()->type->isVoidPointerType() && !IsThunk) {
  2037. auto IRArgs = IRFunctionArgs.getIRArgs(0);
  2038. assert(IRArgs.second == 1 && "Expected only a single `this` pointer.");
  2039. llvm::AttrBuilder Attrs(getLLVMContext());
  2040. QualType ThisTy =
  2041. FI.arg_begin()->type.castAs<PointerType>()->getPointeeType();
  2042. if (!CodeGenOpts.NullPointerIsValid &&
  2043. getContext().getTargetAddressSpace(FI.arg_begin()->type) == 0) {
  2044. Attrs.addAttribute(llvm::Attribute::NonNull);
  2045. Attrs.addDereferenceableAttr(getMinimumObjectSize(ThisTy).getQuantity());
  2046. } else {
  2047. // FIXME dereferenceable should be correct here, regardless of
  2048. // NullPointerIsValid. However, dereferenceable currently does not always
  2049. // respect NullPointerIsValid and may imply nonnull and break the program.
  2050. // See https://reviews.llvm.org/D66618 for discussions.
  2051. Attrs.addDereferenceableOrNullAttr(
  2052. getMinimumObjectSize(
  2053. FI.arg_begin()->type.castAs<PointerType>()->getPointeeType())
  2054. .getQuantity());
  2055. }
  2056. llvm::Align Alignment =
  2057. getNaturalTypeAlignment(ThisTy, /*BaseInfo=*/nullptr,
  2058. /*TBAAInfo=*/nullptr, /*forPointeeType=*/true)
  2059. .getAsAlign();
  2060. Attrs.addAlignmentAttr(Alignment);
  2061. ArgAttrs[IRArgs.first] = llvm::AttributeSet::get(getLLVMContext(), Attrs);
  2062. }
  2063. unsigned ArgNo = 0;
  2064. for (CGFunctionInfo::const_arg_iterator I = FI.arg_begin(),
  2065. E = FI.arg_end();
  2066. I != E; ++I, ++ArgNo) {
  2067. QualType ParamType = I->type;
  2068. const ABIArgInfo &AI = I->info;
  2069. llvm::AttrBuilder Attrs(getLLVMContext());
  2070. // Add attribute for padding argument, if necessary.
  2071. if (IRFunctionArgs.hasPaddingArg(ArgNo)) {
  2072. if (AI.getPaddingInReg()) {
  2073. ArgAttrs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  2074. llvm::AttributeSet::get(
  2075. getLLVMContext(),
  2076. llvm::AttrBuilder(getLLVMContext()).addAttribute(llvm::Attribute::InReg));
  2077. }
  2078. }
  2079. // Decide whether the argument we're handling could be partially undef
  2080. if (!CodeGenOpts.DisableNoundefAttrs &&
  2081. DetermineNoUndef(ParamType, getTypes(), DL, AI)) {
  2082. Attrs.addAttribute(llvm::Attribute::NoUndef);
  2083. }
  2084. // 'restrict' -> 'noalias' is done in EmitFunctionProlog when we
  2085. // have the corresponding parameter variable. It doesn't make
  2086. // sense to do it here because parameters are so messed up.
  2087. switch (AI.getKind()) {
  2088. case ABIArgInfo::Extend:
  2089. if (AI.isSignExt())
  2090. Attrs.addAttribute(llvm::Attribute::SExt);
  2091. else
  2092. Attrs.addAttribute(llvm::Attribute::ZExt);
  2093. LLVM_FALLTHROUGH;
  2094. case ABIArgInfo::Direct:
  2095. if (ArgNo == 0 && FI.isChainCall())
  2096. Attrs.addAttribute(llvm::Attribute::Nest);
  2097. else if (AI.getInReg())
  2098. Attrs.addAttribute(llvm::Attribute::InReg);
  2099. Attrs.addStackAlignmentAttr(llvm::MaybeAlign(AI.getDirectAlign()));
  2100. break;
  2101. case ABIArgInfo::Indirect: {
  2102. if (AI.getInReg())
  2103. Attrs.addAttribute(llvm::Attribute::InReg);
  2104. if (AI.getIndirectByVal())
  2105. Attrs.addByValAttr(getTypes().ConvertTypeForMem(ParamType));
  2106. auto *Decl = ParamType->getAsRecordDecl();
  2107. if (CodeGenOpts.PassByValueIsNoAlias && Decl &&
  2108. Decl->getArgPassingRestrictions() == RecordDecl::APK_CanPassInRegs)
  2109. // When calling the function, the pointer passed in will be the only
  2110. // reference to the underlying object. Mark it accordingly.
  2111. Attrs.addAttribute(llvm::Attribute::NoAlias);
  2112. // TODO: We could add the byref attribute if not byval, but it would
  2113. // require updating many testcases.
  2114. CharUnits Align = AI.getIndirectAlign();
  2115. // In a byval argument, it is important that the required
  2116. // alignment of the type is honored, as LLVM might be creating a
  2117. // *new* stack object, and needs to know what alignment to give
  2118. // it. (Sometimes it can deduce a sensible alignment on its own,
  2119. // but not if clang decides it must emit a packed struct, or the
  2120. // user specifies increased alignment requirements.)
  2121. //
  2122. // This is different from indirect *not* byval, where the object
  2123. // exists already, and the align attribute is purely
  2124. // informative.
  2125. assert(!Align.isZero());
  2126. // For now, only add this when we have a byval argument.
  2127. // TODO: be less lazy about updating test cases.
  2128. if (AI.getIndirectByVal())
  2129. Attrs.addAlignmentAttr(Align.getQuantity());
  2130. // byval disables readnone and readonly.
  2131. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  2132. .removeAttribute(llvm::Attribute::ReadNone);
  2133. break;
  2134. }
  2135. case ABIArgInfo::IndirectAliased: {
  2136. CharUnits Align = AI.getIndirectAlign();
  2137. Attrs.addByRefAttr(getTypes().ConvertTypeForMem(ParamType));
  2138. Attrs.addAlignmentAttr(Align.getQuantity());
  2139. break;
  2140. }
  2141. case ABIArgInfo::Ignore:
  2142. case ABIArgInfo::Expand:
  2143. case ABIArgInfo::CoerceAndExpand:
  2144. break;
  2145. case ABIArgInfo::InAlloca:
  2146. // inalloca disables readnone and readonly.
  2147. FuncAttrs.removeAttribute(llvm::Attribute::ReadOnly)
  2148. .removeAttribute(llvm::Attribute::ReadNone);
  2149. continue;
  2150. }
  2151. if (const auto *RefTy = ParamType->getAs<ReferenceType>()) {
  2152. QualType PTy = RefTy->getPointeeType();
  2153. if (!PTy->isIncompleteType() && PTy->isConstantSizeType())
  2154. Attrs.addDereferenceableAttr(
  2155. getMinimumObjectSize(PTy).getQuantity());
  2156. if (getContext().getTargetAddressSpace(PTy) == 0 &&
  2157. !CodeGenOpts.NullPointerIsValid)
  2158. Attrs.addAttribute(llvm::Attribute::NonNull);
  2159. if (PTy->isObjectType()) {
  2160. llvm::Align Alignment =
  2161. getNaturalPointeeTypeAlignment(ParamType).getAsAlign();
  2162. Attrs.addAlignmentAttr(Alignment);
  2163. }
  2164. }
  2165. switch (FI.getExtParameterInfo(ArgNo).getABI()) {
  2166. case ParameterABI::Ordinary:
  2167. break;
  2168. case ParameterABI::SwiftIndirectResult: {
  2169. // Add 'sret' if we haven't already used it for something, but
  2170. // only if the result is void.
  2171. if (!hasUsedSRet && RetTy->isVoidType()) {
  2172. Attrs.addStructRetAttr(getTypes().ConvertTypeForMem(ParamType));
  2173. hasUsedSRet = true;
  2174. }
  2175. // Add 'noalias' in either case.
  2176. Attrs.addAttribute(llvm::Attribute::NoAlias);
  2177. // Add 'dereferenceable' and 'alignment'.
  2178. auto PTy = ParamType->getPointeeType();
  2179. if (!PTy->isIncompleteType() && PTy->isConstantSizeType()) {
  2180. auto info = getContext().getTypeInfoInChars(PTy);
  2181. Attrs.addDereferenceableAttr(info.Width.getQuantity());
  2182. Attrs.addAlignmentAttr(info.Align.getAsAlign());
  2183. }
  2184. break;
  2185. }
  2186. case ParameterABI::SwiftErrorResult:
  2187. Attrs.addAttribute(llvm::Attribute::SwiftError);
  2188. break;
  2189. case ParameterABI::SwiftContext:
  2190. Attrs.addAttribute(llvm::Attribute::SwiftSelf);
  2191. break;
  2192. case ParameterABI::SwiftAsyncContext:
  2193. Attrs.addAttribute(llvm::Attribute::SwiftAsync);
  2194. break;
  2195. }
  2196. if (FI.getExtParameterInfo(ArgNo).isNoEscape())
  2197. Attrs.addAttribute(llvm::Attribute::NoCapture);
  2198. if (Attrs.hasAttributes()) {
  2199. unsigned FirstIRArg, NumIRArgs;
  2200. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  2201. for (unsigned i = 0; i < NumIRArgs; i++)
  2202. ArgAttrs[FirstIRArg + i] = ArgAttrs[FirstIRArg + i].addAttributes(
  2203. getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), Attrs));
  2204. }
  2205. }
  2206. assert(ArgNo == FI.arg_size());
  2207. AttrList = llvm::AttributeList::get(
  2208. getLLVMContext(), llvm::AttributeSet::get(getLLVMContext(), FuncAttrs),
  2209. llvm::AttributeSet::get(getLLVMContext(), RetAttrs), ArgAttrs);
  2210. }
  2211. /// An argument came in as a promoted argument; demote it back to its
  2212. /// declared type.
  2213. static llvm::Value *emitArgumentDemotion(CodeGenFunction &CGF,
  2214. const VarDecl *var,
  2215. llvm::Value *value) {
  2216. llvm::Type *varType = CGF.ConvertType(var->getType());
  2217. // This can happen with promotions that actually don't change the
  2218. // underlying type, like the enum promotions.
  2219. if (value->getType() == varType) return value;
  2220. assert((varType->isIntegerTy() || varType->isFloatingPointTy())
  2221. && "unexpected promotion type");
  2222. if (isa<llvm::IntegerType>(varType))
  2223. return CGF.Builder.CreateTrunc(value, varType, "arg.unpromote");
  2224. return CGF.Builder.CreateFPCast(value, varType, "arg.unpromote");
  2225. }
  2226. /// Returns the attribute (either parameter attribute, or function
  2227. /// attribute), which declares argument ArgNo to be non-null.
  2228. static const NonNullAttr *getNonNullAttr(const Decl *FD, const ParmVarDecl *PVD,
  2229. QualType ArgType, unsigned ArgNo) {
  2230. // FIXME: __attribute__((nonnull)) can also be applied to:
  2231. // - references to pointers, where the pointee is known to be
  2232. // nonnull (apparently a Clang extension)
  2233. // - transparent unions containing pointers
  2234. // In the former case, LLVM IR cannot represent the constraint. In
  2235. // the latter case, we have no guarantee that the transparent union
  2236. // is in fact passed as a pointer.
  2237. if (!ArgType->isAnyPointerType() && !ArgType->isBlockPointerType())
  2238. return nullptr;
  2239. // First, check attribute on parameter itself.
  2240. if (PVD) {
  2241. if (auto ParmNNAttr = PVD->getAttr<NonNullAttr>())
  2242. return ParmNNAttr;
  2243. }
  2244. // Check function attributes.
  2245. if (!FD)
  2246. return nullptr;
  2247. for (const auto *NNAttr : FD->specific_attrs<NonNullAttr>()) {
  2248. if (NNAttr->isNonNull(ArgNo))
  2249. return NNAttr;
  2250. }
  2251. return nullptr;
  2252. }
  2253. namespace {
  2254. struct CopyBackSwiftError final : EHScopeStack::Cleanup {
  2255. Address Temp;
  2256. Address Arg;
  2257. CopyBackSwiftError(Address temp, Address arg) : Temp(temp), Arg(arg) {}
  2258. void Emit(CodeGenFunction &CGF, Flags flags) override {
  2259. llvm::Value *errorValue = CGF.Builder.CreateLoad(Temp);
  2260. CGF.Builder.CreateStore(errorValue, Arg);
  2261. }
  2262. };
  2263. }
  2264. void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
  2265. llvm::Function *Fn,
  2266. const FunctionArgList &Args) {
  2267. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>())
  2268. // Naked functions don't have prologues.
  2269. return;
  2270. // If this is an implicit-return-zero function, go ahead and
  2271. // initialize the return value. TODO: it might be nice to have
  2272. // a more general mechanism for this that didn't require synthesized
  2273. // return statements.
  2274. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
  2275. if (FD->hasImplicitReturnZero()) {
  2276. QualType RetTy = FD->getReturnType().getUnqualifiedType();
  2277. llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
  2278. llvm::Constant* Zero = llvm::Constant::getNullValue(LLVMTy);
  2279. Builder.CreateStore(Zero, ReturnValue);
  2280. }
  2281. }
  2282. // FIXME: We no longer need the types from FunctionArgList; lift up and
  2283. // simplify.
  2284. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), FI);
  2285. assert(Fn->arg_size() == IRFunctionArgs.totalIRArgs());
  2286. // If we're using inalloca, all the memory arguments are GEPs off of the last
  2287. // parameter, which is a pointer to the complete memory area.
  2288. Address ArgStruct = Address::invalid();
  2289. if (IRFunctionArgs.hasInallocaArg()) {
  2290. ArgStruct = Address(Fn->getArg(IRFunctionArgs.getInallocaArgNo()),
  2291. FI.getArgStructAlignment());
  2292. assert(ArgStruct.getType() == FI.getArgStruct()->getPointerTo());
  2293. }
  2294. // Name the struct return parameter.
  2295. if (IRFunctionArgs.hasSRetArg()) {
  2296. auto AI = Fn->getArg(IRFunctionArgs.getSRetArgNo());
  2297. AI->setName("agg.result");
  2298. AI->addAttr(llvm::Attribute::NoAlias);
  2299. }
  2300. // Track if we received the parameter as a pointer (indirect, byval, or
  2301. // inalloca). If already have a pointer, EmitParmDecl doesn't need to copy it
  2302. // into a local alloca for us.
  2303. SmallVector<ParamValue, 16> ArgVals;
  2304. ArgVals.reserve(Args.size());
  2305. // Create a pointer value for every parameter declaration. This usually
  2306. // entails copying one or more LLVM IR arguments into an alloca. Don't push
  2307. // any cleanups or do anything that might unwind. We do that separately, so
  2308. // we can push the cleanups in the correct order for the ABI.
  2309. assert(FI.arg_size() == Args.size() &&
  2310. "Mismatch between function signature & arguments.");
  2311. unsigned ArgNo = 0;
  2312. CGFunctionInfo::const_arg_iterator info_it = FI.arg_begin();
  2313. for (FunctionArgList::const_iterator i = Args.begin(), e = Args.end();
  2314. i != e; ++i, ++info_it, ++ArgNo) {
  2315. const VarDecl *Arg = *i;
  2316. const ABIArgInfo &ArgI = info_it->info;
  2317. bool isPromoted =
  2318. isa<ParmVarDecl>(Arg) && cast<ParmVarDecl>(Arg)->isKNRPromoted();
  2319. // We are converting from ABIArgInfo type to VarDecl type directly, unless
  2320. // the parameter is promoted. In this case we convert to
  2321. // CGFunctionInfo::ArgInfo type with subsequent argument demotion.
  2322. QualType Ty = isPromoted ? info_it->type : Arg->getType();
  2323. assert(hasScalarEvaluationKind(Ty) ==
  2324. hasScalarEvaluationKind(Arg->getType()));
  2325. unsigned FirstIRArg, NumIRArgs;
  2326. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  2327. switch (ArgI.getKind()) {
  2328. case ABIArgInfo::InAlloca: {
  2329. assert(NumIRArgs == 0);
  2330. auto FieldIndex = ArgI.getInAllocaFieldIndex();
  2331. Address V =
  2332. Builder.CreateStructGEP(ArgStruct, FieldIndex, Arg->getName());
  2333. if (ArgI.getInAllocaIndirect())
  2334. V = Address(Builder.CreateLoad(V),
  2335. getContext().getTypeAlignInChars(Ty));
  2336. ArgVals.push_back(ParamValue::forIndirect(V));
  2337. break;
  2338. }
  2339. case ABIArgInfo::Indirect:
  2340. case ABIArgInfo::IndirectAliased: {
  2341. assert(NumIRArgs == 1);
  2342. Address ParamAddr = Address(Fn->getArg(FirstIRArg), ConvertTypeForMem(Ty),
  2343. ArgI.getIndirectAlign());
  2344. if (!hasScalarEvaluationKind(Ty)) {
  2345. // Aggregates and complex variables are accessed by reference. All we
  2346. // need to do is realign the value, if requested. Also, if the address
  2347. // may be aliased, copy it to ensure that the parameter variable is
  2348. // mutable and has a unique adress, as C requires.
  2349. Address V = ParamAddr;
  2350. if (ArgI.getIndirectRealign() || ArgI.isIndirectAliased()) {
  2351. Address AlignedTemp = CreateMemTemp(Ty, "coerce");
  2352. // Copy from the incoming argument pointer to the temporary with the
  2353. // appropriate alignment.
  2354. //
  2355. // FIXME: We should have a common utility for generating an aggregate
  2356. // copy.
  2357. CharUnits Size = getContext().getTypeSizeInChars(Ty);
  2358. Builder.CreateMemCpy(
  2359. AlignedTemp.getPointer(), AlignedTemp.getAlignment().getAsAlign(),
  2360. ParamAddr.getPointer(), ParamAddr.getAlignment().getAsAlign(),
  2361. llvm::ConstantInt::get(IntPtrTy, Size.getQuantity()));
  2362. V = AlignedTemp;
  2363. }
  2364. ArgVals.push_back(ParamValue::forIndirect(V));
  2365. } else {
  2366. // Load scalar value from indirect argument.
  2367. llvm::Value *V =
  2368. EmitLoadOfScalar(ParamAddr, false, Ty, Arg->getBeginLoc());
  2369. if (isPromoted)
  2370. V = emitArgumentDemotion(*this, Arg, V);
  2371. ArgVals.push_back(ParamValue::forDirect(V));
  2372. }
  2373. break;
  2374. }
  2375. case ABIArgInfo::Extend:
  2376. case ABIArgInfo::Direct: {
  2377. auto AI = Fn->getArg(FirstIRArg);
  2378. llvm::Type *LTy = ConvertType(Arg->getType());
  2379. // Prepare parameter attributes. So far, only attributes for pointer
  2380. // parameters are prepared. See
  2381. // http://llvm.org/docs/LangRef.html#paramattrs.
  2382. if (ArgI.getDirectOffset() == 0 && LTy->isPointerTy() &&
  2383. ArgI.getCoerceToType()->isPointerTy()) {
  2384. assert(NumIRArgs == 1);
  2385. if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(Arg)) {
  2386. // Set `nonnull` attribute if any.
  2387. if (getNonNullAttr(CurCodeDecl, PVD, PVD->getType(),
  2388. PVD->getFunctionScopeIndex()) &&
  2389. !CGM.getCodeGenOpts().NullPointerIsValid)
  2390. AI->addAttr(llvm::Attribute::NonNull);
  2391. QualType OTy = PVD->getOriginalType();
  2392. if (const auto *ArrTy =
  2393. getContext().getAsConstantArrayType(OTy)) {
  2394. // A C99 array parameter declaration with the static keyword also
  2395. // indicates dereferenceability, and if the size is constant we can
  2396. // use the dereferenceable attribute (which requires the size in
  2397. // bytes).
  2398. if (ArrTy->getSizeModifier() == ArrayType::Static) {
  2399. QualType ETy = ArrTy->getElementType();
  2400. llvm::Align Alignment =
  2401. CGM.getNaturalTypeAlignment(ETy).getAsAlign();
  2402. AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
  2403. uint64_t ArrSize = ArrTy->getSize().getZExtValue();
  2404. if (!ETy->isIncompleteType() && ETy->isConstantSizeType() &&
  2405. ArrSize) {
  2406. llvm::AttrBuilder Attrs(getLLVMContext());
  2407. Attrs.addDereferenceableAttr(
  2408. getContext().getTypeSizeInChars(ETy).getQuantity() *
  2409. ArrSize);
  2410. AI->addAttrs(Attrs);
  2411. } else if (getContext().getTargetInfo().getNullPointerValue(
  2412. ETy.getAddressSpace()) == 0 &&
  2413. !CGM.getCodeGenOpts().NullPointerIsValid) {
  2414. AI->addAttr(llvm::Attribute::NonNull);
  2415. }
  2416. }
  2417. } else if (const auto *ArrTy =
  2418. getContext().getAsVariableArrayType(OTy)) {
  2419. // For C99 VLAs with the static keyword, we don't know the size so
  2420. // we can't use the dereferenceable attribute, but in addrspace(0)
  2421. // we know that it must be nonnull.
  2422. if (ArrTy->getSizeModifier() == VariableArrayType::Static) {
  2423. QualType ETy = ArrTy->getElementType();
  2424. llvm::Align Alignment =
  2425. CGM.getNaturalTypeAlignment(ETy).getAsAlign();
  2426. AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(Alignment));
  2427. if (!getContext().getTargetAddressSpace(ETy) &&
  2428. !CGM.getCodeGenOpts().NullPointerIsValid)
  2429. AI->addAttr(llvm::Attribute::NonNull);
  2430. }
  2431. }
  2432. // Set `align` attribute if any.
  2433. const auto *AVAttr = PVD->getAttr<AlignValueAttr>();
  2434. if (!AVAttr)
  2435. if (const auto *TOTy = dyn_cast<TypedefType>(OTy))
  2436. AVAttr = TOTy->getDecl()->getAttr<AlignValueAttr>();
  2437. if (AVAttr && !SanOpts.has(SanitizerKind::Alignment)) {
  2438. // If alignment-assumption sanitizer is enabled, we do *not* add
  2439. // alignment attribute here, but emit normal alignment assumption,
  2440. // so the UBSAN check could function.
  2441. llvm::ConstantInt *AlignmentCI =
  2442. cast<llvm::ConstantInt>(EmitScalarExpr(AVAttr->getAlignment()));
  2443. uint64_t AlignmentInt =
  2444. AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment);
  2445. if (AI->getParamAlign().valueOrOne() < AlignmentInt) {
  2446. AI->removeAttr(llvm::Attribute::AttrKind::Alignment);
  2447. AI->addAttrs(llvm::AttrBuilder(getLLVMContext()).addAlignmentAttr(
  2448. llvm::Align(AlignmentInt)));
  2449. }
  2450. }
  2451. }
  2452. // Set 'noalias' if an argument type has the `restrict` qualifier.
  2453. if (Arg->getType().isRestrictQualified())
  2454. AI->addAttr(llvm::Attribute::NoAlias);
  2455. }
  2456. // Prepare the argument value. If we have the trivial case, handle it
  2457. // with no muss and fuss.
  2458. if (!isa<llvm::StructType>(ArgI.getCoerceToType()) &&
  2459. ArgI.getCoerceToType() == ConvertType(Ty) &&
  2460. ArgI.getDirectOffset() == 0) {
  2461. assert(NumIRArgs == 1);
  2462. // LLVM expects swifterror parameters to be used in very restricted
  2463. // ways. Copy the value into a less-restricted temporary.
  2464. llvm::Value *V = AI;
  2465. if (FI.getExtParameterInfo(ArgNo).getABI()
  2466. == ParameterABI::SwiftErrorResult) {
  2467. QualType pointeeTy = Ty->getPointeeType();
  2468. assert(pointeeTy->isPointerType());
  2469. Address temp =
  2470. CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
  2471. Address arg = Address(V, getContext().getTypeAlignInChars(pointeeTy));
  2472. llvm::Value *incomingErrorValue = Builder.CreateLoad(arg);
  2473. Builder.CreateStore(incomingErrorValue, temp);
  2474. V = temp.getPointer();
  2475. // Push a cleanup to copy the value back at the end of the function.
  2476. // The convention does not guarantee that the value will be written
  2477. // back if the function exits with an unwind exception.
  2478. EHStack.pushCleanup<CopyBackSwiftError>(NormalCleanup, temp, arg);
  2479. }
  2480. // Ensure the argument is the correct type.
  2481. if (V->getType() != ArgI.getCoerceToType())
  2482. V = Builder.CreateBitCast(V, ArgI.getCoerceToType());
  2483. if (isPromoted)
  2484. V = emitArgumentDemotion(*this, Arg, V);
  2485. // Because of merging of function types from multiple decls it is
  2486. // possible for the type of an argument to not match the corresponding
  2487. // type in the function type. Since we are codegening the callee
  2488. // in here, add a cast to the argument type.
  2489. llvm::Type *LTy = ConvertType(Arg->getType());
  2490. if (V->getType() != LTy)
  2491. V = Builder.CreateBitCast(V, LTy);
  2492. ArgVals.push_back(ParamValue::forDirect(V));
  2493. break;
  2494. }
  2495. // VLST arguments are coerced to VLATs at the function boundary for
  2496. // ABI consistency. If this is a VLST that was coerced to
  2497. // a VLAT at the function boundary and the types match up, use
  2498. // llvm.experimental.vector.extract to convert back to the original
  2499. // VLST.
  2500. if (auto *VecTyTo = dyn_cast<llvm::FixedVectorType>(ConvertType(Ty))) {
  2501. llvm::Value *Coerced = Fn->getArg(FirstIRArg);
  2502. if (auto *VecTyFrom =
  2503. dyn_cast<llvm::ScalableVectorType>(Coerced->getType())) {
  2504. // If we are casting a scalable 16 x i1 predicate vector to a fixed i8
  2505. // vector, bitcast the source and use a vector extract.
  2506. auto PredType =
  2507. llvm::ScalableVectorType::get(Builder.getInt1Ty(), 16);
  2508. if (VecTyFrom == PredType &&
  2509. VecTyTo->getElementType() == Builder.getInt8Ty()) {
  2510. VecTyFrom = llvm::ScalableVectorType::get(Builder.getInt8Ty(), 2);
  2511. Coerced = Builder.CreateBitCast(Coerced, VecTyFrom);
  2512. }
  2513. if (VecTyFrom->getElementType() == VecTyTo->getElementType()) {
  2514. llvm::Value *Zero = llvm::Constant::getNullValue(CGM.Int64Ty);
  2515. assert(NumIRArgs == 1);
  2516. Coerced->setName(Arg->getName() + ".coerce");
  2517. ArgVals.push_back(ParamValue::forDirect(Builder.CreateExtractVector(
  2518. VecTyTo, Coerced, Zero, "castFixedSve")));
  2519. break;
  2520. }
  2521. }
  2522. }
  2523. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg),
  2524. Arg->getName());
  2525. // Pointer to store into.
  2526. Address Ptr = emitAddressAtOffset(*this, Alloca, ArgI);
  2527. // Fast-isel and the optimizer generally like scalar values better than
  2528. // FCAs, so we flatten them if this is safe to do for this argument.
  2529. llvm::StructType *STy = dyn_cast<llvm::StructType>(ArgI.getCoerceToType());
  2530. if (ArgI.isDirect() && ArgI.getCanBeFlattened() && STy &&
  2531. STy->getNumElements() > 1) {
  2532. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(STy);
  2533. llvm::Type *DstTy = Ptr.getElementType();
  2534. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(DstTy);
  2535. Address AddrToStoreInto = Address::invalid();
  2536. if (SrcSize <= DstSize) {
  2537. AddrToStoreInto = Builder.CreateElementBitCast(Ptr, STy);
  2538. } else {
  2539. AddrToStoreInto =
  2540. CreateTempAlloca(STy, Alloca.getAlignment(), "coerce");
  2541. }
  2542. assert(STy->getNumElements() == NumIRArgs);
  2543. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  2544. auto AI = Fn->getArg(FirstIRArg + i);
  2545. AI->setName(Arg->getName() + ".coerce" + Twine(i));
  2546. Address EltPtr = Builder.CreateStructGEP(AddrToStoreInto, i);
  2547. Builder.CreateStore(AI, EltPtr);
  2548. }
  2549. if (SrcSize > DstSize) {
  2550. Builder.CreateMemCpy(Ptr, AddrToStoreInto, DstSize);
  2551. }
  2552. } else {
  2553. // Simple case, just do a coerced store of the argument into the alloca.
  2554. assert(NumIRArgs == 1);
  2555. auto AI = Fn->getArg(FirstIRArg);
  2556. AI->setName(Arg->getName() + ".coerce");
  2557. CreateCoercedStore(AI, Ptr, /*DstIsVolatile=*/false, *this);
  2558. }
  2559. // Match to what EmitParmDecl is expecting for this type.
  2560. if (CodeGenFunction::hasScalarEvaluationKind(Ty)) {
  2561. llvm::Value *V =
  2562. EmitLoadOfScalar(Alloca, false, Ty, Arg->getBeginLoc());
  2563. if (isPromoted)
  2564. V = emitArgumentDemotion(*this, Arg, V);
  2565. ArgVals.push_back(ParamValue::forDirect(V));
  2566. } else {
  2567. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  2568. }
  2569. break;
  2570. }
  2571. case ABIArgInfo::CoerceAndExpand: {
  2572. // Reconstruct into a temporary.
  2573. Address alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
  2574. ArgVals.push_back(ParamValue::forIndirect(alloca));
  2575. auto coercionType = ArgI.getCoerceAndExpandType();
  2576. alloca = Builder.CreateElementBitCast(alloca, coercionType);
  2577. unsigned argIndex = FirstIRArg;
  2578. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  2579. llvm::Type *eltType = coercionType->getElementType(i);
  2580. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType))
  2581. continue;
  2582. auto eltAddr = Builder.CreateStructGEP(alloca, i);
  2583. auto elt = Fn->getArg(argIndex++);
  2584. Builder.CreateStore(elt, eltAddr);
  2585. }
  2586. assert(argIndex == FirstIRArg + NumIRArgs);
  2587. break;
  2588. }
  2589. case ABIArgInfo::Expand: {
  2590. // If this structure was expanded into multiple arguments then
  2591. // we need to create a temporary and reconstruct it from the
  2592. // arguments.
  2593. Address Alloca = CreateMemTemp(Ty, getContext().getDeclAlign(Arg));
  2594. LValue LV = MakeAddrLValue(Alloca, Ty);
  2595. ArgVals.push_back(ParamValue::forIndirect(Alloca));
  2596. auto FnArgIter = Fn->arg_begin() + FirstIRArg;
  2597. ExpandTypeFromArgs(Ty, LV, FnArgIter);
  2598. assert(FnArgIter == Fn->arg_begin() + FirstIRArg + NumIRArgs);
  2599. for (unsigned i = 0, e = NumIRArgs; i != e; ++i) {
  2600. auto AI = Fn->getArg(FirstIRArg + i);
  2601. AI->setName(Arg->getName() + "." + Twine(i));
  2602. }
  2603. break;
  2604. }
  2605. case ABIArgInfo::Ignore:
  2606. assert(NumIRArgs == 0);
  2607. // Initialize the local variable appropriately.
  2608. if (!hasScalarEvaluationKind(Ty)) {
  2609. ArgVals.push_back(ParamValue::forIndirect(CreateMemTemp(Ty)));
  2610. } else {
  2611. llvm::Value *U = llvm::UndefValue::get(ConvertType(Arg->getType()));
  2612. ArgVals.push_back(ParamValue::forDirect(U));
  2613. }
  2614. break;
  2615. }
  2616. }
  2617. if (getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) {
  2618. for (int I = Args.size() - 1; I >= 0; --I)
  2619. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  2620. } else {
  2621. for (unsigned I = 0, E = Args.size(); I != E; ++I)
  2622. EmitParmDecl(*Args[I], ArgVals[I], I + 1);
  2623. }
  2624. }
  2625. static void eraseUnusedBitCasts(llvm::Instruction *insn) {
  2626. while (insn->use_empty()) {
  2627. llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(insn);
  2628. if (!bitcast) return;
  2629. // This is "safe" because we would have used a ConstantExpr otherwise.
  2630. insn = cast<llvm::Instruction>(bitcast->getOperand(0));
  2631. bitcast->eraseFromParent();
  2632. }
  2633. }
  2634. /// Try to emit a fused autorelease of a return result.
  2635. static llvm::Value *tryEmitFusedAutoreleaseOfResult(CodeGenFunction &CGF,
  2636. llvm::Value *result) {
  2637. // We must be immediately followed the cast.
  2638. llvm::BasicBlock *BB = CGF.Builder.GetInsertBlock();
  2639. if (BB->empty()) return nullptr;
  2640. if (&BB->back() != result) return nullptr;
  2641. llvm::Type *resultType = result->getType();
  2642. // result is in a BasicBlock and is therefore an Instruction.
  2643. llvm::Instruction *generator = cast<llvm::Instruction>(result);
  2644. SmallVector<llvm::Instruction *, 4> InstsToKill;
  2645. // Look for:
  2646. // %generator = bitcast %type1* %generator2 to %type2*
  2647. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(generator)) {
  2648. // We would have emitted this as a constant if the operand weren't
  2649. // an Instruction.
  2650. generator = cast<llvm::Instruction>(bitcast->getOperand(0));
  2651. // Require the generator to be immediately followed by the cast.
  2652. if (generator->getNextNode() != bitcast)
  2653. return nullptr;
  2654. InstsToKill.push_back(bitcast);
  2655. }
  2656. // Look for:
  2657. // %generator = call i8* @objc_retain(i8* %originalResult)
  2658. // or
  2659. // %generator = call i8* @objc_retainAutoreleasedReturnValue(i8* %originalResult)
  2660. llvm::CallInst *call = dyn_cast<llvm::CallInst>(generator);
  2661. if (!call) return nullptr;
  2662. bool doRetainAutorelease;
  2663. if (call->getCalledOperand() == CGF.CGM.getObjCEntrypoints().objc_retain) {
  2664. doRetainAutorelease = true;
  2665. } else if (call->getCalledOperand() ==
  2666. CGF.CGM.getObjCEntrypoints().objc_retainAutoreleasedReturnValue) {
  2667. doRetainAutorelease = false;
  2668. // If we emitted an assembly marker for this call (and the
  2669. // ARCEntrypoints field should have been set if so), go looking
  2670. // for that call. If we can't find it, we can't do this
  2671. // optimization. But it should always be the immediately previous
  2672. // instruction, unless we needed bitcasts around the call.
  2673. if (CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker) {
  2674. llvm::Instruction *prev = call->getPrevNode();
  2675. assert(prev);
  2676. if (isa<llvm::BitCastInst>(prev)) {
  2677. prev = prev->getPrevNode();
  2678. assert(prev);
  2679. }
  2680. assert(isa<llvm::CallInst>(prev));
  2681. assert(cast<llvm::CallInst>(prev)->getCalledOperand() ==
  2682. CGF.CGM.getObjCEntrypoints().retainAutoreleasedReturnValueMarker);
  2683. InstsToKill.push_back(prev);
  2684. }
  2685. } else {
  2686. return nullptr;
  2687. }
  2688. result = call->getArgOperand(0);
  2689. InstsToKill.push_back(call);
  2690. // Keep killing bitcasts, for sanity. Note that we no longer care
  2691. // about precise ordering as long as there's exactly one use.
  2692. while (llvm::BitCastInst *bitcast = dyn_cast<llvm::BitCastInst>(result)) {
  2693. if (!bitcast->hasOneUse()) break;
  2694. InstsToKill.push_back(bitcast);
  2695. result = bitcast->getOperand(0);
  2696. }
  2697. // Delete all the unnecessary instructions, from latest to earliest.
  2698. for (auto *I : InstsToKill)
  2699. I->eraseFromParent();
  2700. // Do the fused retain/autorelease if we were asked to.
  2701. if (doRetainAutorelease)
  2702. result = CGF.EmitARCRetainAutoreleaseReturnValue(result);
  2703. // Cast back to the result type.
  2704. return CGF.Builder.CreateBitCast(result, resultType);
  2705. }
  2706. /// If this is a +1 of the value of an immutable 'self', remove it.
  2707. static llvm::Value *tryRemoveRetainOfSelf(CodeGenFunction &CGF,
  2708. llvm::Value *result) {
  2709. // This is only applicable to a method with an immutable 'self'.
  2710. const ObjCMethodDecl *method =
  2711. dyn_cast_or_null<ObjCMethodDecl>(CGF.CurCodeDecl);
  2712. if (!method) return nullptr;
  2713. const VarDecl *self = method->getSelfDecl();
  2714. if (!self->getType().isConstQualified()) return nullptr;
  2715. // Look for a retain call.
  2716. llvm::CallInst *retainCall =
  2717. dyn_cast<llvm::CallInst>(result->stripPointerCasts());
  2718. if (!retainCall || retainCall->getCalledOperand() !=
  2719. CGF.CGM.getObjCEntrypoints().objc_retain)
  2720. return nullptr;
  2721. // Look for an ordinary load of 'self'.
  2722. llvm::Value *retainedValue = retainCall->getArgOperand(0);
  2723. llvm::LoadInst *load =
  2724. dyn_cast<llvm::LoadInst>(retainedValue->stripPointerCasts());
  2725. if (!load || load->isAtomic() || load->isVolatile() ||
  2726. load->getPointerOperand() != CGF.GetAddrOfLocalVar(self).getPointer())
  2727. return nullptr;
  2728. // Okay! Burn it all down. This relies for correctness on the
  2729. // assumption that the retain is emitted as part of the return and
  2730. // that thereafter everything is used "linearly".
  2731. llvm::Type *resultType = result->getType();
  2732. eraseUnusedBitCasts(cast<llvm::Instruction>(result));
  2733. assert(retainCall->use_empty());
  2734. retainCall->eraseFromParent();
  2735. eraseUnusedBitCasts(cast<llvm::Instruction>(retainedValue));
  2736. return CGF.Builder.CreateBitCast(load, resultType);
  2737. }
  2738. /// Emit an ARC autorelease of the result of a function.
  2739. ///
  2740. /// \return the value to actually return from the function
  2741. static llvm::Value *emitAutoreleaseOfResult(CodeGenFunction &CGF,
  2742. llvm::Value *result) {
  2743. // If we're returning 'self', kill the initial retain. This is a
  2744. // heuristic attempt to "encourage correctness" in the really unfortunate
  2745. // case where we have a return of self during a dealloc and we desperately
  2746. // need to avoid the possible autorelease.
  2747. if (llvm::Value *self = tryRemoveRetainOfSelf(CGF, result))
  2748. return self;
  2749. // At -O0, try to emit a fused retain/autorelease.
  2750. if (CGF.shouldUseFusedARCCalls())
  2751. if (llvm::Value *fused = tryEmitFusedAutoreleaseOfResult(CGF, result))
  2752. return fused;
  2753. return CGF.EmitARCAutoreleaseReturnValue(result);
  2754. }
  2755. /// Heuristically search for a dominating store to the return-value slot.
  2756. static llvm::StoreInst *findDominatingStoreToReturnValue(CodeGenFunction &CGF) {
  2757. // Check if a User is a store which pointerOperand is the ReturnValue.
  2758. // We are looking for stores to the ReturnValue, not for stores of the
  2759. // ReturnValue to some other location.
  2760. auto GetStoreIfValid = [&CGF](llvm::User *U) -> llvm::StoreInst * {
  2761. auto *SI = dyn_cast<llvm::StoreInst>(U);
  2762. if (!SI || SI->getPointerOperand() != CGF.ReturnValue.getPointer())
  2763. return nullptr;
  2764. // These aren't actually possible for non-coerced returns, and we
  2765. // only care about non-coerced returns on this code path.
  2766. assert(!SI->isAtomic() && !SI->isVolatile());
  2767. return SI;
  2768. };
  2769. // If there are multiple uses of the return-value slot, just check
  2770. // for something immediately preceding the IP. Sometimes this can
  2771. // happen with how we generate implicit-returns; it can also happen
  2772. // with noreturn cleanups.
  2773. if (!CGF.ReturnValue.getPointer()->hasOneUse()) {
  2774. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2775. if (IP->empty()) return nullptr;
  2776. llvm::Instruction *I = &IP->back();
  2777. // Skip lifetime markers
  2778. for (llvm::BasicBlock::reverse_iterator II = IP->rbegin(),
  2779. IE = IP->rend();
  2780. II != IE; ++II) {
  2781. if (llvm::IntrinsicInst *Intrinsic =
  2782. dyn_cast<llvm::IntrinsicInst>(&*II)) {
  2783. if (Intrinsic->getIntrinsicID() == llvm::Intrinsic::lifetime_end) {
  2784. const llvm::Value *CastAddr = Intrinsic->getArgOperand(1);
  2785. ++II;
  2786. if (II == IE)
  2787. break;
  2788. if (isa<llvm::BitCastInst>(&*II) && (CastAddr == &*II))
  2789. continue;
  2790. }
  2791. }
  2792. I = &*II;
  2793. break;
  2794. }
  2795. return GetStoreIfValid(I);
  2796. }
  2797. llvm::StoreInst *store =
  2798. GetStoreIfValid(CGF.ReturnValue.getPointer()->user_back());
  2799. if (!store) return nullptr;
  2800. // Now do a first-and-dirty dominance check: just walk up the
  2801. // single-predecessors chain from the current insertion point.
  2802. llvm::BasicBlock *StoreBB = store->getParent();
  2803. llvm::BasicBlock *IP = CGF.Builder.GetInsertBlock();
  2804. while (IP != StoreBB) {
  2805. if (!(IP = IP->getSinglePredecessor()))
  2806. return nullptr;
  2807. }
  2808. // Okay, the store's basic block dominates the insertion point; we
  2809. // can do our thing.
  2810. return store;
  2811. }
  2812. // Helper functions for EmitCMSEClearRecord
  2813. // Set the bits corresponding to a field having width `BitWidth` and located at
  2814. // offset `BitOffset` (from the least significant bit) within a storage unit of
  2815. // `Bits.size()` bytes. Each element of `Bits` corresponds to one target byte.
  2816. // Use little-endian layout, i.e.`Bits[0]` is the LSB.
  2817. static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int BitOffset,
  2818. int BitWidth, int CharWidth) {
  2819. assert(CharWidth <= 64);
  2820. assert(static_cast<unsigned>(BitWidth) <= Bits.size() * CharWidth);
  2821. int Pos = 0;
  2822. if (BitOffset >= CharWidth) {
  2823. Pos += BitOffset / CharWidth;
  2824. BitOffset = BitOffset % CharWidth;
  2825. }
  2826. const uint64_t Used = (uint64_t(1) << CharWidth) - 1;
  2827. if (BitOffset + BitWidth >= CharWidth) {
  2828. Bits[Pos++] |= (Used << BitOffset) & Used;
  2829. BitWidth -= CharWidth - BitOffset;
  2830. BitOffset = 0;
  2831. }
  2832. while (BitWidth >= CharWidth) {
  2833. Bits[Pos++] = Used;
  2834. BitWidth -= CharWidth;
  2835. }
  2836. if (BitWidth > 0)
  2837. Bits[Pos++] |= (Used >> (CharWidth - BitWidth)) << BitOffset;
  2838. }
  2839. // Set the bits corresponding to a field having width `BitWidth` and located at
  2840. // offset `BitOffset` (from the least significant bit) within a storage unit of
  2841. // `StorageSize` bytes, located at `StorageOffset` in `Bits`. Each element of
  2842. // `Bits` corresponds to one target byte. Use target endian layout.
  2843. static void setBitRange(SmallVectorImpl<uint64_t> &Bits, int StorageOffset,
  2844. int StorageSize, int BitOffset, int BitWidth,
  2845. int CharWidth, bool BigEndian) {
  2846. SmallVector<uint64_t, 8> TmpBits(StorageSize);
  2847. setBitRange(TmpBits, BitOffset, BitWidth, CharWidth);
  2848. if (BigEndian)
  2849. std::reverse(TmpBits.begin(), TmpBits.end());
  2850. for (uint64_t V : TmpBits)
  2851. Bits[StorageOffset++] |= V;
  2852. }
  2853. static void setUsedBits(CodeGenModule &, QualType, int,
  2854. SmallVectorImpl<uint64_t> &);
  2855. // Set the bits in `Bits`, which correspond to the value representations of
  2856. // the actual members of the record type `RTy`. Note that this function does
  2857. // not handle base classes, virtual tables, etc, since they cannot happen in
  2858. // CMSE function arguments or return. The bit mask corresponds to the target
  2859. // memory layout, i.e. it's endian dependent.
  2860. static void setUsedBits(CodeGenModule &CGM, const RecordType *RTy, int Offset,
  2861. SmallVectorImpl<uint64_t> &Bits) {
  2862. ASTContext &Context = CGM.getContext();
  2863. int CharWidth = Context.getCharWidth();
  2864. const RecordDecl *RD = RTy->getDecl()->getDefinition();
  2865. const ASTRecordLayout &ASTLayout = Context.getASTRecordLayout(RD);
  2866. const CGRecordLayout &Layout = CGM.getTypes().getCGRecordLayout(RD);
  2867. int Idx = 0;
  2868. for (auto I = RD->field_begin(), E = RD->field_end(); I != E; ++I, ++Idx) {
  2869. const FieldDecl *F = *I;
  2870. if (F->isUnnamedBitfield() || F->isZeroLengthBitField(Context) ||
  2871. F->getType()->isIncompleteArrayType())
  2872. continue;
  2873. if (F->isBitField()) {
  2874. const CGBitFieldInfo &BFI = Layout.getBitFieldInfo(F);
  2875. setBitRange(Bits, Offset + BFI.StorageOffset.getQuantity(),
  2876. BFI.StorageSize / CharWidth, BFI.Offset,
  2877. BFI.Size, CharWidth,
  2878. CGM.getDataLayout().isBigEndian());
  2879. continue;
  2880. }
  2881. setUsedBits(CGM, F->getType(),
  2882. Offset + ASTLayout.getFieldOffset(Idx) / CharWidth, Bits);
  2883. }
  2884. }
  2885. // Set the bits in `Bits`, which correspond to the value representations of
  2886. // the elements of an array type `ATy`.
  2887. static void setUsedBits(CodeGenModule &CGM, const ConstantArrayType *ATy,
  2888. int Offset, SmallVectorImpl<uint64_t> &Bits) {
  2889. const ASTContext &Context = CGM.getContext();
  2890. QualType ETy = Context.getBaseElementType(ATy);
  2891. int Size = Context.getTypeSizeInChars(ETy).getQuantity();
  2892. SmallVector<uint64_t, 4> TmpBits(Size);
  2893. setUsedBits(CGM, ETy, 0, TmpBits);
  2894. for (int I = 0, N = Context.getConstantArrayElementCount(ATy); I < N; ++I) {
  2895. auto Src = TmpBits.begin();
  2896. auto Dst = Bits.begin() + Offset + I * Size;
  2897. for (int J = 0; J < Size; ++J)
  2898. *Dst++ |= *Src++;
  2899. }
  2900. }
  2901. // Set the bits in `Bits`, which correspond to the value representations of
  2902. // the type `QTy`.
  2903. static void setUsedBits(CodeGenModule &CGM, QualType QTy, int Offset,
  2904. SmallVectorImpl<uint64_t> &Bits) {
  2905. if (const auto *RTy = QTy->getAs<RecordType>())
  2906. return setUsedBits(CGM, RTy, Offset, Bits);
  2907. ASTContext &Context = CGM.getContext();
  2908. if (const auto *ATy = Context.getAsConstantArrayType(QTy))
  2909. return setUsedBits(CGM, ATy, Offset, Bits);
  2910. int Size = Context.getTypeSizeInChars(QTy).getQuantity();
  2911. if (Size <= 0)
  2912. return;
  2913. std::fill_n(Bits.begin() + Offset, Size,
  2914. (uint64_t(1) << Context.getCharWidth()) - 1);
  2915. }
  2916. static uint64_t buildMultiCharMask(const SmallVectorImpl<uint64_t> &Bits,
  2917. int Pos, int Size, int CharWidth,
  2918. bool BigEndian) {
  2919. assert(Size > 0);
  2920. uint64_t Mask = 0;
  2921. if (BigEndian) {
  2922. for (auto P = Bits.begin() + Pos, E = Bits.begin() + Pos + Size; P != E;
  2923. ++P)
  2924. Mask = (Mask << CharWidth) | *P;
  2925. } else {
  2926. auto P = Bits.begin() + Pos + Size, End = Bits.begin() + Pos;
  2927. do
  2928. Mask = (Mask << CharWidth) | *--P;
  2929. while (P != End);
  2930. }
  2931. return Mask;
  2932. }
  2933. // Emit code to clear the bits in a record, which aren't a part of any user
  2934. // declared member, when the record is a function return.
  2935. llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
  2936. llvm::IntegerType *ITy,
  2937. QualType QTy) {
  2938. assert(Src->getType() == ITy);
  2939. assert(ITy->getScalarSizeInBits() <= 64);
  2940. const llvm::DataLayout &DataLayout = CGM.getDataLayout();
  2941. int Size = DataLayout.getTypeStoreSize(ITy);
  2942. SmallVector<uint64_t, 4> Bits(Size);
  2943. setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
  2944. int CharWidth = CGM.getContext().getCharWidth();
  2945. uint64_t Mask =
  2946. buildMultiCharMask(Bits, 0, Size, CharWidth, DataLayout.isBigEndian());
  2947. return Builder.CreateAnd(Src, Mask, "cmse.clear");
  2948. }
  2949. // Emit code to clear the bits in a record, which aren't a part of any user
  2950. // declared member, when the record is a function argument.
  2951. llvm::Value *CodeGenFunction::EmitCMSEClearRecord(llvm::Value *Src,
  2952. llvm::ArrayType *ATy,
  2953. QualType QTy) {
  2954. const llvm::DataLayout &DataLayout = CGM.getDataLayout();
  2955. int Size = DataLayout.getTypeStoreSize(ATy);
  2956. SmallVector<uint64_t, 16> Bits(Size);
  2957. setUsedBits(CGM, QTy->castAs<RecordType>(), 0, Bits);
  2958. // Clear each element of the LLVM array.
  2959. int CharWidth = CGM.getContext().getCharWidth();
  2960. int CharsPerElt =
  2961. ATy->getArrayElementType()->getScalarSizeInBits() / CharWidth;
  2962. int MaskIndex = 0;
  2963. llvm::Value *R = llvm::UndefValue::get(ATy);
  2964. for (int I = 0, N = ATy->getArrayNumElements(); I != N; ++I) {
  2965. uint64_t Mask = buildMultiCharMask(Bits, MaskIndex, CharsPerElt, CharWidth,
  2966. DataLayout.isBigEndian());
  2967. MaskIndex += CharsPerElt;
  2968. llvm::Value *T0 = Builder.CreateExtractValue(Src, I);
  2969. llvm::Value *T1 = Builder.CreateAnd(T0, Mask, "cmse.clear");
  2970. R = Builder.CreateInsertValue(R, T1, I);
  2971. }
  2972. return R;
  2973. }
  2974. void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
  2975. bool EmitRetDbgLoc,
  2976. SourceLocation EndLoc) {
  2977. if (FI.isNoReturn()) {
  2978. // Noreturn functions don't return.
  2979. EmitUnreachable(EndLoc);
  2980. return;
  2981. }
  2982. if (CurCodeDecl && CurCodeDecl->hasAttr<NakedAttr>()) {
  2983. // Naked functions don't have epilogues.
  2984. Builder.CreateUnreachable();
  2985. return;
  2986. }
  2987. // Functions with no result always return void.
  2988. if (!ReturnValue.isValid()) {
  2989. Builder.CreateRetVoid();
  2990. return;
  2991. }
  2992. llvm::DebugLoc RetDbgLoc;
  2993. llvm::Value *RV = nullptr;
  2994. QualType RetTy = FI.getReturnType();
  2995. const ABIArgInfo &RetAI = FI.getReturnInfo();
  2996. switch (RetAI.getKind()) {
  2997. case ABIArgInfo::InAlloca:
  2998. // Aggregrates get evaluated directly into the destination. Sometimes we
  2999. // need to return the sret value in a register, though.
  3000. assert(hasAggregateEvaluationKind(RetTy));
  3001. if (RetAI.getInAllocaSRet()) {
  3002. llvm::Function::arg_iterator EI = CurFn->arg_end();
  3003. --EI;
  3004. llvm::Value *ArgStruct = &*EI;
  3005. llvm::Value *SRet = Builder.CreateStructGEP(
  3006. EI->getType()->getPointerElementType(), ArgStruct,
  3007. RetAI.getInAllocaFieldIndex());
  3008. llvm::Type *Ty =
  3009. cast<llvm::GetElementPtrInst>(SRet)->getResultElementType();
  3010. RV = Builder.CreateAlignedLoad(Ty, SRet, getPointerAlign(), "sret");
  3011. }
  3012. break;
  3013. case ABIArgInfo::Indirect: {
  3014. auto AI = CurFn->arg_begin();
  3015. if (RetAI.isSRetAfterThis())
  3016. ++AI;
  3017. switch (getEvaluationKind(RetTy)) {
  3018. case TEK_Complex: {
  3019. ComplexPairTy RT =
  3020. EmitLoadOfComplex(MakeAddrLValue(ReturnValue, RetTy), EndLoc);
  3021. EmitStoreOfComplex(RT, MakeNaturalAlignAddrLValue(&*AI, RetTy),
  3022. /*isInit*/ true);
  3023. break;
  3024. }
  3025. case TEK_Aggregate:
  3026. // Do nothing; aggregrates get evaluated directly into the destination.
  3027. break;
  3028. case TEK_Scalar: {
  3029. LValueBaseInfo BaseInfo;
  3030. TBAAAccessInfo TBAAInfo;
  3031. CharUnits Alignment =
  3032. CGM.getNaturalTypeAlignment(RetTy, &BaseInfo, &TBAAInfo);
  3033. Address ArgAddr(&*AI, ConvertType(RetTy), Alignment);
  3034. LValue ArgVal =
  3035. LValue::MakeAddr(ArgAddr, RetTy, getContext(), BaseInfo, TBAAInfo);
  3036. EmitStoreOfScalar(
  3037. Builder.CreateLoad(ReturnValue), ArgVal, /*isInit*/ true);
  3038. break;
  3039. }
  3040. }
  3041. break;
  3042. }
  3043. case ABIArgInfo::Extend:
  3044. case ABIArgInfo::Direct:
  3045. if (RetAI.getCoerceToType() == ConvertType(RetTy) &&
  3046. RetAI.getDirectOffset() == 0) {
  3047. // The internal return value temp always will have pointer-to-return-type
  3048. // type, just do a load.
  3049. // If there is a dominating store to ReturnValue, we can elide
  3050. // the load, zap the store, and usually zap the alloca.
  3051. if (llvm::StoreInst *SI =
  3052. findDominatingStoreToReturnValue(*this)) {
  3053. // Reuse the debug location from the store unless there is
  3054. // cleanup code to be emitted between the store and return
  3055. // instruction.
  3056. if (EmitRetDbgLoc && !AutoreleaseResult)
  3057. RetDbgLoc = SI->getDebugLoc();
  3058. // Get the stored value and nuke the now-dead store.
  3059. RV = SI->getValueOperand();
  3060. SI->eraseFromParent();
  3061. // Otherwise, we have to do a simple load.
  3062. } else {
  3063. RV = Builder.CreateLoad(ReturnValue);
  3064. }
  3065. } else {
  3066. // If the value is offset in memory, apply the offset now.
  3067. Address V = emitAddressAtOffset(*this, ReturnValue, RetAI);
  3068. RV = CreateCoercedLoad(V, RetAI.getCoerceToType(), *this);
  3069. }
  3070. // In ARC, end functions that return a retainable type with a call
  3071. // to objc_autoreleaseReturnValue.
  3072. if (AutoreleaseResult) {
  3073. #ifndef NDEBUG
  3074. // Type::isObjCRetainabletype has to be called on a QualType that hasn't
  3075. // been stripped of the typedefs, so we cannot use RetTy here. Get the
  3076. // original return type of FunctionDecl, CurCodeDecl, and BlockDecl from
  3077. // CurCodeDecl or BlockInfo.
  3078. QualType RT;
  3079. if (auto *FD = dyn_cast<FunctionDecl>(CurCodeDecl))
  3080. RT = FD->getReturnType();
  3081. else if (auto *MD = dyn_cast<ObjCMethodDecl>(CurCodeDecl))
  3082. RT = MD->getReturnType();
  3083. else if (isa<BlockDecl>(CurCodeDecl))
  3084. RT = BlockInfo->BlockExpression->getFunctionType()->getReturnType();
  3085. else
  3086. llvm_unreachable("Unexpected function/method type");
  3087. assert(getLangOpts().ObjCAutoRefCount &&
  3088. !FI.isReturnsRetained() &&
  3089. RT->isObjCRetainableType());
  3090. #endif
  3091. RV = emitAutoreleaseOfResult(*this, RV);
  3092. }
  3093. break;
  3094. case ABIArgInfo::Ignore:
  3095. break;
  3096. case ABIArgInfo::CoerceAndExpand: {
  3097. auto coercionType = RetAI.getCoerceAndExpandType();
  3098. // Load all of the coerced elements out into results.
  3099. llvm::SmallVector<llvm::Value*, 4> results;
  3100. Address addr = Builder.CreateElementBitCast(ReturnValue, coercionType);
  3101. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  3102. auto coercedEltType = coercionType->getElementType(i);
  3103. if (ABIArgInfo::isPaddingForCoerceAndExpand(coercedEltType))
  3104. continue;
  3105. auto eltAddr = Builder.CreateStructGEP(addr, i);
  3106. auto elt = Builder.CreateLoad(eltAddr);
  3107. results.push_back(elt);
  3108. }
  3109. // If we have one result, it's the single direct result type.
  3110. if (results.size() == 1) {
  3111. RV = results[0];
  3112. // Otherwise, we need to make a first-class aggregate.
  3113. } else {
  3114. // Construct a return type that lacks padding elements.
  3115. llvm::Type *returnType = RetAI.getUnpaddedCoerceAndExpandType();
  3116. RV = llvm::UndefValue::get(returnType);
  3117. for (unsigned i = 0, e = results.size(); i != e; ++i) {
  3118. RV = Builder.CreateInsertValue(RV, results[i], i);
  3119. }
  3120. }
  3121. break;
  3122. }
  3123. case ABIArgInfo::Expand:
  3124. case ABIArgInfo::IndirectAliased:
  3125. llvm_unreachable("Invalid ABI kind for return argument");
  3126. }
  3127. llvm::Instruction *Ret;
  3128. if (RV) {
  3129. if (CurFuncDecl && CurFuncDecl->hasAttr<CmseNSEntryAttr>()) {
  3130. // For certain return types, clear padding bits, as they may reveal
  3131. // sensitive information.
  3132. // Small struct/union types are passed as integers.
  3133. auto *ITy = dyn_cast<llvm::IntegerType>(RV->getType());
  3134. if (ITy != nullptr && isa<RecordType>(RetTy.getCanonicalType()))
  3135. RV = EmitCMSEClearRecord(RV, ITy, RetTy);
  3136. }
  3137. EmitReturnValueCheck(RV);
  3138. Ret = Builder.CreateRet(RV);
  3139. } else {
  3140. Ret = Builder.CreateRetVoid();
  3141. }
  3142. if (RetDbgLoc)
  3143. Ret->setDebugLoc(std::move(RetDbgLoc));
  3144. }
  3145. void CodeGenFunction::EmitReturnValueCheck(llvm::Value *RV) {
  3146. // A current decl may not be available when emitting vtable thunks.
  3147. if (!CurCodeDecl)
  3148. return;
  3149. // If the return block isn't reachable, neither is this check, so don't emit
  3150. // it.
  3151. if (ReturnBlock.isValid() && ReturnBlock.getBlock()->use_empty())
  3152. return;
  3153. ReturnsNonNullAttr *RetNNAttr = nullptr;
  3154. if (SanOpts.has(SanitizerKind::ReturnsNonnullAttribute))
  3155. RetNNAttr = CurCodeDecl->getAttr<ReturnsNonNullAttr>();
  3156. if (!RetNNAttr && !requiresReturnValueNullabilityCheck())
  3157. return;
  3158. // Prefer the returns_nonnull attribute if it's present.
  3159. SourceLocation AttrLoc;
  3160. SanitizerMask CheckKind;
  3161. SanitizerHandler Handler;
  3162. if (RetNNAttr) {
  3163. assert(!requiresReturnValueNullabilityCheck() &&
  3164. "Cannot check nullability and the nonnull attribute");
  3165. AttrLoc = RetNNAttr->getLocation();
  3166. CheckKind = SanitizerKind::ReturnsNonnullAttribute;
  3167. Handler = SanitizerHandler::NonnullReturn;
  3168. } else {
  3169. if (auto *DD = dyn_cast<DeclaratorDecl>(CurCodeDecl))
  3170. if (auto *TSI = DD->getTypeSourceInfo())
  3171. if (auto FTL = TSI->getTypeLoc().getAsAdjusted<FunctionTypeLoc>())
  3172. AttrLoc = FTL.getReturnLoc().findNullabilityLoc();
  3173. CheckKind = SanitizerKind::NullabilityReturn;
  3174. Handler = SanitizerHandler::NullabilityReturn;
  3175. }
  3176. SanitizerScope SanScope(this);
  3177. // Make sure the "return" source location is valid. If we're checking a
  3178. // nullability annotation, make sure the preconditions for the check are met.
  3179. llvm::BasicBlock *Check = createBasicBlock("nullcheck");
  3180. llvm::BasicBlock *NoCheck = createBasicBlock("no.nullcheck");
  3181. llvm::Value *SLocPtr = Builder.CreateLoad(ReturnLocation, "return.sloc.load");
  3182. llvm::Value *CanNullCheck = Builder.CreateIsNotNull(SLocPtr);
  3183. if (requiresReturnValueNullabilityCheck())
  3184. CanNullCheck =
  3185. Builder.CreateAnd(CanNullCheck, RetValNullabilityPrecondition);
  3186. Builder.CreateCondBr(CanNullCheck, Check, NoCheck);
  3187. EmitBlock(Check);
  3188. // Now do the null check.
  3189. llvm::Value *Cond = Builder.CreateIsNotNull(RV);
  3190. llvm::Constant *StaticData[] = {EmitCheckSourceLocation(AttrLoc)};
  3191. llvm::Value *DynamicData[] = {SLocPtr};
  3192. EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, DynamicData);
  3193. EmitBlock(NoCheck);
  3194. #ifndef NDEBUG
  3195. // The return location should not be used after the check has been emitted.
  3196. ReturnLocation = Address::invalid();
  3197. #endif
  3198. }
  3199. static bool isInAllocaArgument(CGCXXABI &ABI, QualType type) {
  3200. const CXXRecordDecl *RD = type->getAsCXXRecordDecl();
  3201. return RD && ABI.getRecordArgABI(RD) == CGCXXABI::RAA_DirectInMemory;
  3202. }
  3203. static AggValueSlot createPlaceholderSlot(CodeGenFunction &CGF,
  3204. QualType Ty) {
  3205. // FIXME: Generate IR in one pass, rather than going back and fixing up these
  3206. // placeholders.
  3207. llvm::Type *IRTy = CGF.ConvertTypeForMem(Ty);
  3208. llvm::Type *IRPtrTy = IRTy->getPointerTo();
  3209. llvm::Value *Placeholder = llvm::UndefValue::get(IRPtrTy->getPointerTo());
  3210. // FIXME: When we generate this IR in one pass, we shouldn't need
  3211. // this win32-specific alignment hack.
  3212. CharUnits Align = CharUnits::fromQuantity(4);
  3213. Placeholder = CGF.Builder.CreateAlignedLoad(IRPtrTy, Placeholder, Align);
  3214. return AggValueSlot::forAddr(Address(Placeholder, Align),
  3215. Ty.getQualifiers(),
  3216. AggValueSlot::IsNotDestructed,
  3217. AggValueSlot::DoesNotNeedGCBarriers,
  3218. AggValueSlot::IsNotAliased,
  3219. AggValueSlot::DoesNotOverlap);
  3220. }
  3221. void CodeGenFunction::EmitDelegateCallArg(CallArgList &args,
  3222. const VarDecl *param,
  3223. SourceLocation loc) {
  3224. // StartFunction converted the ABI-lowered parameter(s) into a
  3225. // local alloca. We need to turn that into an r-value suitable
  3226. // for EmitCall.
  3227. Address local = GetAddrOfLocalVar(param);
  3228. QualType type = param->getType();
  3229. if (isInAllocaArgument(CGM.getCXXABI(), type)) {
  3230. CGM.ErrorUnsupported(param, "forwarded non-trivially copyable parameter");
  3231. }
  3232. // GetAddrOfLocalVar returns a pointer-to-pointer for references,
  3233. // but the argument needs to be the original pointer.
  3234. if (type->isReferenceType()) {
  3235. args.add(RValue::get(Builder.CreateLoad(local)), type);
  3236. // In ARC, move out of consumed arguments so that the release cleanup
  3237. // entered by StartFunction doesn't cause an over-release. This isn't
  3238. // optimal -O0 code generation, but it should get cleaned up when
  3239. // optimization is enabled. This also assumes that delegate calls are
  3240. // performed exactly once for a set of arguments, but that should be safe.
  3241. } else if (getLangOpts().ObjCAutoRefCount &&
  3242. param->hasAttr<NSConsumedAttr>() &&
  3243. type->isObjCRetainableType()) {
  3244. llvm::Value *ptr = Builder.CreateLoad(local);
  3245. auto null =
  3246. llvm::ConstantPointerNull::get(cast<llvm::PointerType>(ptr->getType()));
  3247. Builder.CreateStore(null, local);
  3248. args.add(RValue::get(ptr), type);
  3249. // For the most part, we just need to load the alloca, except that
  3250. // aggregate r-values are actually pointers to temporaries.
  3251. } else {
  3252. args.add(convertTempToRValue(local, type, loc), type);
  3253. }
  3254. // Deactivate the cleanup for the callee-destructed param that was pushed.
  3255. if (type->isRecordType() && !CurFuncIsThunk &&
  3256. type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee() &&
  3257. param->needsDestruction(getContext())) {
  3258. EHScopeStack::stable_iterator cleanup =
  3259. CalleeDestructedParamCleanups.lookup(cast<ParmVarDecl>(param));
  3260. assert(cleanup.isValid() &&
  3261. "cleanup for callee-destructed param not recorded");
  3262. // This unreachable is a temporary marker which will be removed later.
  3263. llvm::Instruction *isActive = Builder.CreateUnreachable();
  3264. args.addArgCleanupDeactivation(cleanup, isActive);
  3265. }
  3266. }
  3267. static bool isProvablyNull(llvm::Value *addr) {
  3268. return isa<llvm::ConstantPointerNull>(addr);
  3269. }
  3270. /// Emit the actual writing-back of a writeback.
  3271. static void emitWriteback(CodeGenFunction &CGF,
  3272. const CallArgList::Writeback &writeback) {
  3273. const LValue &srcLV = writeback.Source;
  3274. Address srcAddr = srcLV.getAddress(CGF);
  3275. assert(!isProvablyNull(srcAddr.getPointer()) &&
  3276. "shouldn't have writeback for provably null argument");
  3277. llvm::BasicBlock *contBB = nullptr;
  3278. // If the argument wasn't provably non-null, we need to null check
  3279. // before doing the store.
  3280. bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
  3281. CGF.CGM.getDataLayout());
  3282. if (!provablyNonNull) {
  3283. llvm::BasicBlock *writebackBB = CGF.createBasicBlock("icr.writeback");
  3284. contBB = CGF.createBasicBlock("icr.done");
  3285. llvm::Value *isNull =
  3286. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  3287. CGF.Builder.CreateCondBr(isNull, contBB, writebackBB);
  3288. CGF.EmitBlock(writebackBB);
  3289. }
  3290. // Load the value to writeback.
  3291. llvm::Value *value = CGF.Builder.CreateLoad(writeback.Temporary);
  3292. // Cast it back, in case we're writing an id to a Foo* or something.
  3293. value = CGF.Builder.CreateBitCast(value, srcAddr.getElementType(),
  3294. "icr.writeback-cast");
  3295. // Perform the writeback.
  3296. // If we have a "to use" value, it's something we need to emit a use
  3297. // of. This has to be carefully threaded in: if it's done after the
  3298. // release it's potentially undefined behavior (and the optimizer
  3299. // will ignore it), and if it happens before the retain then the
  3300. // optimizer could move the release there.
  3301. if (writeback.ToUse) {
  3302. assert(srcLV.getObjCLifetime() == Qualifiers::OCL_Strong);
  3303. // Retain the new value. No need to block-copy here: the block's
  3304. // being passed up the stack.
  3305. value = CGF.EmitARCRetainNonBlock(value);
  3306. // Emit the intrinsic use here.
  3307. CGF.EmitARCIntrinsicUse(writeback.ToUse);
  3308. // Load the old value (primitively).
  3309. llvm::Value *oldValue = CGF.EmitLoadOfScalar(srcLV, SourceLocation());
  3310. // Put the new value in place (primitively).
  3311. CGF.EmitStoreOfScalar(value, srcLV, /*init*/ false);
  3312. // Release the old value.
  3313. CGF.EmitARCRelease(oldValue, srcLV.isARCPreciseLifetime());
  3314. // Otherwise, we can just do a normal lvalue store.
  3315. } else {
  3316. CGF.EmitStoreThroughLValue(RValue::get(value), srcLV);
  3317. }
  3318. // Jump to the continuation block.
  3319. if (!provablyNonNull)
  3320. CGF.EmitBlock(contBB);
  3321. }
  3322. static void emitWritebacks(CodeGenFunction &CGF,
  3323. const CallArgList &args) {
  3324. for (const auto &I : args.writebacks())
  3325. emitWriteback(CGF, I);
  3326. }
  3327. static void deactivateArgCleanupsBeforeCall(CodeGenFunction &CGF,
  3328. const CallArgList &CallArgs) {
  3329. ArrayRef<CallArgList::CallArgCleanup> Cleanups =
  3330. CallArgs.getCleanupsToDeactivate();
  3331. // Iterate in reverse to increase the likelihood of popping the cleanup.
  3332. for (const auto &I : llvm::reverse(Cleanups)) {
  3333. CGF.DeactivateCleanupBlock(I.Cleanup, I.IsActiveIP);
  3334. I.IsActiveIP->eraseFromParent();
  3335. }
  3336. }
  3337. static const Expr *maybeGetUnaryAddrOfOperand(const Expr *E) {
  3338. if (const UnaryOperator *uop = dyn_cast<UnaryOperator>(E->IgnoreParens()))
  3339. if (uop->getOpcode() == UO_AddrOf)
  3340. return uop->getSubExpr();
  3341. return nullptr;
  3342. }
  3343. /// Emit an argument that's being passed call-by-writeback. That is,
  3344. /// we are passing the address of an __autoreleased temporary; it
  3345. /// might be copy-initialized with the current value of the given
  3346. /// address, but it will definitely be copied out of after the call.
  3347. static void emitWritebackArg(CodeGenFunction &CGF, CallArgList &args,
  3348. const ObjCIndirectCopyRestoreExpr *CRE) {
  3349. LValue srcLV;
  3350. // Make an optimistic effort to emit the address as an l-value.
  3351. // This can fail if the argument expression is more complicated.
  3352. if (const Expr *lvExpr = maybeGetUnaryAddrOfOperand(CRE->getSubExpr())) {
  3353. srcLV = CGF.EmitLValue(lvExpr);
  3354. // Otherwise, just emit it as a scalar.
  3355. } else {
  3356. Address srcAddr = CGF.EmitPointerWithAlignment(CRE->getSubExpr());
  3357. QualType srcAddrType =
  3358. CRE->getSubExpr()->getType()->castAs<PointerType>()->getPointeeType();
  3359. srcLV = CGF.MakeAddrLValue(srcAddr, srcAddrType);
  3360. }
  3361. Address srcAddr = srcLV.getAddress(CGF);
  3362. // The dest and src types don't necessarily match in LLVM terms
  3363. // because of the crazy ObjC compatibility rules.
  3364. llvm::PointerType *destType =
  3365. cast<llvm::PointerType>(CGF.ConvertType(CRE->getType()));
  3366. // If the address is a constant null, just pass the appropriate null.
  3367. if (isProvablyNull(srcAddr.getPointer())) {
  3368. args.add(RValue::get(llvm::ConstantPointerNull::get(destType)),
  3369. CRE->getType());
  3370. return;
  3371. }
  3372. // Create the temporary.
  3373. Address temp = CGF.CreateTempAlloca(destType->getPointerElementType(),
  3374. CGF.getPointerAlign(), "icr.temp");
  3375. // Loading an l-value can introduce a cleanup if the l-value is __weak,
  3376. // and that cleanup will be conditional if we can't prove that the l-value
  3377. // isn't null, so we need to register a dominating point so that the cleanups
  3378. // system will make valid IR.
  3379. CodeGenFunction::ConditionalEvaluation condEval(CGF);
  3380. // Zero-initialize it if we're not doing a copy-initialization.
  3381. bool shouldCopy = CRE->shouldCopy();
  3382. if (!shouldCopy) {
  3383. llvm::Value *null = llvm::ConstantPointerNull::get(
  3384. cast<llvm::PointerType>(destType->getPointerElementType()));
  3385. CGF.Builder.CreateStore(null, temp);
  3386. }
  3387. llvm::BasicBlock *contBB = nullptr;
  3388. llvm::BasicBlock *originBB = nullptr;
  3389. // If the address is *not* known to be non-null, we need to switch.
  3390. llvm::Value *finalArgument;
  3391. bool provablyNonNull = llvm::isKnownNonZero(srcAddr.getPointer(),
  3392. CGF.CGM.getDataLayout());
  3393. if (provablyNonNull) {
  3394. finalArgument = temp.getPointer();
  3395. } else {
  3396. llvm::Value *isNull =
  3397. CGF.Builder.CreateIsNull(srcAddr.getPointer(), "icr.isnull");
  3398. finalArgument = CGF.Builder.CreateSelect(isNull,
  3399. llvm::ConstantPointerNull::get(destType),
  3400. temp.getPointer(), "icr.argument");
  3401. // If we need to copy, then the load has to be conditional, which
  3402. // means we need control flow.
  3403. if (shouldCopy) {
  3404. originBB = CGF.Builder.GetInsertBlock();
  3405. contBB = CGF.createBasicBlock("icr.cont");
  3406. llvm::BasicBlock *copyBB = CGF.createBasicBlock("icr.copy");
  3407. CGF.Builder.CreateCondBr(isNull, contBB, copyBB);
  3408. CGF.EmitBlock(copyBB);
  3409. condEval.begin(CGF);
  3410. }
  3411. }
  3412. llvm::Value *valueToUse = nullptr;
  3413. // Perform a copy if necessary.
  3414. if (shouldCopy) {
  3415. RValue srcRV = CGF.EmitLoadOfLValue(srcLV, SourceLocation());
  3416. assert(srcRV.isScalar());
  3417. llvm::Value *src = srcRV.getScalarVal();
  3418. src = CGF.Builder.CreateBitCast(src, destType->getPointerElementType(),
  3419. "icr.cast");
  3420. // Use an ordinary store, not a store-to-lvalue.
  3421. CGF.Builder.CreateStore(src, temp);
  3422. // If optimization is enabled, and the value was held in a
  3423. // __strong variable, we need to tell the optimizer that this
  3424. // value has to stay alive until we're doing the store back.
  3425. // This is because the temporary is effectively unretained,
  3426. // and so otherwise we can violate the high-level semantics.
  3427. if (CGF.CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  3428. srcLV.getObjCLifetime() == Qualifiers::OCL_Strong) {
  3429. valueToUse = src;
  3430. }
  3431. }
  3432. // Finish the control flow if we needed it.
  3433. if (shouldCopy && !provablyNonNull) {
  3434. llvm::BasicBlock *copyBB = CGF.Builder.GetInsertBlock();
  3435. CGF.EmitBlock(contBB);
  3436. // Make a phi for the value to intrinsically use.
  3437. if (valueToUse) {
  3438. llvm::PHINode *phiToUse = CGF.Builder.CreatePHI(valueToUse->getType(), 2,
  3439. "icr.to-use");
  3440. phiToUse->addIncoming(valueToUse, copyBB);
  3441. phiToUse->addIncoming(llvm::UndefValue::get(valueToUse->getType()),
  3442. originBB);
  3443. valueToUse = phiToUse;
  3444. }
  3445. condEval.end(CGF);
  3446. }
  3447. args.addWriteback(srcLV, temp, valueToUse);
  3448. args.add(RValue::get(finalArgument), CRE->getType());
  3449. }
  3450. void CallArgList::allocateArgumentMemory(CodeGenFunction &CGF) {
  3451. assert(!StackBase);
  3452. // Save the stack.
  3453. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stacksave);
  3454. StackBase = CGF.Builder.CreateCall(F, {}, "inalloca.save");
  3455. }
  3456. void CallArgList::freeArgumentMemory(CodeGenFunction &CGF) const {
  3457. if (StackBase) {
  3458. // Restore the stack after the call.
  3459. llvm::Function *F = CGF.CGM.getIntrinsic(llvm::Intrinsic::stackrestore);
  3460. CGF.Builder.CreateCall(F, StackBase);
  3461. }
  3462. }
  3463. void CodeGenFunction::EmitNonNullArgCheck(RValue RV, QualType ArgType,
  3464. SourceLocation ArgLoc,
  3465. AbstractCallee AC,
  3466. unsigned ParmNum) {
  3467. if (!AC.getDecl() || !(SanOpts.has(SanitizerKind::NonnullAttribute) ||
  3468. SanOpts.has(SanitizerKind::NullabilityArg)))
  3469. return;
  3470. // The param decl may be missing in a variadic function.
  3471. auto PVD = ParmNum < AC.getNumParams() ? AC.getParamDecl(ParmNum) : nullptr;
  3472. unsigned ArgNo = PVD ? PVD->getFunctionScopeIndex() : ParmNum;
  3473. // Prefer the nonnull attribute if it's present.
  3474. const NonNullAttr *NNAttr = nullptr;
  3475. if (SanOpts.has(SanitizerKind::NonnullAttribute))
  3476. NNAttr = getNonNullAttr(AC.getDecl(), PVD, ArgType, ArgNo);
  3477. bool CanCheckNullability = false;
  3478. if (SanOpts.has(SanitizerKind::NullabilityArg) && !NNAttr && PVD) {
  3479. auto Nullability = PVD->getType()->getNullability(getContext());
  3480. CanCheckNullability = Nullability &&
  3481. *Nullability == NullabilityKind::NonNull &&
  3482. PVD->getTypeSourceInfo();
  3483. }
  3484. if (!NNAttr && !CanCheckNullability)
  3485. return;
  3486. SourceLocation AttrLoc;
  3487. SanitizerMask CheckKind;
  3488. SanitizerHandler Handler;
  3489. if (NNAttr) {
  3490. AttrLoc = NNAttr->getLocation();
  3491. CheckKind = SanitizerKind::NonnullAttribute;
  3492. Handler = SanitizerHandler::NonnullArg;
  3493. } else {
  3494. AttrLoc = PVD->getTypeSourceInfo()->getTypeLoc().findNullabilityLoc();
  3495. CheckKind = SanitizerKind::NullabilityArg;
  3496. Handler = SanitizerHandler::NullabilityArg;
  3497. }
  3498. SanitizerScope SanScope(this);
  3499. llvm::Value *Cond = EmitNonNullRValueCheck(RV, ArgType);
  3500. llvm::Constant *StaticData[] = {
  3501. EmitCheckSourceLocation(ArgLoc), EmitCheckSourceLocation(AttrLoc),
  3502. llvm::ConstantInt::get(Int32Ty, ArgNo + 1),
  3503. };
  3504. EmitCheck(std::make_pair(Cond, CheckKind), Handler, StaticData, None);
  3505. }
  3506. // Check if the call is going to use the inalloca convention. This needs to
  3507. // agree with CGFunctionInfo::usesInAlloca. The CGFunctionInfo is arranged
  3508. // later, so we can't check it directly.
  3509. static bool hasInAllocaArgs(CodeGenModule &CGM, CallingConv ExplicitCC,
  3510. ArrayRef<QualType> ArgTypes) {
  3511. // The Swift calling conventions don't go through the target-specific
  3512. // argument classification, they never use inalloca.
  3513. // TODO: Consider limiting inalloca use to only calling conventions supported
  3514. // by MSVC.
  3515. if (ExplicitCC == CC_Swift || ExplicitCC == CC_SwiftAsync)
  3516. return false;
  3517. if (!CGM.getTarget().getCXXABI().isMicrosoft())
  3518. return false;
  3519. return llvm::any_of(ArgTypes, [&](QualType Ty) {
  3520. return isInAllocaArgument(CGM.getCXXABI(), Ty);
  3521. });
  3522. }
  3523. #ifndef NDEBUG
  3524. // Determine whether the given argument is an Objective-C method
  3525. // that may have type parameters in its signature.
  3526. static bool isObjCMethodWithTypeParams(const ObjCMethodDecl *method) {
  3527. const DeclContext *dc = method->getDeclContext();
  3528. if (const ObjCInterfaceDecl *classDecl = dyn_cast<ObjCInterfaceDecl>(dc)) {
  3529. return classDecl->getTypeParamListAsWritten();
  3530. }
  3531. if (const ObjCCategoryDecl *catDecl = dyn_cast<ObjCCategoryDecl>(dc)) {
  3532. return catDecl->getTypeParamList();
  3533. }
  3534. return false;
  3535. }
  3536. #endif
  3537. /// EmitCallArgs - Emit call arguments for a function.
  3538. void CodeGenFunction::EmitCallArgs(
  3539. CallArgList &Args, PrototypeWrapper Prototype,
  3540. llvm::iterator_range<CallExpr::const_arg_iterator> ArgRange,
  3541. AbstractCallee AC, unsigned ParamsToSkip, EvaluationOrder Order) {
  3542. SmallVector<QualType, 16> ArgTypes;
  3543. assert((ParamsToSkip == 0 || Prototype.P) &&
  3544. "Can't skip parameters if type info is not provided");
  3545. // This variable only captures *explicitly* written conventions, not those
  3546. // applied by default via command line flags or target defaults, such as
  3547. // thiscall, aapcs, stdcall via -mrtd, etc. Computing that correctly would
  3548. // require knowing if this is a C++ instance method or being able to see
  3549. // unprototyped FunctionTypes.
  3550. CallingConv ExplicitCC = CC_C;
  3551. // First, if a prototype was provided, use those argument types.
  3552. bool IsVariadic = false;
  3553. if (Prototype.P) {
  3554. const auto *MD = Prototype.P.dyn_cast<const ObjCMethodDecl *>();
  3555. if (MD) {
  3556. IsVariadic = MD->isVariadic();
  3557. ExplicitCC = getCallingConventionForDecl(
  3558. MD, CGM.getTarget().getTriple().isOSWindows());
  3559. ArgTypes.assign(MD->param_type_begin() + ParamsToSkip,
  3560. MD->param_type_end());
  3561. } else {
  3562. const auto *FPT = Prototype.P.get<const FunctionProtoType *>();
  3563. IsVariadic = FPT->isVariadic();
  3564. ExplicitCC = FPT->getExtInfo().getCC();
  3565. ArgTypes.assign(FPT->param_type_begin() + ParamsToSkip,
  3566. FPT->param_type_end());
  3567. }
  3568. #ifndef NDEBUG
  3569. // Check that the prototyped types match the argument expression types.
  3570. bool isGenericMethod = MD && isObjCMethodWithTypeParams(MD);
  3571. CallExpr::const_arg_iterator Arg = ArgRange.begin();
  3572. for (QualType Ty : ArgTypes) {
  3573. assert(Arg != ArgRange.end() && "Running over edge of argument list!");
  3574. assert(
  3575. (isGenericMethod || Ty->isVariablyModifiedType() ||
  3576. Ty.getNonReferenceType()->isObjCRetainableType() ||
  3577. getContext()
  3578. .getCanonicalType(Ty.getNonReferenceType())
  3579. .getTypePtr() ==
  3580. getContext().getCanonicalType((*Arg)->getType()).getTypePtr()) &&
  3581. "type mismatch in call argument!");
  3582. ++Arg;
  3583. }
  3584. // Either we've emitted all the call args, or we have a call to variadic
  3585. // function.
  3586. assert((Arg == ArgRange.end() || IsVariadic) &&
  3587. "Extra arguments in non-variadic function!");
  3588. #endif
  3589. }
  3590. // If we still have any arguments, emit them using the type of the argument.
  3591. for (auto *A : llvm::drop_begin(ArgRange, ArgTypes.size()))
  3592. ArgTypes.push_back(IsVariadic ? getVarArgType(A) : A->getType());
  3593. assert((int)ArgTypes.size() == (ArgRange.end() - ArgRange.begin()));
  3594. // We must evaluate arguments from right to left in the MS C++ ABI,
  3595. // because arguments are destroyed left to right in the callee. As a special
  3596. // case, there are certain language constructs that require left-to-right
  3597. // evaluation, and in those cases we consider the evaluation order requirement
  3598. // to trump the "destruction order is reverse construction order" guarantee.
  3599. bool LeftToRight =
  3600. CGM.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()
  3601. ? Order == EvaluationOrder::ForceLeftToRight
  3602. : Order != EvaluationOrder::ForceRightToLeft;
  3603. auto MaybeEmitImplicitObjectSize = [&](unsigned I, const Expr *Arg,
  3604. RValue EmittedArg) {
  3605. if (!AC.hasFunctionDecl() || I >= AC.getNumParams())
  3606. return;
  3607. auto *PS = AC.getParamDecl(I)->getAttr<PassObjectSizeAttr>();
  3608. if (PS == nullptr)
  3609. return;
  3610. const auto &Context = getContext();
  3611. auto SizeTy = Context.getSizeType();
  3612. auto T = Builder.getIntNTy(Context.getTypeSize(SizeTy));
  3613. assert(EmittedArg.getScalarVal() && "We emitted nothing for the arg?");
  3614. llvm::Value *V = evaluateOrEmitBuiltinObjectSize(Arg, PS->getType(), T,
  3615. EmittedArg.getScalarVal(),
  3616. PS->isDynamic());
  3617. Args.add(RValue::get(V), SizeTy);
  3618. // If we're emitting args in reverse, be sure to do so with
  3619. // pass_object_size, as well.
  3620. if (!LeftToRight)
  3621. std::swap(Args.back(), *(&Args.back() - 1));
  3622. };
  3623. // Insert a stack save if we're going to need any inalloca args.
  3624. if (hasInAllocaArgs(CGM, ExplicitCC, ArgTypes)) {
  3625. assert(getTarget().getTriple().getArch() == llvm::Triple::x86 &&
  3626. "inalloca only supported on x86");
  3627. Args.allocateArgumentMemory(*this);
  3628. }
  3629. // Evaluate each argument in the appropriate order.
  3630. size_t CallArgsStart = Args.size();
  3631. for (unsigned I = 0, E = ArgTypes.size(); I != E; ++I) {
  3632. unsigned Idx = LeftToRight ? I : E - I - 1;
  3633. CallExpr::const_arg_iterator Arg = ArgRange.begin() + Idx;
  3634. unsigned InitialArgSize = Args.size();
  3635. // If *Arg is an ObjCIndirectCopyRestoreExpr, check that either the types of
  3636. // the argument and parameter match or the objc method is parameterized.
  3637. assert((!isa<ObjCIndirectCopyRestoreExpr>(*Arg) ||
  3638. getContext().hasSameUnqualifiedType((*Arg)->getType(),
  3639. ArgTypes[Idx]) ||
  3640. (isa<ObjCMethodDecl>(AC.getDecl()) &&
  3641. isObjCMethodWithTypeParams(cast<ObjCMethodDecl>(AC.getDecl())))) &&
  3642. "Argument and parameter types don't match");
  3643. EmitCallArg(Args, *Arg, ArgTypes[Idx]);
  3644. // In particular, we depend on it being the last arg in Args, and the
  3645. // objectsize bits depend on there only being one arg if !LeftToRight.
  3646. assert(InitialArgSize + 1 == Args.size() &&
  3647. "The code below depends on only adding one arg per EmitCallArg");
  3648. (void)InitialArgSize;
  3649. // Since pointer argument are never emitted as LValue, it is safe to emit
  3650. // non-null argument check for r-value only.
  3651. if (!Args.back().hasLValue()) {
  3652. RValue RVArg = Args.back().getKnownRValue();
  3653. EmitNonNullArgCheck(RVArg, ArgTypes[Idx], (*Arg)->getExprLoc(), AC,
  3654. ParamsToSkip + Idx);
  3655. // @llvm.objectsize should never have side-effects and shouldn't need
  3656. // destruction/cleanups, so we can safely "emit" it after its arg,
  3657. // regardless of right-to-leftness
  3658. MaybeEmitImplicitObjectSize(Idx, *Arg, RVArg);
  3659. }
  3660. }
  3661. if (!LeftToRight) {
  3662. // Un-reverse the arguments we just evaluated so they match up with the LLVM
  3663. // IR function.
  3664. std::reverse(Args.begin() + CallArgsStart, Args.end());
  3665. }
  3666. }
  3667. namespace {
  3668. struct DestroyUnpassedArg final : EHScopeStack::Cleanup {
  3669. DestroyUnpassedArg(Address Addr, QualType Ty)
  3670. : Addr(Addr), Ty(Ty) {}
  3671. Address Addr;
  3672. QualType Ty;
  3673. void Emit(CodeGenFunction &CGF, Flags flags) override {
  3674. QualType::DestructionKind DtorKind = Ty.isDestructedType();
  3675. if (DtorKind == QualType::DK_cxx_destructor) {
  3676. const CXXDestructorDecl *Dtor = Ty->getAsCXXRecordDecl()->getDestructor();
  3677. assert(!Dtor->isTrivial());
  3678. CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*for vbase*/ false,
  3679. /*Delegating=*/false, Addr, Ty);
  3680. } else {
  3681. CGF.callCStructDestructor(CGF.MakeAddrLValue(Addr, Ty));
  3682. }
  3683. }
  3684. };
  3685. struct DisableDebugLocationUpdates {
  3686. CodeGenFunction &CGF;
  3687. bool disabledDebugInfo;
  3688. DisableDebugLocationUpdates(CodeGenFunction &CGF, const Expr *E) : CGF(CGF) {
  3689. if ((disabledDebugInfo = isa<CXXDefaultArgExpr>(E) && CGF.getDebugInfo()))
  3690. CGF.disableDebugInfo();
  3691. }
  3692. ~DisableDebugLocationUpdates() {
  3693. if (disabledDebugInfo)
  3694. CGF.enableDebugInfo();
  3695. }
  3696. };
  3697. } // end anonymous namespace
  3698. RValue CallArg::getRValue(CodeGenFunction &CGF) const {
  3699. if (!HasLV)
  3700. return RV;
  3701. LValue Copy = CGF.MakeAddrLValue(CGF.CreateMemTemp(Ty), Ty);
  3702. CGF.EmitAggregateCopy(Copy, LV, Ty, AggValueSlot::DoesNotOverlap,
  3703. LV.isVolatile());
  3704. IsUsed = true;
  3705. return RValue::getAggregate(Copy.getAddress(CGF));
  3706. }
  3707. void CallArg::copyInto(CodeGenFunction &CGF, Address Addr) const {
  3708. LValue Dst = CGF.MakeAddrLValue(Addr, Ty);
  3709. if (!HasLV && RV.isScalar())
  3710. CGF.EmitStoreOfScalar(RV.getScalarVal(), Dst, /*isInit=*/true);
  3711. else if (!HasLV && RV.isComplex())
  3712. CGF.EmitStoreOfComplex(RV.getComplexVal(), Dst, /*init=*/true);
  3713. else {
  3714. auto Addr = HasLV ? LV.getAddress(CGF) : RV.getAggregateAddress();
  3715. LValue SrcLV = CGF.MakeAddrLValue(Addr, Ty);
  3716. // We assume that call args are never copied into subobjects.
  3717. CGF.EmitAggregateCopy(Dst, SrcLV, Ty, AggValueSlot::DoesNotOverlap,
  3718. HasLV ? LV.isVolatileQualified()
  3719. : RV.isVolatileQualified());
  3720. }
  3721. IsUsed = true;
  3722. }
  3723. void CodeGenFunction::EmitCallArg(CallArgList &args, const Expr *E,
  3724. QualType type) {
  3725. DisableDebugLocationUpdates Dis(*this, E);
  3726. if (const ObjCIndirectCopyRestoreExpr *CRE
  3727. = dyn_cast<ObjCIndirectCopyRestoreExpr>(E)) {
  3728. assert(getLangOpts().ObjCAutoRefCount);
  3729. return emitWritebackArg(*this, args, CRE);
  3730. }
  3731. assert(type->isReferenceType() == E->isGLValue() &&
  3732. "reference binding to unmaterialized r-value!");
  3733. if (E->isGLValue()) {
  3734. assert(E->getObjectKind() == OK_Ordinary);
  3735. return args.add(EmitReferenceBindingToExpr(E), type);
  3736. }
  3737. bool HasAggregateEvalKind = hasAggregateEvaluationKind(type);
  3738. // In the Microsoft C++ ABI, aggregate arguments are destructed by the callee.
  3739. // However, we still have to push an EH-only cleanup in case we unwind before
  3740. // we make it to the call.
  3741. if (type->isRecordType() &&
  3742. type->castAs<RecordType>()->getDecl()->isParamDestroyedInCallee()) {
  3743. // If we're using inalloca, use the argument memory. Otherwise, use a
  3744. // temporary.
  3745. AggValueSlot Slot = args.isUsingInAlloca()
  3746. ? createPlaceholderSlot(*this, type) : CreateAggTemp(type, "agg.tmp");
  3747. bool DestroyedInCallee = true, NeedsEHCleanup = true;
  3748. if (const auto *RD = type->getAsCXXRecordDecl())
  3749. DestroyedInCallee = RD->hasNonTrivialDestructor();
  3750. else
  3751. NeedsEHCleanup = needsEHCleanup(type.isDestructedType());
  3752. if (DestroyedInCallee)
  3753. Slot.setExternallyDestructed();
  3754. EmitAggExpr(E, Slot);
  3755. RValue RV = Slot.asRValue();
  3756. args.add(RV, type);
  3757. if (DestroyedInCallee && NeedsEHCleanup) {
  3758. // Create a no-op GEP between the placeholder and the cleanup so we can
  3759. // RAUW it successfully. It also serves as a marker of the first
  3760. // instruction where the cleanup is active.
  3761. pushFullExprCleanup<DestroyUnpassedArg>(EHCleanup, Slot.getAddress(),
  3762. type);
  3763. // This unreachable is a temporary marker which will be removed later.
  3764. llvm::Instruction *IsActive = Builder.CreateUnreachable();
  3765. args.addArgCleanupDeactivation(EHStack.getInnermostEHScope(), IsActive);
  3766. }
  3767. return;
  3768. }
  3769. if (HasAggregateEvalKind && isa<ImplicitCastExpr>(E) &&
  3770. cast<CastExpr>(E)->getCastKind() == CK_LValueToRValue) {
  3771. LValue L = EmitLValue(cast<CastExpr>(E)->getSubExpr());
  3772. assert(L.isSimple());
  3773. args.addUncopiedAggregate(L, type);
  3774. return;
  3775. }
  3776. args.add(EmitAnyExprToTemp(E), type);
  3777. }
  3778. QualType CodeGenFunction::getVarArgType(const Expr *Arg) {
  3779. // System headers on Windows define NULL to 0 instead of 0LL on Win64. MSVC
  3780. // implicitly widens null pointer constants that are arguments to varargs
  3781. // functions to pointer-sized ints.
  3782. if (!getTarget().getTriple().isOSWindows())
  3783. return Arg->getType();
  3784. if (Arg->getType()->isIntegerType() &&
  3785. getContext().getTypeSize(Arg->getType()) <
  3786. getContext().getTargetInfo().getPointerWidth(0) &&
  3787. Arg->isNullPointerConstant(getContext(),
  3788. Expr::NPC_ValueDependentIsNotNull)) {
  3789. return getContext().getIntPtrType();
  3790. }
  3791. return Arg->getType();
  3792. }
  3793. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3794. // optimizer it can aggressively ignore unwind edges.
  3795. void
  3796. CodeGenFunction::AddObjCARCExceptionMetadata(llvm::Instruction *Inst) {
  3797. if (CGM.getCodeGenOpts().OptimizationLevel != 0 &&
  3798. !CGM.getCodeGenOpts().ObjCAutoRefCountExceptions)
  3799. Inst->setMetadata("clang.arc.no_objc_arc_exceptions",
  3800. CGM.getNoObjCARCExceptionsMetadata());
  3801. }
  3802. /// Emits a call to the given no-arguments nounwind runtime function.
  3803. llvm::CallInst *
  3804. CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3805. const llvm::Twine &name) {
  3806. return EmitNounwindRuntimeCall(callee, None, name);
  3807. }
  3808. /// Emits a call to the given nounwind runtime function.
  3809. llvm::CallInst *
  3810. CodeGenFunction::EmitNounwindRuntimeCall(llvm::FunctionCallee callee,
  3811. ArrayRef<llvm::Value *> args,
  3812. const llvm::Twine &name) {
  3813. llvm::CallInst *call = EmitRuntimeCall(callee, args, name);
  3814. call->setDoesNotThrow();
  3815. return call;
  3816. }
  3817. /// Emits a simple call (never an invoke) to the given no-arguments
  3818. /// runtime function.
  3819. llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
  3820. const llvm::Twine &name) {
  3821. return EmitRuntimeCall(callee, None, name);
  3822. }
  3823. // Calls which may throw must have operand bundles indicating which funclet
  3824. // they are nested within.
  3825. SmallVector<llvm::OperandBundleDef, 1>
  3826. CodeGenFunction::getBundlesForFunclet(llvm::Value *Callee) {
  3827. SmallVector<llvm::OperandBundleDef, 1> BundleList;
  3828. // There is no need for a funclet operand bundle if we aren't inside a
  3829. // funclet.
  3830. if (!CurrentFuncletPad)
  3831. return BundleList;
  3832. // Skip intrinsics which cannot throw.
  3833. auto *CalleeFn = dyn_cast<llvm::Function>(Callee->stripPointerCasts());
  3834. if (CalleeFn && CalleeFn->isIntrinsic() && CalleeFn->doesNotThrow())
  3835. return BundleList;
  3836. BundleList.emplace_back("funclet", CurrentFuncletPad);
  3837. return BundleList;
  3838. }
  3839. /// Emits a simple call (never an invoke) to the given runtime function.
  3840. llvm::CallInst *CodeGenFunction::EmitRuntimeCall(llvm::FunctionCallee callee,
  3841. ArrayRef<llvm::Value *> args,
  3842. const llvm::Twine &name) {
  3843. llvm::CallInst *call = Builder.CreateCall(
  3844. callee, args, getBundlesForFunclet(callee.getCallee()), name);
  3845. call->setCallingConv(getRuntimeCC());
  3846. return call;
  3847. }
  3848. /// Emits a call or invoke to the given noreturn runtime function.
  3849. void CodeGenFunction::EmitNoreturnRuntimeCallOrInvoke(
  3850. llvm::FunctionCallee callee, ArrayRef<llvm::Value *> args) {
  3851. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3852. getBundlesForFunclet(callee.getCallee());
  3853. if (getInvokeDest()) {
  3854. llvm::InvokeInst *invoke =
  3855. Builder.CreateInvoke(callee,
  3856. getUnreachableBlock(),
  3857. getInvokeDest(),
  3858. args,
  3859. BundleList);
  3860. invoke->setDoesNotReturn();
  3861. invoke->setCallingConv(getRuntimeCC());
  3862. } else {
  3863. llvm::CallInst *call = Builder.CreateCall(callee, args, BundleList);
  3864. call->setDoesNotReturn();
  3865. call->setCallingConv(getRuntimeCC());
  3866. Builder.CreateUnreachable();
  3867. }
  3868. }
  3869. /// Emits a call or invoke instruction to the given nullary runtime function.
  3870. llvm::CallBase *
  3871. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3872. const Twine &name) {
  3873. return EmitRuntimeCallOrInvoke(callee, None, name);
  3874. }
  3875. /// Emits a call or invoke instruction to the given runtime function.
  3876. llvm::CallBase *
  3877. CodeGenFunction::EmitRuntimeCallOrInvoke(llvm::FunctionCallee callee,
  3878. ArrayRef<llvm::Value *> args,
  3879. const Twine &name) {
  3880. llvm::CallBase *call = EmitCallOrInvoke(callee, args, name);
  3881. call->setCallingConv(getRuntimeCC());
  3882. return call;
  3883. }
  3884. /// Emits a call or invoke instruction to the given function, depending
  3885. /// on the current state of the EH stack.
  3886. llvm::CallBase *CodeGenFunction::EmitCallOrInvoke(llvm::FunctionCallee Callee,
  3887. ArrayRef<llvm::Value *> Args,
  3888. const Twine &Name) {
  3889. llvm::BasicBlock *InvokeDest = getInvokeDest();
  3890. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  3891. getBundlesForFunclet(Callee.getCallee());
  3892. llvm::CallBase *Inst;
  3893. if (!InvokeDest)
  3894. Inst = Builder.CreateCall(Callee, Args, BundleList, Name);
  3895. else {
  3896. llvm::BasicBlock *ContBB = createBasicBlock("invoke.cont");
  3897. Inst = Builder.CreateInvoke(Callee, ContBB, InvokeDest, Args, BundleList,
  3898. Name);
  3899. EmitBlock(ContBB);
  3900. }
  3901. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  3902. // optimizer it can aggressively ignore unwind edges.
  3903. if (CGM.getLangOpts().ObjCAutoRefCount)
  3904. AddObjCARCExceptionMetadata(Inst);
  3905. return Inst;
  3906. }
  3907. void CodeGenFunction::deferPlaceholderReplacement(llvm::Instruction *Old,
  3908. llvm::Value *New) {
  3909. DeferredReplacements.push_back(
  3910. std::make_pair(llvm::WeakTrackingVH(Old), New));
  3911. }
  3912. namespace {
  3913. /// Specify given \p NewAlign as the alignment of return value attribute. If
  3914. /// such attribute already exists, re-set it to the maximal one of two options.
  3915. LLVM_NODISCARD llvm::AttributeList
  3916. maybeRaiseRetAlignmentAttribute(llvm::LLVMContext &Ctx,
  3917. const llvm::AttributeList &Attrs,
  3918. llvm::Align NewAlign) {
  3919. llvm::Align CurAlign = Attrs.getRetAlignment().valueOrOne();
  3920. if (CurAlign >= NewAlign)
  3921. return Attrs;
  3922. llvm::Attribute AlignAttr = llvm::Attribute::getWithAlignment(Ctx, NewAlign);
  3923. return Attrs.removeRetAttribute(Ctx, llvm::Attribute::AttrKind::Alignment)
  3924. .addRetAttribute(Ctx, AlignAttr);
  3925. }
  3926. template <typename AlignedAttrTy> class AbstractAssumeAlignedAttrEmitter {
  3927. protected:
  3928. CodeGenFunction &CGF;
  3929. /// We do nothing if this is, or becomes, nullptr.
  3930. const AlignedAttrTy *AA = nullptr;
  3931. llvm::Value *Alignment = nullptr; // May or may not be a constant.
  3932. llvm::ConstantInt *OffsetCI = nullptr; // Constant, hopefully zero.
  3933. AbstractAssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
  3934. : CGF(CGF_) {
  3935. if (!FuncDecl)
  3936. return;
  3937. AA = FuncDecl->getAttr<AlignedAttrTy>();
  3938. }
  3939. public:
  3940. /// If we can, materialize the alignment as an attribute on return value.
  3941. LLVM_NODISCARD llvm::AttributeList
  3942. TryEmitAsCallSiteAttribute(const llvm::AttributeList &Attrs) {
  3943. if (!AA || OffsetCI || CGF.SanOpts.has(SanitizerKind::Alignment))
  3944. return Attrs;
  3945. const auto *AlignmentCI = dyn_cast<llvm::ConstantInt>(Alignment);
  3946. if (!AlignmentCI)
  3947. return Attrs;
  3948. // We may legitimately have non-power-of-2 alignment here.
  3949. // If so, this is UB land, emit it via `@llvm.assume` instead.
  3950. if (!AlignmentCI->getValue().isPowerOf2())
  3951. return Attrs;
  3952. llvm::AttributeList NewAttrs = maybeRaiseRetAlignmentAttribute(
  3953. CGF.getLLVMContext(), Attrs,
  3954. llvm::Align(
  3955. AlignmentCI->getLimitedValue(llvm::Value::MaximumAlignment)));
  3956. AA = nullptr; // We're done. Disallow doing anything else.
  3957. return NewAttrs;
  3958. }
  3959. /// Emit alignment assumption.
  3960. /// This is a general fallback that we take if either there is an offset,
  3961. /// or the alignment is variable or we are sanitizing for alignment.
  3962. void EmitAsAnAssumption(SourceLocation Loc, QualType RetTy, RValue &Ret) {
  3963. if (!AA)
  3964. return;
  3965. CGF.emitAlignmentAssumption(Ret.getScalarVal(), RetTy, Loc,
  3966. AA->getLocation(), Alignment, OffsetCI);
  3967. AA = nullptr; // We're done. Disallow doing anything else.
  3968. }
  3969. };
  3970. /// Helper data structure to emit `AssumeAlignedAttr`.
  3971. class AssumeAlignedAttrEmitter final
  3972. : public AbstractAssumeAlignedAttrEmitter<AssumeAlignedAttr> {
  3973. public:
  3974. AssumeAlignedAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl)
  3975. : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
  3976. if (!AA)
  3977. return;
  3978. // It is guaranteed that the alignment/offset are constants.
  3979. Alignment = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(AA->getAlignment()));
  3980. if (Expr *Offset = AA->getOffset()) {
  3981. OffsetCI = cast<llvm::ConstantInt>(CGF.EmitScalarExpr(Offset));
  3982. if (OffsetCI->isNullValue()) // Canonicalize zero offset to no offset.
  3983. OffsetCI = nullptr;
  3984. }
  3985. }
  3986. };
  3987. /// Helper data structure to emit `AllocAlignAttr`.
  3988. class AllocAlignAttrEmitter final
  3989. : public AbstractAssumeAlignedAttrEmitter<AllocAlignAttr> {
  3990. public:
  3991. AllocAlignAttrEmitter(CodeGenFunction &CGF_, const Decl *FuncDecl,
  3992. const CallArgList &CallArgs)
  3993. : AbstractAssumeAlignedAttrEmitter(CGF_, FuncDecl) {
  3994. if (!AA)
  3995. return;
  3996. // Alignment may or may not be a constant, and that is okay.
  3997. Alignment = CallArgs[AA->getParamIndex().getLLVMIndex()]
  3998. .getRValue(CGF)
  3999. .getScalarVal();
  4000. }
  4001. };
  4002. } // namespace
  4003. RValue CodeGenFunction::EmitCall(const CGFunctionInfo &CallInfo,
  4004. const CGCallee &Callee,
  4005. ReturnValueSlot ReturnValue,
  4006. const CallArgList &CallArgs,
  4007. llvm::CallBase **callOrInvoke, bool IsMustTail,
  4008. SourceLocation Loc) {
  4009. // FIXME: We no longer need the types from CallArgs; lift up and simplify.
  4010. assert(Callee.isOrdinary() || Callee.isVirtual());
  4011. // Handle struct-return functions by passing a pointer to the
  4012. // location that we would like to return into.
  4013. QualType RetTy = CallInfo.getReturnType();
  4014. const ABIArgInfo &RetAI = CallInfo.getReturnInfo();
  4015. llvm::FunctionType *IRFuncTy = getTypes().GetFunctionType(CallInfo);
  4016. const Decl *TargetDecl = Callee.getAbstractInfo().getCalleeDecl().getDecl();
  4017. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(TargetDecl)) {
  4018. // We can only guarantee that a function is called from the correct
  4019. // context/function based on the appropriate target attributes,
  4020. // so only check in the case where we have both always_inline and target
  4021. // since otherwise we could be making a conditional call after a check for
  4022. // the proper cpu features (and it won't cause code generation issues due to
  4023. // function based code generation).
  4024. if (TargetDecl->hasAttr<AlwaysInlineAttr>() &&
  4025. TargetDecl->hasAttr<TargetAttr>())
  4026. checkTargetFeatures(Loc, FD);
  4027. // Some architectures (such as x86-64) have the ABI changed based on
  4028. // attribute-target/features. Give them a chance to diagnose.
  4029. CGM.getTargetCodeGenInfo().checkFunctionCallABI(
  4030. CGM, Loc, dyn_cast_or_null<FunctionDecl>(CurCodeDecl), FD, CallArgs);
  4031. }
  4032. #ifndef NDEBUG
  4033. if (!(CallInfo.isVariadic() && CallInfo.getArgStruct())) {
  4034. // For an inalloca varargs function, we don't expect CallInfo to match the
  4035. // function pointer's type, because the inalloca struct a will have extra
  4036. // fields in it for the varargs parameters. Code later in this function
  4037. // bitcasts the function pointer to the type derived from CallInfo.
  4038. //
  4039. // In other cases, we assert that the types match up (until pointers stop
  4040. // having pointee types).
  4041. if (Callee.isVirtual())
  4042. assert(IRFuncTy == Callee.getVirtualFunctionType());
  4043. else {
  4044. llvm::PointerType *PtrTy =
  4045. llvm::cast<llvm::PointerType>(Callee.getFunctionPointer()->getType());
  4046. assert(PtrTy->isOpaqueOrPointeeTypeMatches(IRFuncTy));
  4047. }
  4048. }
  4049. #endif
  4050. // 1. Set up the arguments.
  4051. // If we're using inalloca, insert the allocation after the stack save.
  4052. // FIXME: Do this earlier rather than hacking it in here!
  4053. Address ArgMemory = Address::invalid();
  4054. if (llvm::StructType *ArgStruct = CallInfo.getArgStruct()) {
  4055. const llvm::DataLayout &DL = CGM.getDataLayout();
  4056. llvm::Instruction *IP = CallArgs.getStackBase();
  4057. llvm::AllocaInst *AI;
  4058. if (IP) {
  4059. IP = IP->getNextNode();
  4060. AI = new llvm::AllocaInst(ArgStruct, DL.getAllocaAddrSpace(),
  4061. "argmem", IP);
  4062. } else {
  4063. AI = CreateTempAlloca(ArgStruct, "argmem");
  4064. }
  4065. auto Align = CallInfo.getArgStructAlignment();
  4066. AI->setAlignment(Align.getAsAlign());
  4067. AI->setUsedWithInAlloca(true);
  4068. assert(AI->isUsedWithInAlloca() && !AI->isStaticAlloca());
  4069. ArgMemory = Address(AI, Align);
  4070. }
  4071. ClangToLLVMArgMapping IRFunctionArgs(CGM.getContext(), CallInfo);
  4072. SmallVector<llvm::Value *, 16> IRCallArgs(IRFunctionArgs.totalIRArgs());
  4073. // If the call returns a temporary with struct return, create a temporary
  4074. // alloca to hold the result, unless one is given to us.
  4075. Address SRetPtr = Address::invalid();
  4076. Address SRetAlloca = Address::invalid();
  4077. llvm::Value *UnusedReturnSizePtr = nullptr;
  4078. if (RetAI.isIndirect() || RetAI.isInAlloca() || RetAI.isCoerceAndExpand()) {
  4079. if (!ReturnValue.isNull()) {
  4080. SRetPtr = ReturnValue.getValue();
  4081. } else {
  4082. SRetPtr = CreateMemTemp(RetTy, "tmp", &SRetAlloca);
  4083. if (HaveInsertPoint() && ReturnValue.isUnused()) {
  4084. llvm::TypeSize size =
  4085. CGM.getDataLayout().getTypeAllocSize(ConvertTypeForMem(RetTy));
  4086. UnusedReturnSizePtr = EmitLifetimeStart(size, SRetAlloca.getPointer());
  4087. }
  4088. }
  4089. if (IRFunctionArgs.hasSRetArg()) {
  4090. IRCallArgs[IRFunctionArgs.getSRetArgNo()] = SRetPtr.getPointer();
  4091. } else if (RetAI.isInAlloca()) {
  4092. Address Addr =
  4093. Builder.CreateStructGEP(ArgMemory, RetAI.getInAllocaFieldIndex());
  4094. Builder.CreateStore(SRetPtr.getPointer(), Addr);
  4095. }
  4096. }
  4097. Address swiftErrorTemp = Address::invalid();
  4098. Address swiftErrorArg = Address::invalid();
  4099. // When passing arguments using temporary allocas, we need to add the
  4100. // appropriate lifetime markers. This vector keeps track of all the lifetime
  4101. // markers that need to be ended right after the call.
  4102. SmallVector<CallLifetimeEnd, 2> CallLifetimeEndAfterCall;
  4103. // Translate all of the arguments as necessary to match the IR lowering.
  4104. assert(CallInfo.arg_size() == CallArgs.size() &&
  4105. "Mismatch between function signature & arguments.");
  4106. unsigned ArgNo = 0;
  4107. CGFunctionInfo::const_arg_iterator info_it = CallInfo.arg_begin();
  4108. for (CallArgList::const_iterator I = CallArgs.begin(), E = CallArgs.end();
  4109. I != E; ++I, ++info_it, ++ArgNo) {
  4110. const ABIArgInfo &ArgInfo = info_it->info;
  4111. // Insert a padding argument to ensure proper alignment.
  4112. if (IRFunctionArgs.hasPaddingArg(ArgNo))
  4113. IRCallArgs[IRFunctionArgs.getPaddingArgNo(ArgNo)] =
  4114. llvm::UndefValue::get(ArgInfo.getPaddingType());
  4115. unsigned FirstIRArg, NumIRArgs;
  4116. std::tie(FirstIRArg, NumIRArgs) = IRFunctionArgs.getIRArgs(ArgNo);
  4117. switch (ArgInfo.getKind()) {
  4118. case ABIArgInfo::InAlloca: {
  4119. assert(NumIRArgs == 0);
  4120. assert(getTarget().getTriple().getArch() == llvm::Triple::x86);
  4121. if (I->isAggregate()) {
  4122. Address Addr = I->hasLValue()
  4123. ? I->getKnownLValue().getAddress(*this)
  4124. : I->getKnownRValue().getAggregateAddress();
  4125. llvm::Instruction *Placeholder =
  4126. cast<llvm::Instruction>(Addr.getPointer());
  4127. if (!ArgInfo.getInAllocaIndirect()) {
  4128. // Replace the placeholder with the appropriate argument slot GEP.
  4129. CGBuilderTy::InsertPoint IP = Builder.saveIP();
  4130. Builder.SetInsertPoint(Placeholder);
  4131. Addr = Builder.CreateStructGEP(ArgMemory,
  4132. ArgInfo.getInAllocaFieldIndex());
  4133. Builder.restoreIP(IP);
  4134. } else {
  4135. // For indirect things such as overaligned structs, replace the
  4136. // placeholder with a regular aggregate temporary alloca. Store the
  4137. // address of this alloca into the struct.
  4138. Addr = CreateMemTemp(info_it->type, "inalloca.indirect.tmp");
  4139. Address ArgSlot = Builder.CreateStructGEP(
  4140. ArgMemory, ArgInfo.getInAllocaFieldIndex());
  4141. Builder.CreateStore(Addr.getPointer(), ArgSlot);
  4142. }
  4143. deferPlaceholderReplacement(Placeholder, Addr.getPointer());
  4144. } else if (ArgInfo.getInAllocaIndirect()) {
  4145. // Make a temporary alloca and store the address of it into the argument
  4146. // struct.
  4147. Address Addr = CreateMemTempWithoutCast(
  4148. I->Ty, getContext().getTypeAlignInChars(I->Ty),
  4149. "indirect-arg-temp");
  4150. I->copyInto(*this, Addr);
  4151. Address ArgSlot =
  4152. Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
  4153. Builder.CreateStore(Addr.getPointer(), ArgSlot);
  4154. } else {
  4155. // Store the RValue into the argument struct.
  4156. Address Addr =
  4157. Builder.CreateStructGEP(ArgMemory, ArgInfo.getInAllocaFieldIndex());
  4158. unsigned AS = Addr.getType()->getPointerAddressSpace();
  4159. llvm::Type *MemType = ConvertTypeForMem(I->Ty)->getPointerTo(AS);
  4160. // There are some cases where a trivial bitcast is not avoidable. The
  4161. // definition of a type later in a translation unit may change it's type
  4162. // from {}* to (%struct.foo*)*.
  4163. if (Addr.getType() != MemType)
  4164. Addr = Builder.CreateBitCast(Addr, MemType);
  4165. I->copyInto(*this, Addr);
  4166. }
  4167. break;
  4168. }
  4169. case ABIArgInfo::Indirect:
  4170. case ABIArgInfo::IndirectAliased: {
  4171. assert(NumIRArgs == 1);
  4172. if (!I->isAggregate()) {
  4173. // Make a temporary alloca to pass the argument.
  4174. Address Addr = CreateMemTempWithoutCast(
  4175. I->Ty, ArgInfo.getIndirectAlign(), "indirect-arg-temp");
  4176. IRCallArgs[FirstIRArg] = Addr.getPointer();
  4177. I->copyInto(*this, Addr);
  4178. } else {
  4179. // We want to avoid creating an unnecessary temporary+copy here;
  4180. // however, we need one in three cases:
  4181. // 1. If the argument is not byval, and we are required to copy the
  4182. // source. (This case doesn't occur on any common architecture.)
  4183. // 2. If the argument is byval, RV is not sufficiently aligned, and
  4184. // we cannot force it to be sufficiently aligned.
  4185. // 3. If the argument is byval, but RV is not located in default
  4186. // or alloca address space.
  4187. Address Addr = I->hasLValue()
  4188. ? I->getKnownLValue().getAddress(*this)
  4189. : I->getKnownRValue().getAggregateAddress();
  4190. llvm::Value *V = Addr.getPointer();
  4191. CharUnits Align = ArgInfo.getIndirectAlign();
  4192. const llvm::DataLayout *TD = &CGM.getDataLayout();
  4193. assert((FirstIRArg >= IRFuncTy->getNumParams() ||
  4194. IRFuncTy->getParamType(FirstIRArg)->getPointerAddressSpace() ==
  4195. TD->getAllocaAddrSpace()) &&
  4196. "indirect argument must be in alloca address space");
  4197. bool NeedCopy = false;
  4198. if (Addr.getAlignment() < Align &&
  4199. llvm::getOrEnforceKnownAlignment(V, Align.getAsAlign(), *TD) <
  4200. Align.getAsAlign()) {
  4201. NeedCopy = true;
  4202. } else if (I->hasLValue()) {
  4203. auto LV = I->getKnownLValue();
  4204. auto AS = LV.getAddressSpace();
  4205. if (!ArgInfo.getIndirectByVal() ||
  4206. (LV.getAlignment() < getContext().getTypeAlignInChars(I->Ty))) {
  4207. NeedCopy = true;
  4208. }
  4209. if (!getLangOpts().OpenCL) {
  4210. if ((ArgInfo.getIndirectByVal() &&
  4211. (AS != LangAS::Default &&
  4212. AS != CGM.getASTAllocaAddressSpace()))) {
  4213. NeedCopy = true;
  4214. }
  4215. }
  4216. // For OpenCL even if RV is located in default or alloca address space
  4217. // we don't want to perform address space cast for it.
  4218. else if ((ArgInfo.getIndirectByVal() &&
  4219. Addr.getType()->getAddressSpace() != IRFuncTy->
  4220. getParamType(FirstIRArg)->getPointerAddressSpace())) {
  4221. NeedCopy = true;
  4222. }
  4223. }
  4224. if (NeedCopy) {
  4225. // Create an aligned temporary, and copy to it.
  4226. Address AI = CreateMemTempWithoutCast(
  4227. I->Ty, ArgInfo.getIndirectAlign(), "byval-temp");
  4228. IRCallArgs[FirstIRArg] = AI.getPointer();
  4229. // Emit lifetime markers for the temporary alloca.
  4230. llvm::TypeSize ByvalTempElementSize =
  4231. CGM.getDataLayout().getTypeAllocSize(AI.getElementType());
  4232. llvm::Value *LifetimeSize =
  4233. EmitLifetimeStart(ByvalTempElementSize, AI.getPointer());
  4234. // Add cleanup code to emit the end lifetime marker after the call.
  4235. if (LifetimeSize) // In case we disabled lifetime markers.
  4236. CallLifetimeEndAfterCall.emplace_back(AI, LifetimeSize);
  4237. // Generate the copy.
  4238. I->copyInto(*this, AI);
  4239. } else {
  4240. // Skip the extra memcpy call.
  4241. auto *T = llvm::PointerType::getWithSamePointeeType(
  4242. cast<llvm::PointerType>(V->getType()),
  4243. CGM.getDataLayout().getAllocaAddrSpace());
  4244. IRCallArgs[FirstIRArg] = getTargetHooks().performAddrSpaceCast(
  4245. *this, V, LangAS::Default, CGM.getASTAllocaAddressSpace(), T,
  4246. true);
  4247. }
  4248. }
  4249. break;
  4250. }
  4251. case ABIArgInfo::Ignore:
  4252. assert(NumIRArgs == 0);
  4253. break;
  4254. case ABIArgInfo::Extend:
  4255. case ABIArgInfo::Direct: {
  4256. if (!isa<llvm::StructType>(ArgInfo.getCoerceToType()) &&
  4257. ArgInfo.getCoerceToType() == ConvertType(info_it->type) &&
  4258. ArgInfo.getDirectOffset() == 0) {
  4259. assert(NumIRArgs == 1);
  4260. llvm::Value *V;
  4261. if (!I->isAggregate())
  4262. V = I->getKnownRValue().getScalarVal();
  4263. else
  4264. V = Builder.CreateLoad(
  4265. I->hasLValue() ? I->getKnownLValue().getAddress(*this)
  4266. : I->getKnownRValue().getAggregateAddress());
  4267. // Implement swifterror by copying into a new swifterror argument.
  4268. // We'll write back in the normal path out of the call.
  4269. if (CallInfo.getExtParameterInfo(ArgNo).getABI()
  4270. == ParameterABI::SwiftErrorResult) {
  4271. assert(!swiftErrorTemp.isValid() && "multiple swifterror args");
  4272. QualType pointeeTy = I->Ty->getPointeeType();
  4273. swiftErrorArg =
  4274. Address(V, getContext().getTypeAlignInChars(pointeeTy));
  4275. swiftErrorTemp =
  4276. CreateMemTemp(pointeeTy, getPointerAlign(), "swifterror.temp");
  4277. V = swiftErrorTemp.getPointer();
  4278. cast<llvm::AllocaInst>(V)->setSwiftError(true);
  4279. llvm::Value *errorValue = Builder.CreateLoad(swiftErrorArg);
  4280. Builder.CreateStore(errorValue, swiftErrorTemp);
  4281. }
  4282. // We might have to widen integers, but we should never truncate.
  4283. if (ArgInfo.getCoerceToType() != V->getType() &&
  4284. V->getType()->isIntegerTy())
  4285. V = Builder.CreateZExt(V, ArgInfo.getCoerceToType());
  4286. // If the argument doesn't match, perform a bitcast to coerce it. This
  4287. // can happen due to trivial type mismatches.
  4288. if (FirstIRArg < IRFuncTy->getNumParams() &&
  4289. V->getType() != IRFuncTy->getParamType(FirstIRArg))
  4290. V = Builder.CreateBitCast(V, IRFuncTy->getParamType(FirstIRArg));
  4291. IRCallArgs[FirstIRArg] = V;
  4292. break;
  4293. }
  4294. // FIXME: Avoid the conversion through memory if possible.
  4295. Address Src = Address::invalid();
  4296. if (!I->isAggregate()) {
  4297. Src = CreateMemTemp(I->Ty, "coerce");
  4298. I->copyInto(*this, Src);
  4299. } else {
  4300. Src = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
  4301. : I->getKnownRValue().getAggregateAddress();
  4302. }
  4303. // If the value is offset in memory, apply the offset now.
  4304. Src = emitAddressAtOffset(*this, Src, ArgInfo);
  4305. // Fast-isel and the optimizer generally like scalar values better than
  4306. // FCAs, so we flatten them if this is safe to do for this argument.
  4307. llvm::StructType *STy =
  4308. dyn_cast<llvm::StructType>(ArgInfo.getCoerceToType());
  4309. if (STy && ArgInfo.isDirect() && ArgInfo.getCanBeFlattened()) {
  4310. llvm::Type *SrcTy = Src.getElementType();
  4311. uint64_t SrcSize = CGM.getDataLayout().getTypeAllocSize(SrcTy);
  4312. uint64_t DstSize = CGM.getDataLayout().getTypeAllocSize(STy);
  4313. // If the source type is smaller than the destination type of the
  4314. // coerce-to logic, copy the source value into a temp alloca the size
  4315. // of the destination type to allow loading all of it. The bits past
  4316. // the source value are left undef.
  4317. if (SrcSize < DstSize) {
  4318. Address TempAlloca
  4319. = CreateTempAlloca(STy, Src.getAlignment(),
  4320. Src.getName() + ".coerce");
  4321. Builder.CreateMemCpy(TempAlloca, Src, SrcSize);
  4322. Src = TempAlloca;
  4323. } else {
  4324. Src = Builder.CreateElementBitCast(Src, STy);
  4325. }
  4326. assert(NumIRArgs == STy->getNumElements());
  4327. for (unsigned i = 0, e = STy->getNumElements(); i != e; ++i) {
  4328. Address EltPtr = Builder.CreateStructGEP(Src, i);
  4329. llvm::Value *LI = Builder.CreateLoad(EltPtr);
  4330. IRCallArgs[FirstIRArg + i] = LI;
  4331. }
  4332. } else {
  4333. // In the simple case, just pass the coerced loaded value.
  4334. assert(NumIRArgs == 1);
  4335. llvm::Value *Load =
  4336. CreateCoercedLoad(Src, ArgInfo.getCoerceToType(), *this);
  4337. if (CallInfo.isCmseNSCall()) {
  4338. // For certain parameter types, clear padding bits, as they may reveal
  4339. // sensitive information.
  4340. // Small struct/union types are passed as integer arrays.
  4341. auto *ATy = dyn_cast<llvm::ArrayType>(Load->getType());
  4342. if (ATy != nullptr && isa<RecordType>(I->Ty.getCanonicalType()))
  4343. Load = EmitCMSEClearRecord(Load, ATy, I->Ty);
  4344. }
  4345. IRCallArgs[FirstIRArg] = Load;
  4346. }
  4347. break;
  4348. }
  4349. case ABIArgInfo::CoerceAndExpand: {
  4350. auto coercionType = ArgInfo.getCoerceAndExpandType();
  4351. auto layout = CGM.getDataLayout().getStructLayout(coercionType);
  4352. llvm::Value *tempSize = nullptr;
  4353. Address addr = Address::invalid();
  4354. Address AllocaAddr = Address::invalid();
  4355. if (I->isAggregate()) {
  4356. addr = I->hasLValue() ? I->getKnownLValue().getAddress(*this)
  4357. : I->getKnownRValue().getAggregateAddress();
  4358. } else {
  4359. RValue RV = I->getKnownRValue();
  4360. assert(RV.isScalar()); // complex should always just be direct
  4361. llvm::Type *scalarType = RV.getScalarVal()->getType();
  4362. auto scalarSize = CGM.getDataLayout().getTypeAllocSize(scalarType);
  4363. auto scalarAlign = CGM.getDataLayout().getPrefTypeAlignment(scalarType);
  4364. // Materialize to a temporary.
  4365. addr =
  4366. CreateTempAlloca(RV.getScalarVal()->getType(),
  4367. CharUnits::fromQuantity(std::max(
  4368. layout->getAlignment().value(), scalarAlign)),
  4369. "tmp",
  4370. /*ArraySize=*/nullptr, &AllocaAddr);
  4371. tempSize = EmitLifetimeStart(scalarSize, AllocaAddr.getPointer());
  4372. Builder.CreateStore(RV.getScalarVal(), addr);
  4373. }
  4374. addr = Builder.CreateElementBitCast(addr, coercionType);
  4375. unsigned IRArgPos = FirstIRArg;
  4376. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  4377. llvm::Type *eltType = coercionType->getElementType(i);
  4378. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
  4379. Address eltAddr = Builder.CreateStructGEP(addr, i);
  4380. llvm::Value *elt = Builder.CreateLoad(eltAddr);
  4381. IRCallArgs[IRArgPos++] = elt;
  4382. }
  4383. assert(IRArgPos == FirstIRArg + NumIRArgs);
  4384. if (tempSize) {
  4385. EmitLifetimeEnd(tempSize, AllocaAddr.getPointer());
  4386. }
  4387. break;
  4388. }
  4389. case ABIArgInfo::Expand: {
  4390. unsigned IRArgPos = FirstIRArg;
  4391. ExpandTypeToArgs(I->Ty, *I, IRFuncTy, IRCallArgs, IRArgPos);
  4392. assert(IRArgPos == FirstIRArg + NumIRArgs);
  4393. break;
  4394. }
  4395. }
  4396. }
  4397. const CGCallee &ConcreteCallee = Callee.prepareConcreteCallee(*this);
  4398. llvm::Value *CalleePtr = ConcreteCallee.getFunctionPointer();
  4399. // If we're using inalloca, set up that argument.
  4400. if (ArgMemory.isValid()) {
  4401. llvm::Value *Arg = ArgMemory.getPointer();
  4402. if (CallInfo.isVariadic()) {
  4403. // When passing non-POD arguments by value to variadic functions, we will
  4404. // end up with a variadic prototype and an inalloca call site. In such
  4405. // cases, we can't do any parameter mismatch checks. Give up and bitcast
  4406. // the callee.
  4407. unsigned CalleeAS = CalleePtr->getType()->getPointerAddressSpace();
  4408. CalleePtr =
  4409. Builder.CreateBitCast(CalleePtr, IRFuncTy->getPointerTo(CalleeAS));
  4410. } else {
  4411. llvm::Type *LastParamTy =
  4412. IRFuncTy->getParamType(IRFuncTy->getNumParams() - 1);
  4413. if (Arg->getType() != LastParamTy) {
  4414. #ifndef NDEBUG
  4415. // Assert that these structs have equivalent element types.
  4416. llvm::StructType *FullTy = CallInfo.getArgStruct();
  4417. llvm::StructType *DeclaredTy =
  4418. cast<llvm::StructType>(LastParamTy->getPointerElementType());
  4419. assert(DeclaredTy->getNumElements() == FullTy->getNumElements());
  4420. for (llvm::StructType::element_iterator DI = DeclaredTy->element_begin(),
  4421. DE = DeclaredTy->element_end(),
  4422. FI = FullTy->element_begin();
  4423. DI != DE; ++DI, ++FI)
  4424. assert(*DI == *FI);
  4425. #endif
  4426. Arg = Builder.CreateBitCast(Arg, LastParamTy);
  4427. }
  4428. }
  4429. assert(IRFunctionArgs.hasInallocaArg());
  4430. IRCallArgs[IRFunctionArgs.getInallocaArgNo()] = Arg;
  4431. }
  4432. // 2. Prepare the function pointer.
  4433. // If the callee is a bitcast of a non-variadic function to have a
  4434. // variadic function pointer type, check to see if we can remove the
  4435. // bitcast. This comes up with unprototyped functions.
  4436. //
  4437. // This makes the IR nicer, but more importantly it ensures that we
  4438. // can inline the function at -O0 if it is marked always_inline.
  4439. auto simplifyVariadicCallee = [](llvm::FunctionType *CalleeFT,
  4440. llvm::Value *Ptr) -> llvm::Function * {
  4441. if (!CalleeFT->isVarArg())
  4442. return nullptr;
  4443. // Get underlying value if it's a bitcast
  4444. if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Ptr)) {
  4445. if (CE->getOpcode() == llvm::Instruction::BitCast)
  4446. Ptr = CE->getOperand(0);
  4447. }
  4448. llvm::Function *OrigFn = dyn_cast<llvm::Function>(Ptr);
  4449. if (!OrigFn)
  4450. return nullptr;
  4451. llvm::FunctionType *OrigFT = OrigFn->getFunctionType();
  4452. // If the original type is variadic, or if any of the component types
  4453. // disagree, we cannot remove the cast.
  4454. if (OrigFT->isVarArg() ||
  4455. OrigFT->getNumParams() != CalleeFT->getNumParams() ||
  4456. OrigFT->getReturnType() != CalleeFT->getReturnType())
  4457. return nullptr;
  4458. for (unsigned i = 0, e = OrigFT->getNumParams(); i != e; ++i)
  4459. if (OrigFT->getParamType(i) != CalleeFT->getParamType(i))
  4460. return nullptr;
  4461. return OrigFn;
  4462. };
  4463. if (llvm::Function *OrigFn = simplifyVariadicCallee(IRFuncTy, CalleePtr)) {
  4464. CalleePtr = OrigFn;
  4465. IRFuncTy = OrigFn->getFunctionType();
  4466. }
  4467. // 3. Perform the actual call.
  4468. // Deactivate any cleanups that we're supposed to do immediately before
  4469. // the call.
  4470. if (!CallArgs.getCleanupsToDeactivate().empty())
  4471. deactivateArgCleanupsBeforeCall(*this, CallArgs);
  4472. // Assert that the arguments we computed match up. The IR verifier
  4473. // will catch this, but this is a common enough source of problems
  4474. // during IRGen changes that it's way better for debugging to catch
  4475. // it ourselves here.
  4476. #ifndef NDEBUG
  4477. assert(IRCallArgs.size() == IRFuncTy->getNumParams() || IRFuncTy->isVarArg());
  4478. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  4479. // Inalloca argument can have different type.
  4480. if (IRFunctionArgs.hasInallocaArg() &&
  4481. i == IRFunctionArgs.getInallocaArgNo())
  4482. continue;
  4483. if (i < IRFuncTy->getNumParams())
  4484. assert(IRCallArgs[i]->getType() == IRFuncTy->getParamType(i));
  4485. }
  4486. #endif
  4487. // Update the largest vector width if any arguments have vector types.
  4488. for (unsigned i = 0; i < IRCallArgs.size(); ++i) {
  4489. if (auto *VT = dyn_cast<llvm::VectorType>(IRCallArgs[i]->getType()))
  4490. LargestVectorWidth =
  4491. std::max((uint64_t)LargestVectorWidth,
  4492. VT->getPrimitiveSizeInBits().getKnownMinSize());
  4493. }
  4494. // Compute the calling convention and attributes.
  4495. unsigned CallingConv;
  4496. llvm::AttributeList Attrs;
  4497. CGM.ConstructAttributeList(CalleePtr->getName(), CallInfo,
  4498. Callee.getAbstractInfo(), Attrs, CallingConv,
  4499. /*AttrOnCallSite=*/true,
  4500. /*IsThunk=*/false);
  4501. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
  4502. if (FD->hasAttr<StrictFPAttr>())
  4503. // All calls within a strictfp function are marked strictfp
  4504. Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
  4505. // Add call-site nomerge attribute if exists.
  4506. if (InNoMergeAttributedStmt)
  4507. Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoMerge);
  4508. // Apply some call-site-specific attributes.
  4509. // TODO: work this into building the attribute set.
  4510. // Apply always_inline to all calls within flatten functions.
  4511. // FIXME: should this really take priority over __try, below?
  4512. if (CurCodeDecl && CurCodeDecl->hasAttr<FlattenAttr>() &&
  4513. !(TargetDecl && TargetDecl->hasAttr<NoInlineAttr>())) {
  4514. Attrs =
  4515. Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::AlwaysInline);
  4516. }
  4517. // Disable inlining inside SEH __try blocks.
  4518. if (isSEHTryScope()) {
  4519. Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::NoInline);
  4520. }
  4521. // Decide whether to use a call or an invoke.
  4522. bool CannotThrow;
  4523. if (currentFunctionUsesSEHTry()) {
  4524. // SEH cares about asynchronous exceptions, so everything can "throw."
  4525. CannotThrow = false;
  4526. } else if (isCleanupPadScope() &&
  4527. EHPersonality::get(*this).isMSVCXXPersonality()) {
  4528. // The MSVC++ personality will implicitly terminate the program if an
  4529. // exception is thrown during a cleanup outside of a try/catch.
  4530. // We don't need to model anything in IR to get this behavior.
  4531. CannotThrow = true;
  4532. } else {
  4533. // Otherwise, nounwind call sites will never throw.
  4534. CannotThrow = Attrs.hasFnAttr(llvm::Attribute::NoUnwind);
  4535. if (auto *FPtr = dyn_cast<llvm::Function>(CalleePtr))
  4536. if (FPtr->hasFnAttribute(llvm::Attribute::NoUnwind))
  4537. CannotThrow = true;
  4538. }
  4539. // If we made a temporary, be sure to clean up after ourselves. Note that we
  4540. // can't depend on being inside of an ExprWithCleanups, so we need to manually
  4541. // pop this cleanup later on. Being eager about this is OK, since this
  4542. // temporary is 'invisible' outside of the callee.
  4543. if (UnusedReturnSizePtr)
  4544. pushFullExprCleanup<CallLifetimeEnd>(NormalEHLifetimeMarker, SRetAlloca,
  4545. UnusedReturnSizePtr);
  4546. llvm::BasicBlock *InvokeDest = CannotThrow ? nullptr : getInvokeDest();
  4547. SmallVector<llvm::OperandBundleDef, 1> BundleList =
  4548. getBundlesForFunclet(CalleePtr);
  4549. if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl))
  4550. if (FD->hasAttr<StrictFPAttr>())
  4551. // All calls within a strictfp function are marked strictfp
  4552. Attrs = Attrs.addFnAttribute(getLLVMContext(), llvm::Attribute::StrictFP);
  4553. AssumeAlignedAttrEmitter AssumeAlignedAttrEmitter(*this, TargetDecl);
  4554. Attrs = AssumeAlignedAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
  4555. AllocAlignAttrEmitter AllocAlignAttrEmitter(*this, TargetDecl, CallArgs);
  4556. Attrs = AllocAlignAttrEmitter.TryEmitAsCallSiteAttribute(Attrs);
  4557. // Emit the actual call/invoke instruction.
  4558. llvm::CallBase *CI;
  4559. if (!InvokeDest) {
  4560. CI = Builder.CreateCall(IRFuncTy, CalleePtr, IRCallArgs, BundleList);
  4561. } else {
  4562. llvm::BasicBlock *Cont = createBasicBlock("invoke.cont");
  4563. CI = Builder.CreateInvoke(IRFuncTy, CalleePtr, Cont, InvokeDest, IRCallArgs,
  4564. BundleList);
  4565. EmitBlock(Cont);
  4566. }
  4567. if (callOrInvoke)
  4568. *callOrInvoke = CI;
  4569. // If this is within a function that has the guard(nocf) attribute and is an
  4570. // indirect call, add the "guard_nocf" attribute to this call to indicate that
  4571. // Control Flow Guard checks should not be added, even if the call is inlined.
  4572. if (const auto *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
  4573. if (const auto *A = FD->getAttr<CFGuardAttr>()) {
  4574. if (A->getGuard() == CFGuardAttr::GuardArg::nocf && !CI->getCalledFunction())
  4575. Attrs = Attrs.addFnAttribute(getLLVMContext(), "guard_nocf");
  4576. }
  4577. }
  4578. // Apply the attributes and calling convention.
  4579. CI->setAttributes(Attrs);
  4580. CI->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
  4581. // Apply various metadata.
  4582. if (!CI->getType()->isVoidTy())
  4583. CI->setName("call");
  4584. // Update largest vector width from the return type.
  4585. if (auto *VT = dyn_cast<llvm::VectorType>(CI->getType()))
  4586. LargestVectorWidth =
  4587. std::max((uint64_t)LargestVectorWidth,
  4588. VT->getPrimitiveSizeInBits().getKnownMinSize());
  4589. // Insert instrumentation or attach profile metadata at indirect call sites.
  4590. // For more details, see the comment before the definition of
  4591. // IPVK_IndirectCallTarget in InstrProfData.inc.
  4592. if (!CI->getCalledFunction())
  4593. PGO.valueProfile(Builder, llvm::IPVK_IndirectCallTarget,
  4594. CI, CalleePtr);
  4595. // In ObjC ARC mode with no ObjC ARC exception safety, tell the ARC
  4596. // optimizer it can aggressively ignore unwind edges.
  4597. if (CGM.getLangOpts().ObjCAutoRefCount)
  4598. AddObjCARCExceptionMetadata(CI);
  4599. // Set tail call kind if necessary.
  4600. if (llvm::CallInst *Call = dyn_cast<llvm::CallInst>(CI)) {
  4601. if (TargetDecl && TargetDecl->hasAttr<NotTailCalledAttr>())
  4602. Call->setTailCallKind(llvm::CallInst::TCK_NoTail);
  4603. else if (IsMustTail)
  4604. Call->setTailCallKind(llvm::CallInst::TCK_MustTail);
  4605. }
  4606. // Add metadata for calls to MSAllocator functions
  4607. if (getDebugInfo() && TargetDecl &&
  4608. TargetDecl->hasAttr<MSAllocatorAttr>())
  4609. getDebugInfo()->addHeapAllocSiteMetadata(CI, RetTy->getPointeeType(), Loc);
  4610. // Add metadata if calling an __attribute__((error(""))) or warning fn.
  4611. if (TargetDecl && TargetDecl->hasAttr<ErrorAttr>()) {
  4612. llvm::ConstantInt *Line =
  4613. llvm::ConstantInt::get(Int32Ty, Loc.getRawEncoding());
  4614. llvm::ConstantAsMetadata *MD = llvm::ConstantAsMetadata::get(Line);
  4615. llvm::MDTuple *MDT = llvm::MDNode::get(getLLVMContext(), {MD});
  4616. CI->setMetadata("srcloc", MDT);
  4617. }
  4618. // 4. Finish the call.
  4619. // If the call doesn't return, finish the basic block and clear the
  4620. // insertion point; this allows the rest of IRGen to discard
  4621. // unreachable code.
  4622. if (CI->doesNotReturn()) {
  4623. if (UnusedReturnSizePtr)
  4624. PopCleanupBlock();
  4625. // Strip away the noreturn attribute to better diagnose unreachable UB.
  4626. if (SanOpts.has(SanitizerKind::Unreachable)) {
  4627. // Also remove from function since CallBase::hasFnAttr additionally checks
  4628. // attributes of the called function.
  4629. if (auto *F = CI->getCalledFunction())
  4630. F->removeFnAttr(llvm::Attribute::NoReturn);
  4631. CI->removeFnAttr(llvm::Attribute::NoReturn);
  4632. // Avoid incompatibility with ASan which relies on the `noreturn`
  4633. // attribute to insert handler calls.
  4634. if (SanOpts.hasOneOf(SanitizerKind::Address |
  4635. SanitizerKind::KernelAddress)) {
  4636. SanitizerScope SanScope(this);
  4637. llvm::IRBuilder<>::InsertPointGuard IPGuard(Builder);
  4638. Builder.SetInsertPoint(CI);
  4639. auto *FnType = llvm::FunctionType::get(CGM.VoidTy, /*isVarArg=*/false);
  4640. llvm::FunctionCallee Fn =
  4641. CGM.CreateRuntimeFunction(FnType, "__asan_handle_no_return");
  4642. EmitNounwindRuntimeCall(Fn);
  4643. }
  4644. }
  4645. EmitUnreachable(Loc);
  4646. Builder.ClearInsertionPoint();
  4647. // FIXME: For now, emit a dummy basic block because expr emitters in
  4648. // generally are not ready to handle emitting expressions at unreachable
  4649. // points.
  4650. EnsureInsertPoint();
  4651. // Return a reasonable RValue.
  4652. return GetUndefRValue(RetTy);
  4653. }
  4654. // If this is a musttail call, return immediately. We do not branch to the
  4655. // epilogue in this case.
  4656. if (IsMustTail) {
  4657. for (auto it = EHStack.find(CurrentCleanupScopeDepth); it != EHStack.end();
  4658. ++it) {
  4659. EHCleanupScope *Cleanup = dyn_cast<EHCleanupScope>(&*it);
  4660. if (!(Cleanup && Cleanup->getCleanup()->isRedundantBeforeReturn()))
  4661. CGM.ErrorUnsupported(MustTailCall, "tail call skipping over cleanups");
  4662. }
  4663. if (CI->getType()->isVoidTy())
  4664. Builder.CreateRetVoid();
  4665. else
  4666. Builder.CreateRet(CI);
  4667. Builder.ClearInsertionPoint();
  4668. EnsureInsertPoint();
  4669. return GetUndefRValue(RetTy);
  4670. }
  4671. // Perform the swifterror writeback.
  4672. if (swiftErrorTemp.isValid()) {
  4673. llvm::Value *errorResult = Builder.CreateLoad(swiftErrorTemp);
  4674. Builder.CreateStore(errorResult, swiftErrorArg);
  4675. }
  4676. // Emit any call-associated writebacks immediately. Arguably this
  4677. // should happen after any return-value munging.
  4678. if (CallArgs.hasWritebacks())
  4679. emitWritebacks(*this, CallArgs);
  4680. // The stack cleanup for inalloca arguments has to run out of the normal
  4681. // lexical order, so deactivate it and run it manually here.
  4682. CallArgs.freeArgumentMemory(*this);
  4683. // Extract the return value.
  4684. RValue Ret = [&] {
  4685. switch (RetAI.getKind()) {
  4686. case ABIArgInfo::CoerceAndExpand: {
  4687. auto coercionType = RetAI.getCoerceAndExpandType();
  4688. Address addr = SRetPtr;
  4689. addr = Builder.CreateElementBitCast(addr, coercionType);
  4690. assert(CI->getType() == RetAI.getUnpaddedCoerceAndExpandType());
  4691. bool requiresExtract = isa<llvm::StructType>(CI->getType());
  4692. unsigned unpaddedIndex = 0;
  4693. for (unsigned i = 0, e = coercionType->getNumElements(); i != e; ++i) {
  4694. llvm::Type *eltType = coercionType->getElementType(i);
  4695. if (ABIArgInfo::isPaddingForCoerceAndExpand(eltType)) continue;
  4696. Address eltAddr = Builder.CreateStructGEP(addr, i);
  4697. llvm::Value *elt = CI;
  4698. if (requiresExtract)
  4699. elt = Builder.CreateExtractValue(elt, unpaddedIndex++);
  4700. else
  4701. assert(unpaddedIndex == 0);
  4702. Builder.CreateStore(elt, eltAddr);
  4703. }
  4704. // FALLTHROUGH
  4705. LLVM_FALLTHROUGH;
  4706. }
  4707. case ABIArgInfo::InAlloca:
  4708. case ABIArgInfo::Indirect: {
  4709. RValue ret = convertTempToRValue(SRetPtr, RetTy, SourceLocation());
  4710. if (UnusedReturnSizePtr)
  4711. PopCleanupBlock();
  4712. return ret;
  4713. }
  4714. case ABIArgInfo::Ignore:
  4715. // If we are ignoring an argument that had a result, make sure to
  4716. // construct the appropriate return value for our caller.
  4717. return GetUndefRValue(RetTy);
  4718. case ABIArgInfo::Extend:
  4719. case ABIArgInfo::Direct: {
  4720. llvm::Type *RetIRTy = ConvertType(RetTy);
  4721. if (RetAI.getCoerceToType() == RetIRTy && RetAI.getDirectOffset() == 0) {
  4722. switch (getEvaluationKind(RetTy)) {
  4723. case TEK_Complex: {
  4724. llvm::Value *Real = Builder.CreateExtractValue(CI, 0);
  4725. llvm::Value *Imag = Builder.CreateExtractValue(CI, 1);
  4726. return RValue::getComplex(std::make_pair(Real, Imag));
  4727. }
  4728. case TEK_Aggregate: {
  4729. Address DestPtr = ReturnValue.getValue();
  4730. bool DestIsVolatile = ReturnValue.isVolatile();
  4731. if (!DestPtr.isValid()) {
  4732. DestPtr = CreateMemTemp(RetTy, "agg.tmp");
  4733. DestIsVolatile = false;
  4734. }
  4735. EmitAggregateStore(CI, DestPtr, DestIsVolatile);
  4736. return RValue::getAggregate(DestPtr);
  4737. }
  4738. case TEK_Scalar: {
  4739. // If the argument doesn't match, perform a bitcast to coerce it. This
  4740. // can happen due to trivial type mismatches.
  4741. llvm::Value *V = CI;
  4742. if (V->getType() != RetIRTy)
  4743. V = Builder.CreateBitCast(V, RetIRTy);
  4744. return RValue::get(V);
  4745. }
  4746. }
  4747. llvm_unreachable("bad evaluation kind");
  4748. }
  4749. Address DestPtr = ReturnValue.getValue();
  4750. bool DestIsVolatile = ReturnValue.isVolatile();
  4751. if (!DestPtr.isValid()) {
  4752. DestPtr = CreateMemTemp(RetTy, "coerce");
  4753. DestIsVolatile = false;
  4754. }
  4755. // If the value is offset in memory, apply the offset now.
  4756. Address StorePtr = emitAddressAtOffset(*this, DestPtr, RetAI);
  4757. CreateCoercedStore(CI, StorePtr, DestIsVolatile, *this);
  4758. return convertTempToRValue(DestPtr, RetTy, SourceLocation());
  4759. }
  4760. case ABIArgInfo::Expand:
  4761. case ABIArgInfo::IndirectAliased:
  4762. llvm_unreachable("Invalid ABI kind for return argument");
  4763. }
  4764. llvm_unreachable("Unhandled ABIArgInfo::Kind");
  4765. } ();
  4766. // Emit the assume_aligned check on the return value.
  4767. if (Ret.isScalar() && TargetDecl) {
  4768. AssumeAlignedAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
  4769. AllocAlignAttrEmitter.EmitAsAnAssumption(Loc, RetTy, Ret);
  4770. }
  4771. // Explicitly call CallLifetimeEnd::Emit just to re-use the code even though
  4772. // we can't use the full cleanup mechanism.
  4773. for (CallLifetimeEnd &LifetimeEnd : CallLifetimeEndAfterCall)
  4774. LifetimeEnd.Emit(*this, /*Flags=*/{});
  4775. if (!ReturnValue.isExternallyDestructed() &&
  4776. RetTy.isDestructedType() == QualType::DK_nontrivial_c_struct)
  4777. pushDestroy(QualType::DK_nontrivial_c_struct, Ret.getAggregateAddress(),
  4778. RetTy);
  4779. return Ret;
  4780. }
  4781. CGCallee CGCallee::prepareConcreteCallee(CodeGenFunction &CGF) const {
  4782. if (isVirtual()) {
  4783. const CallExpr *CE = getVirtualCallExpr();
  4784. return CGF.CGM.getCXXABI().getVirtualFunctionPointer(
  4785. CGF, getVirtualMethodDecl(), getThisAddress(), getVirtualFunctionType(),
  4786. CE ? CE->getBeginLoc() : SourceLocation());
  4787. }
  4788. return *this;
  4789. }
  4790. /* VarArg handling */
  4791. Address CodeGenFunction::EmitVAArg(VAArgExpr *VE, Address &VAListAddr) {
  4792. VAListAddr = VE->isMicrosoftABI()
  4793. ? EmitMSVAListRef(VE->getSubExpr())
  4794. : EmitVAListRef(VE->getSubExpr());
  4795. QualType Ty = VE->getType();
  4796. if (VE->isMicrosoftABI())
  4797. return CGM.getTypes().getABIInfo().EmitMSVAArg(*this, VAListAddr, Ty);
  4798. return CGM.getTypes().getABIInfo().EmitVAArg(*this, VAListAddr, Ty);
  4799. }