1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
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 // This file implements the auto-upgrade helper functions.
10 // This is where deprecated IR intrinsics and other IR features are updated to
11 // current specifications.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/IR/AutoUpgrade.h"
16 #include "llvm/ADT/StringSwitch.h"
17 #include "llvm/IR/Constants.h"
18 #include "llvm/IR/DIBuilder.h"
19 #include "llvm/IR/DebugInfo.h"
20 #include "llvm/IR/DiagnosticInfo.h"
21 #include "llvm/IR/Function.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instruction.h"
24 #include "llvm/IR/InstVisitor.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/Intrinsics.h"
27 #include "llvm/IR/IntrinsicsAArch64.h"
28 #include "llvm/IR/IntrinsicsARM.h"
29 #include "llvm/IR/IntrinsicsX86.h"
30 #include "llvm/IR/LLVMContext.h"
31 #include "llvm/IR/Module.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/Support/ErrorHandling.h"
34 #include "llvm/Support/Regex.h"
35 #include <cstring>
36 using namespace llvm;
37 
rename(GlobalValue * GV)38 static void rename(GlobalValue *GV) { GV->setName(GV->getName() + ".old"); }
39 
40 // Upgrade the declarations of the SSE4.1 ptest intrinsics whose arguments have
41 // changed their type from v4f32 to v2i64.
UpgradePTESTIntrinsic(Function * F,Intrinsic::ID IID,Function * & NewFn)42 static bool UpgradePTESTIntrinsic(Function* F, Intrinsic::ID IID,
43                                   Function *&NewFn) {
44   // Check whether this is an old version of the function, which received
45   // v4f32 arguments.
46   Type *Arg0Type = F->getFunctionType()->getParamType(0);
47   if (Arg0Type != FixedVectorType::get(Type::getFloatTy(F->getContext()), 4))
48     return false;
49 
50   // Yes, it's old, replace it with new version.
51   rename(F);
52   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
53   return true;
54 }
55 
56 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
57 // arguments have changed their type from i32 to i8.
UpgradeX86IntrinsicsWith8BitMask(Function * F,Intrinsic::ID IID,Function * & NewFn)58 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
59                                              Function *&NewFn) {
60   // Check that the last argument is an i32.
61   Type *LastArgType = F->getFunctionType()->getParamType(
62      F->getFunctionType()->getNumParams() - 1);
63   if (!LastArgType->isIntegerTy(32))
64     return false;
65 
66   // Move this function aside and map down.
67   rename(F);
68   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
69   return true;
70 }
71 
72 // Upgrade the declaration of fp compare intrinsics that change return type
73 // from scalar to vXi1 mask.
UpgradeX86MaskedFPCompare(Function * F,Intrinsic::ID IID,Function * & NewFn)74 static bool UpgradeX86MaskedFPCompare(Function *F, Intrinsic::ID IID,
75                                       Function *&NewFn) {
76   // Check if the return type is a vector.
77   if (F->getReturnType()->isVectorTy())
78     return false;
79 
80   rename(F);
81   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
82   return true;
83 }
84 
ShouldUpgradeX86Intrinsic(Function * F,StringRef Name)85 static bool ShouldUpgradeX86Intrinsic(Function *F, StringRef Name) {
86   // All of the intrinsics matches below should be marked with which llvm
87   // version started autoupgrading them. At some point in the future we would
88   // like to use this information to remove upgrade code for some older
89   // intrinsics. It is currently undecided how we will determine that future
90   // point.
91   if (Name == "addcarryx.u32" || // Added in 8.0
92       Name == "addcarryx.u64" || // Added in 8.0
93       Name == "addcarry.u32" || // Added in 8.0
94       Name == "addcarry.u64" || // Added in 8.0
95       Name == "subborrow.u32" || // Added in 8.0
96       Name == "subborrow.u64" || // Added in 8.0
97       Name.startswith("sse2.padds.") || // Added in 8.0
98       Name.startswith("sse2.psubs.") || // Added in 8.0
99       Name.startswith("sse2.paddus.") || // Added in 8.0
100       Name.startswith("sse2.psubus.") || // Added in 8.0
101       Name.startswith("avx2.padds.") || // Added in 8.0
102       Name.startswith("avx2.psubs.") || // Added in 8.0
103       Name.startswith("avx2.paddus.") || // Added in 8.0
104       Name.startswith("avx2.psubus.") || // Added in 8.0
105       Name.startswith("avx512.padds.") || // Added in 8.0
106       Name.startswith("avx512.psubs.") || // Added in 8.0
107       Name.startswith("avx512.mask.padds.") || // Added in 8.0
108       Name.startswith("avx512.mask.psubs.") || // Added in 8.0
109       Name.startswith("avx512.mask.paddus.") || // Added in 8.0
110       Name.startswith("avx512.mask.psubus.") || // Added in 8.0
111       Name=="ssse3.pabs.b.128" || // Added in 6.0
112       Name=="ssse3.pabs.w.128" || // Added in 6.0
113       Name=="ssse3.pabs.d.128" || // Added in 6.0
114       Name.startswith("fma4.vfmadd.s") || // Added in 7.0
115       Name.startswith("fma.vfmadd.") || // Added in 7.0
116       Name.startswith("fma.vfmsub.") || // Added in 7.0
117       Name.startswith("fma.vfmsubadd.") || // Added in 7.0
118       Name.startswith("fma.vfnmadd.") || // Added in 7.0
119       Name.startswith("fma.vfnmsub.") || // Added in 7.0
120       Name.startswith("avx512.mask.vfmadd.") || // Added in 7.0
121       Name.startswith("avx512.mask.vfnmadd.") || // Added in 7.0
122       Name.startswith("avx512.mask.vfnmsub.") || // Added in 7.0
123       Name.startswith("avx512.mask3.vfmadd.") || // Added in 7.0
124       Name.startswith("avx512.maskz.vfmadd.") || // Added in 7.0
125       Name.startswith("avx512.mask3.vfmsub.") || // Added in 7.0
126       Name.startswith("avx512.mask3.vfnmsub.") || // Added in 7.0
127       Name.startswith("avx512.mask.vfmaddsub.") || // Added in 7.0
128       Name.startswith("avx512.maskz.vfmaddsub.") || // Added in 7.0
129       Name.startswith("avx512.mask3.vfmaddsub.") || // Added in 7.0
130       Name.startswith("avx512.mask3.vfmsubadd.") || // Added in 7.0
131       Name.startswith("avx512.mask.shuf.i") || // Added in 6.0
132       Name.startswith("avx512.mask.shuf.f") || // Added in 6.0
133       Name.startswith("avx512.kunpck") || //added in 6.0
134       Name.startswith("avx2.pabs.") || // Added in 6.0
135       Name.startswith("avx512.mask.pabs.") || // Added in 6.0
136       Name.startswith("avx512.broadcastm") || // Added in 6.0
137       Name == "sse.sqrt.ss" || // Added in 7.0
138       Name == "sse2.sqrt.sd" || // Added in 7.0
139       Name.startswith("avx512.mask.sqrt.p") || // Added in 7.0
140       Name.startswith("avx.sqrt.p") || // Added in 7.0
141       Name.startswith("sse2.sqrt.p") || // Added in 7.0
142       Name.startswith("sse.sqrt.p") || // Added in 7.0
143       Name.startswith("avx512.mask.pbroadcast") || // Added in 6.0
144       Name.startswith("sse2.pcmpeq.") || // Added in 3.1
145       Name.startswith("sse2.pcmpgt.") || // Added in 3.1
146       Name.startswith("avx2.pcmpeq.") || // Added in 3.1
147       Name.startswith("avx2.pcmpgt.") || // Added in 3.1
148       Name.startswith("avx512.mask.pcmpeq.") || // Added in 3.9
149       Name.startswith("avx512.mask.pcmpgt.") || // Added in 3.9
150       Name.startswith("avx.vperm2f128.") || // Added in 6.0
151       Name == "avx2.vperm2i128" || // Added in 6.0
152       Name == "sse.add.ss" || // Added in 4.0
153       Name == "sse2.add.sd" || // Added in 4.0
154       Name == "sse.sub.ss" || // Added in 4.0
155       Name == "sse2.sub.sd" || // Added in 4.0
156       Name == "sse.mul.ss" || // Added in 4.0
157       Name == "sse2.mul.sd" || // Added in 4.0
158       Name == "sse.div.ss" || // Added in 4.0
159       Name == "sse2.div.sd" || // Added in 4.0
160       Name == "sse41.pmaxsb" || // Added in 3.9
161       Name == "sse2.pmaxs.w" || // Added in 3.9
162       Name == "sse41.pmaxsd" || // Added in 3.9
163       Name == "sse2.pmaxu.b" || // Added in 3.9
164       Name == "sse41.pmaxuw" || // Added in 3.9
165       Name == "sse41.pmaxud" || // Added in 3.9
166       Name == "sse41.pminsb" || // Added in 3.9
167       Name == "sse2.pmins.w" || // Added in 3.9
168       Name == "sse41.pminsd" || // Added in 3.9
169       Name == "sse2.pminu.b" || // Added in 3.9
170       Name == "sse41.pminuw" || // Added in 3.9
171       Name == "sse41.pminud" || // Added in 3.9
172       Name == "avx512.kand.w" || // Added in 7.0
173       Name == "avx512.kandn.w" || // Added in 7.0
174       Name == "avx512.knot.w" || // Added in 7.0
175       Name == "avx512.kor.w" || // Added in 7.0
176       Name == "avx512.kxor.w" || // Added in 7.0
177       Name == "avx512.kxnor.w" || // Added in 7.0
178       Name == "avx512.kortestc.w" || // Added in 7.0
179       Name == "avx512.kortestz.w" || // Added in 7.0
180       Name.startswith("avx512.mask.pshuf.b.") || // Added in 4.0
181       Name.startswith("avx2.pmax") || // Added in 3.9
182       Name.startswith("avx2.pmin") || // Added in 3.9
183       Name.startswith("avx512.mask.pmax") || // Added in 4.0
184       Name.startswith("avx512.mask.pmin") || // Added in 4.0
185       Name.startswith("avx2.vbroadcast") || // Added in 3.8
186       Name.startswith("avx2.pbroadcast") || // Added in 3.8
187       Name.startswith("avx.vpermil.") || // Added in 3.1
188       Name.startswith("sse2.pshuf") || // Added in 3.9
189       Name.startswith("avx512.pbroadcast") || // Added in 3.9
190       Name.startswith("avx512.mask.broadcast.s") || // Added in 3.9
191       Name.startswith("avx512.mask.movddup") || // Added in 3.9
192       Name.startswith("avx512.mask.movshdup") || // Added in 3.9
193       Name.startswith("avx512.mask.movsldup") || // Added in 3.9
194       Name.startswith("avx512.mask.pshuf.d.") || // Added in 3.9
195       Name.startswith("avx512.mask.pshufl.w.") || // Added in 3.9
196       Name.startswith("avx512.mask.pshufh.w.") || // Added in 3.9
197       Name.startswith("avx512.mask.shuf.p") || // Added in 4.0
198       Name.startswith("avx512.mask.vpermil.p") || // Added in 3.9
199       Name.startswith("avx512.mask.perm.df.") || // Added in 3.9
200       Name.startswith("avx512.mask.perm.di.") || // Added in 3.9
201       Name.startswith("avx512.mask.punpckl") || // Added in 3.9
202       Name.startswith("avx512.mask.punpckh") || // Added in 3.9
203       Name.startswith("avx512.mask.unpckl.") || // Added in 3.9
204       Name.startswith("avx512.mask.unpckh.") || // Added in 3.9
205       Name.startswith("avx512.mask.pand.") || // Added in 3.9
206       Name.startswith("avx512.mask.pandn.") || // Added in 3.9
207       Name.startswith("avx512.mask.por.") || // Added in 3.9
208       Name.startswith("avx512.mask.pxor.") || // Added in 3.9
209       Name.startswith("avx512.mask.and.") || // Added in 3.9
210       Name.startswith("avx512.mask.andn.") || // Added in 3.9
211       Name.startswith("avx512.mask.or.") || // Added in 3.9
212       Name.startswith("avx512.mask.xor.") || // Added in 3.9
213       Name.startswith("avx512.mask.padd.") || // Added in 4.0
214       Name.startswith("avx512.mask.psub.") || // Added in 4.0
215       Name.startswith("avx512.mask.pmull.") || // Added in 4.0
216       Name.startswith("avx512.mask.cvtdq2pd.") || // Added in 4.0
217       Name.startswith("avx512.mask.cvtudq2pd.") || // Added in 4.0
218       Name.startswith("avx512.mask.cvtudq2ps.") || // Added in 7.0 updated 9.0
219       Name.startswith("avx512.mask.cvtqq2pd.") || // Added in 7.0 updated 9.0
220       Name.startswith("avx512.mask.cvtuqq2pd.") || // Added in 7.0 updated 9.0
221       Name.startswith("avx512.mask.cvtdq2ps.") || // Added in 7.0 updated 9.0
222       Name == "avx512.mask.vcvtph2ps.128" || // Added in 11.0
223       Name == "avx512.mask.vcvtph2ps.256" || // Added in 11.0
224       Name == "avx512.mask.cvtqq2ps.256" || // Added in 9.0
225       Name == "avx512.mask.cvtqq2ps.512" || // Added in 9.0
226       Name == "avx512.mask.cvtuqq2ps.256" || // Added in 9.0
227       Name == "avx512.mask.cvtuqq2ps.512" || // Added in 9.0
228       Name == "avx512.mask.cvtpd2dq.256" || // Added in 7.0
229       Name == "avx512.mask.cvtpd2ps.256" || // Added in 7.0
230       Name == "avx512.mask.cvttpd2dq.256" || // Added in 7.0
231       Name == "avx512.mask.cvttps2dq.128" || // Added in 7.0
232       Name == "avx512.mask.cvttps2dq.256" || // Added in 7.0
233       Name == "avx512.mask.cvtps2pd.128" || // Added in 7.0
234       Name == "avx512.mask.cvtps2pd.256" || // Added in 7.0
235       Name == "avx512.cvtusi2sd" || // Added in 7.0
236       Name.startswith("avx512.mask.permvar.") || // Added in 7.0
237       Name == "sse2.pmulu.dq" || // Added in 7.0
238       Name == "sse41.pmuldq" || // Added in 7.0
239       Name == "avx2.pmulu.dq" || // Added in 7.0
240       Name == "avx2.pmul.dq" || // Added in 7.0
241       Name == "avx512.pmulu.dq.512" || // Added in 7.0
242       Name == "avx512.pmul.dq.512" || // Added in 7.0
243       Name.startswith("avx512.mask.pmul.dq.") || // Added in 4.0
244       Name.startswith("avx512.mask.pmulu.dq.") || // Added in 4.0
245       Name.startswith("avx512.mask.pmul.hr.sw.") || // Added in 7.0
246       Name.startswith("avx512.mask.pmulh.w.") || // Added in 7.0
247       Name.startswith("avx512.mask.pmulhu.w.") || // Added in 7.0
248       Name.startswith("avx512.mask.pmaddw.d.") || // Added in 7.0
249       Name.startswith("avx512.mask.pmaddubs.w.") || // Added in 7.0
250       Name.startswith("avx512.mask.packsswb.") || // Added in 5.0
251       Name.startswith("avx512.mask.packssdw.") || // Added in 5.0
252       Name.startswith("avx512.mask.packuswb.") || // Added in 5.0
253       Name.startswith("avx512.mask.packusdw.") || // Added in 5.0
254       Name.startswith("avx512.mask.cmp.b") || // Added in 5.0
255       Name.startswith("avx512.mask.cmp.d") || // Added in 5.0
256       Name.startswith("avx512.mask.cmp.q") || // Added in 5.0
257       Name.startswith("avx512.mask.cmp.w") || // Added in 5.0
258       Name.startswith("avx512.cmp.p") || // Added in 12.0
259       Name.startswith("avx512.mask.ucmp.") || // Added in 5.0
260       Name.startswith("avx512.cvtb2mask.") || // Added in 7.0
261       Name.startswith("avx512.cvtw2mask.") || // Added in 7.0
262       Name.startswith("avx512.cvtd2mask.") || // Added in 7.0
263       Name.startswith("avx512.cvtq2mask.") || // Added in 7.0
264       Name.startswith("avx512.mask.vpermilvar.") || // Added in 4.0
265       Name.startswith("avx512.mask.psll.d") || // Added in 4.0
266       Name.startswith("avx512.mask.psll.q") || // Added in 4.0
267       Name.startswith("avx512.mask.psll.w") || // Added in 4.0
268       Name.startswith("avx512.mask.psra.d") || // Added in 4.0
269       Name.startswith("avx512.mask.psra.q") || // Added in 4.0
270       Name.startswith("avx512.mask.psra.w") || // Added in 4.0
271       Name.startswith("avx512.mask.psrl.d") || // Added in 4.0
272       Name.startswith("avx512.mask.psrl.q") || // Added in 4.0
273       Name.startswith("avx512.mask.psrl.w") || // Added in 4.0
274       Name.startswith("avx512.mask.pslli") || // Added in 4.0
275       Name.startswith("avx512.mask.psrai") || // Added in 4.0
276       Name.startswith("avx512.mask.psrli") || // Added in 4.0
277       Name.startswith("avx512.mask.psllv") || // Added in 4.0
278       Name.startswith("avx512.mask.psrav") || // Added in 4.0
279       Name.startswith("avx512.mask.psrlv") || // Added in 4.0
280       Name.startswith("sse41.pmovsx") || // Added in 3.8
281       Name.startswith("sse41.pmovzx") || // Added in 3.9
282       Name.startswith("avx2.pmovsx") || // Added in 3.9
283       Name.startswith("avx2.pmovzx") || // Added in 3.9
284       Name.startswith("avx512.mask.pmovsx") || // Added in 4.0
285       Name.startswith("avx512.mask.pmovzx") || // Added in 4.0
286       Name.startswith("avx512.mask.lzcnt.") || // Added in 5.0
287       Name.startswith("avx512.mask.pternlog.") || // Added in 7.0
288       Name.startswith("avx512.maskz.pternlog.") || // Added in 7.0
289       Name.startswith("avx512.mask.vpmadd52") || // Added in 7.0
290       Name.startswith("avx512.maskz.vpmadd52") || // Added in 7.0
291       Name.startswith("avx512.mask.vpermi2var.") || // Added in 7.0
292       Name.startswith("avx512.mask.vpermt2var.") || // Added in 7.0
293       Name.startswith("avx512.maskz.vpermt2var.") || // Added in 7.0
294       Name.startswith("avx512.mask.vpdpbusd.") || // Added in 7.0
295       Name.startswith("avx512.maskz.vpdpbusd.") || // Added in 7.0
296       Name.startswith("avx512.mask.vpdpbusds.") || // Added in 7.0
297       Name.startswith("avx512.maskz.vpdpbusds.") || // Added in 7.0
298       Name.startswith("avx512.mask.vpdpwssd.") || // Added in 7.0
299       Name.startswith("avx512.maskz.vpdpwssd.") || // Added in 7.0
300       Name.startswith("avx512.mask.vpdpwssds.") || // Added in 7.0
301       Name.startswith("avx512.maskz.vpdpwssds.") || // Added in 7.0
302       Name.startswith("avx512.mask.dbpsadbw.") || // Added in 7.0
303       Name.startswith("avx512.mask.vpshld.") || // Added in 7.0
304       Name.startswith("avx512.mask.vpshrd.") || // Added in 7.0
305       Name.startswith("avx512.mask.vpshldv.") || // Added in 8.0
306       Name.startswith("avx512.mask.vpshrdv.") || // Added in 8.0
307       Name.startswith("avx512.maskz.vpshldv.") || // Added in 8.0
308       Name.startswith("avx512.maskz.vpshrdv.") || // Added in 8.0
309       Name.startswith("avx512.vpshld.") || // Added in 8.0
310       Name.startswith("avx512.vpshrd.") || // Added in 8.0
311       Name.startswith("avx512.mask.add.p") || // Added in 7.0. 128/256 in 4.0
312       Name.startswith("avx512.mask.sub.p") || // Added in 7.0. 128/256 in 4.0
313       Name.startswith("avx512.mask.mul.p") || // Added in 7.0. 128/256 in 4.0
314       Name.startswith("avx512.mask.div.p") || // Added in 7.0. 128/256 in 4.0
315       Name.startswith("avx512.mask.max.p") || // Added in 7.0. 128/256 in 5.0
316       Name.startswith("avx512.mask.min.p") || // Added in 7.0. 128/256 in 5.0
317       Name.startswith("avx512.mask.fpclass.p") || // Added in 7.0
318       Name.startswith("avx512.mask.vpshufbitqmb.") || // Added in 8.0
319       Name.startswith("avx512.mask.pmultishift.qb.") || // Added in 8.0
320       Name.startswith("avx512.mask.conflict.") || // Added in 9.0
321       Name == "avx512.mask.pmov.qd.256" || // Added in 9.0
322       Name == "avx512.mask.pmov.qd.512" || // Added in 9.0
323       Name == "avx512.mask.pmov.wb.256" || // Added in 9.0
324       Name == "avx512.mask.pmov.wb.512" || // Added in 9.0
325       Name == "sse.cvtsi2ss" || // Added in 7.0
326       Name == "sse.cvtsi642ss" || // Added in 7.0
327       Name == "sse2.cvtsi2sd" || // Added in 7.0
328       Name == "sse2.cvtsi642sd" || // Added in 7.0
329       Name == "sse2.cvtss2sd" || // Added in 7.0
330       Name == "sse2.cvtdq2pd" || // Added in 3.9
331       Name == "sse2.cvtdq2ps" || // Added in 7.0
332       Name == "sse2.cvtps2pd" || // Added in 3.9
333       Name == "avx.cvtdq2.pd.256" || // Added in 3.9
334       Name == "avx.cvtdq2.ps.256" || // Added in 7.0
335       Name == "avx.cvt.ps2.pd.256" || // Added in 3.9
336       Name.startswith("vcvtph2ps.") || // Added in 11.0
337       Name.startswith("avx.vinsertf128.") || // Added in 3.7
338       Name == "avx2.vinserti128" || // Added in 3.7
339       Name.startswith("avx512.mask.insert") || // Added in 4.0
340       Name.startswith("avx.vextractf128.") || // Added in 3.7
341       Name == "avx2.vextracti128" || // Added in 3.7
342       Name.startswith("avx512.mask.vextract") || // Added in 4.0
343       Name.startswith("sse4a.movnt.") || // Added in 3.9
344       Name.startswith("avx.movnt.") || // Added in 3.2
345       Name.startswith("avx512.storent.") || // Added in 3.9
346       Name == "sse41.movntdqa" || // Added in 5.0
347       Name == "avx2.movntdqa" || // Added in 5.0
348       Name == "avx512.movntdqa" || // Added in 5.0
349       Name == "sse2.storel.dq" || // Added in 3.9
350       Name.startswith("sse.storeu.") || // Added in 3.9
351       Name.startswith("sse2.storeu.") || // Added in 3.9
352       Name.startswith("avx.storeu.") || // Added in 3.9
353       Name.startswith("avx512.mask.storeu.") || // Added in 3.9
354       Name.startswith("avx512.mask.store.p") || // Added in 3.9
355       Name.startswith("avx512.mask.store.b.") || // Added in 3.9
356       Name.startswith("avx512.mask.store.w.") || // Added in 3.9
357       Name.startswith("avx512.mask.store.d.") || // Added in 3.9
358       Name.startswith("avx512.mask.store.q.") || // Added in 3.9
359       Name == "avx512.mask.store.ss" || // Added in 7.0
360       Name.startswith("avx512.mask.loadu.") || // Added in 3.9
361       Name.startswith("avx512.mask.load.") || // Added in 3.9
362       Name.startswith("avx512.mask.expand.load.") || // Added in 7.0
363       Name.startswith("avx512.mask.compress.store.") || // Added in 7.0
364       Name.startswith("avx512.mask.expand.b") || // Added in 9.0
365       Name.startswith("avx512.mask.expand.w") || // Added in 9.0
366       Name.startswith("avx512.mask.expand.d") || // Added in 9.0
367       Name.startswith("avx512.mask.expand.q") || // Added in 9.0
368       Name.startswith("avx512.mask.expand.p") || // Added in 9.0
369       Name.startswith("avx512.mask.compress.b") || // Added in 9.0
370       Name.startswith("avx512.mask.compress.w") || // Added in 9.0
371       Name.startswith("avx512.mask.compress.d") || // Added in 9.0
372       Name.startswith("avx512.mask.compress.q") || // Added in 9.0
373       Name.startswith("avx512.mask.compress.p") || // Added in 9.0
374       Name == "sse42.crc32.64.8" || // Added in 3.4
375       Name.startswith("avx.vbroadcast.s") || // Added in 3.5
376       Name.startswith("avx512.vbroadcast.s") || // Added in 7.0
377       Name.startswith("avx512.mask.palignr.") || // Added in 3.9
378       Name.startswith("avx512.mask.valign.") || // Added in 4.0
379       Name.startswith("sse2.psll.dq") || // Added in 3.7
380       Name.startswith("sse2.psrl.dq") || // Added in 3.7
381       Name.startswith("avx2.psll.dq") || // Added in 3.7
382       Name.startswith("avx2.psrl.dq") || // Added in 3.7
383       Name.startswith("avx512.psll.dq") || // Added in 3.9
384       Name.startswith("avx512.psrl.dq") || // Added in 3.9
385       Name == "sse41.pblendw" || // Added in 3.7
386       Name.startswith("sse41.blendp") || // Added in 3.7
387       Name.startswith("avx.blend.p") || // Added in 3.7
388       Name == "avx2.pblendw" || // Added in 3.7
389       Name.startswith("avx2.pblendd.") || // Added in 3.7
390       Name.startswith("avx.vbroadcastf128") || // Added in 4.0
391       Name == "avx2.vbroadcasti128" || // Added in 3.7
392       Name.startswith("avx512.mask.broadcastf32x4.") || // Added in 6.0
393       Name.startswith("avx512.mask.broadcastf64x2.") || // Added in 6.0
394       Name.startswith("avx512.mask.broadcastf32x8.") || // Added in 6.0
395       Name.startswith("avx512.mask.broadcastf64x4.") || // Added in 6.0
396       Name.startswith("avx512.mask.broadcasti32x4.") || // Added in 6.0
397       Name.startswith("avx512.mask.broadcasti64x2.") || // Added in 6.0
398       Name.startswith("avx512.mask.broadcasti32x8.") || // Added in 6.0
399       Name.startswith("avx512.mask.broadcasti64x4.") || // Added in 6.0
400       Name == "xop.vpcmov" || // Added in 3.8
401       Name == "xop.vpcmov.256" || // Added in 5.0
402       Name.startswith("avx512.mask.move.s") || // Added in 4.0
403       Name.startswith("avx512.cvtmask2") || // Added in 5.0
404       Name.startswith("xop.vpcom") || // Added in 3.2, Updated in 9.0
405       Name.startswith("xop.vprot") || // Added in 8.0
406       Name.startswith("avx512.prol") || // Added in 8.0
407       Name.startswith("avx512.pror") || // Added in 8.0
408       Name.startswith("avx512.mask.prorv.") || // Added in 8.0
409       Name.startswith("avx512.mask.pror.") ||  // Added in 8.0
410       Name.startswith("avx512.mask.prolv.") || // Added in 8.0
411       Name.startswith("avx512.mask.prol.") ||  // Added in 8.0
412       Name.startswith("avx512.ptestm") || //Added in 6.0
413       Name.startswith("avx512.ptestnm") || //Added in 6.0
414       Name.startswith("avx512.mask.pavg")) // Added in 6.0
415     return true;
416 
417   return false;
418 }
419 
UpgradeX86IntrinsicFunction(Function * F,StringRef Name,Function * & NewFn)420 static bool UpgradeX86IntrinsicFunction(Function *F, StringRef Name,
421                                         Function *&NewFn) {
422   // Only handle intrinsics that start with "x86.".
423   if (!Name.startswith("x86."))
424     return false;
425   // Remove "x86." prefix.
426   Name = Name.substr(4);
427 
428   if (ShouldUpgradeX86Intrinsic(F, Name)) {
429     NewFn = nullptr;
430     return true;
431   }
432 
433   if (Name == "rdtscp") { // Added in 8.0
434     // If this intrinsic has 0 operands, it's the new version.
435     if (F->getFunctionType()->getNumParams() == 0)
436       return false;
437 
438     rename(F);
439     NewFn = Intrinsic::getDeclaration(F->getParent(),
440                                       Intrinsic::x86_rdtscp);
441     return true;
442   }
443 
444   // SSE4.1 ptest functions may have an old signature.
445   if (Name.startswith("sse41.ptest")) { // Added in 3.2
446     if (Name.substr(11) == "c")
447       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestc, NewFn);
448     if (Name.substr(11) == "z")
449       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestz, NewFn);
450     if (Name.substr(11) == "nzc")
451       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
452   }
453   // Several blend and other instructions with masks used the wrong number of
454   // bits.
455   if (Name == "sse41.insertps") // Added in 3.6
456     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
457                                             NewFn);
458   if (Name == "sse41.dppd") // Added in 3.6
459     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
460                                             NewFn);
461   if (Name == "sse41.dpps") // Added in 3.6
462     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
463                                             NewFn);
464   if (Name == "sse41.mpsadbw") // Added in 3.6
465     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
466                                             NewFn);
467   if (Name == "avx.dp.ps.256") // Added in 3.6
468     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
469                                             NewFn);
470   if (Name == "avx2.mpsadbw") // Added in 3.6
471     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
472                                             NewFn);
473   if (Name == "avx512.mask.cmp.pd.128") // Added in 7.0
474     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_128,
475                                      NewFn);
476   if (Name == "avx512.mask.cmp.pd.256") // Added in 7.0
477     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_256,
478                                      NewFn);
479   if (Name == "avx512.mask.cmp.pd.512") // Added in 7.0
480     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_512,
481                                      NewFn);
482   if (Name == "avx512.mask.cmp.ps.128") // Added in 7.0
483     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_128,
484                                      NewFn);
485   if (Name == "avx512.mask.cmp.ps.256") // Added in 7.0
486     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_256,
487                                      NewFn);
488   if (Name == "avx512.mask.cmp.ps.512") // Added in 7.0
489     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_512,
490                                      NewFn);
491 
492   // frcz.ss/sd may need to have an argument dropped. Added in 3.2
493   if (Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
494     rename(F);
495     NewFn = Intrinsic::getDeclaration(F->getParent(),
496                                       Intrinsic::x86_xop_vfrcz_ss);
497     return true;
498   }
499   if (Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
500     rename(F);
501     NewFn = Intrinsic::getDeclaration(F->getParent(),
502                                       Intrinsic::x86_xop_vfrcz_sd);
503     return true;
504   }
505   // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
506   if (Name.startswith("xop.vpermil2")) { // Added in 3.9
507     auto Idx = F->getFunctionType()->getParamType(2);
508     if (Idx->isFPOrFPVectorTy()) {
509       rename(F);
510       unsigned IdxSize = Idx->getPrimitiveSizeInBits();
511       unsigned EltSize = Idx->getScalarSizeInBits();
512       Intrinsic::ID Permil2ID;
513       if (EltSize == 64 && IdxSize == 128)
514         Permil2ID = Intrinsic::x86_xop_vpermil2pd;
515       else if (EltSize == 32 && IdxSize == 128)
516         Permil2ID = Intrinsic::x86_xop_vpermil2ps;
517       else if (EltSize == 64 && IdxSize == 256)
518         Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
519       else
520         Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
521       NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
522       return true;
523     }
524   }
525 
526   if (Name == "seh.recoverfp") {
527     NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::eh_recoverfp);
528     return true;
529   }
530 
531   return false;
532 }
533 
UpgradeIntrinsicFunction1(Function * F,Function * & NewFn)534 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
535   assert(F && "Illegal to upgrade a non-existent Function.");
536 
537   // Quickly eliminate it, if it's not a candidate.
538   StringRef Name = F->getName();
539   if (Name.size() <= 8 || !Name.startswith("llvm."))
540     return false;
541   Name = Name.substr(5); // Strip off "llvm."
542 
543   switch (Name[0]) {
544   default: break;
545   case 'a': {
546     if (Name.startswith("arm.rbit") || Name.startswith("aarch64.rbit")) {
547       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
548                                         F->arg_begin()->getType());
549       return true;
550     }
551     if (Name.startswith("arm.neon.vclz")) {
552       Type* args[2] = {
553         F->arg_begin()->getType(),
554         Type::getInt1Ty(F->getContext())
555       };
556       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
557       // the end of the name. Change name from llvm.arm.neon.vclz.* to
558       //  llvm.ctlz.*
559       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
560       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
561                                "llvm.ctlz." + Name.substr(14), F->getParent());
562       return true;
563     }
564     if (Name.startswith("arm.neon.vcnt")) {
565       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
566                                         F->arg_begin()->getType());
567       return true;
568     }
569     static const Regex vldRegex("^arm\\.neon\\.vld([1234]|[234]lane)\\.v[a-z0-9]*$");
570     if (vldRegex.match(Name)) {
571       auto fArgs = F->getFunctionType()->params();
572       SmallVector<Type *, 4> Tys(fArgs.begin(), fArgs.end());
573       // Can't use Intrinsic::getDeclaration here as the return types might
574       // then only be structurally equal.
575       FunctionType* fType = FunctionType::get(F->getReturnType(), Tys, false);
576       NewFn = Function::Create(fType, F->getLinkage(), F->getAddressSpace(),
577                                "llvm." + Name + ".p0i8", F->getParent());
578       return true;
579     }
580     static const Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
581     if (vstRegex.match(Name)) {
582       static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
583                                                 Intrinsic::arm_neon_vst2,
584                                                 Intrinsic::arm_neon_vst3,
585                                                 Intrinsic::arm_neon_vst4};
586 
587       static const Intrinsic::ID StoreLaneInts[] = {
588         Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
589         Intrinsic::arm_neon_vst4lane
590       };
591 
592       auto fArgs = F->getFunctionType()->params();
593       Type *Tys[] = {fArgs[0], fArgs[1]};
594       if (Name.find("lane") == StringRef::npos)
595         NewFn = Intrinsic::getDeclaration(F->getParent(),
596                                           StoreInts[fArgs.size() - 3], Tys);
597       else
598         NewFn = Intrinsic::getDeclaration(F->getParent(),
599                                           StoreLaneInts[fArgs.size() - 5], Tys);
600       return true;
601     }
602     if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
603       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
604       return true;
605     }
606     if (Name.startswith("arm.neon.vqadds.")) {
607       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::sadd_sat,
608                                         F->arg_begin()->getType());
609       return true;
610     }
611     if (Name.startswith("arm.neon.vqaddu.")) {
612       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::uadd_sat,
613                                         F->arg_begin()->getType());
614       return true;
615     }
616     if (Name.startswith("arm.neon.vqsubs.")) {
617       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ssub_sat,
618                                         F->arg_begin()->getType());
619       return true;
620     }
621     if (Name.startswith("arm.neon.vqsubu.")) {
622       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::usub_sat,
623                                         F->arg_begin()->getType());
624       return true;
625     }
626     if (Name.startswith("aarch64.neon.addp")) {
627       if (F->arg_size() != 2)
628         break; // Invalid IR.
629       VectorType *Ty = dyn_cast<VectorType>(F->getReturnType());
630       if (Ty && Ty->getElementType()->isFloatingPointTy()) {
631         NewFn = Intrinsic::getDeclaration(F->getParent(),
632                                           Intrinsic::aarch64_neon_faddp, Ty);
633         return true;
634       }
635     }
636 
637     // Changed in 12.0: bfdot accept v4bf16 and v8bf16 instead of v8i8 and v16i8
638     // respectively
639     if ((Name.startswith("arm.neon.bfdot.") ||
640          Name.startswith("aarch64.neon.bfdot.")) &&
641         Name.endswith("i8")) {
642       Intrinsic::ID IID =
643           StringSwitch<Intrinsic::ID>(Name)
644               .Cases("arm.neon.bfdot.v2f32.v8i8",
645                      "arm.neon.bfdot.v4f32.v16i8",
646                      Intrinsic::arm_neon_bfdot)
647               .Cases("aarch64.neon.bfdot.v2f32.v8i8",
648                      "aarch64.neon.bfdot.v4f32.v16i8",
649                      Intrinsic::aarch64_neon_bfdot)
650               .Default(Intrinsic::not_intrinsic);
651       if (IID == Intrinsic::not_intrinsic)
652         break;
653 
654       size_t OperandWidth = F->getReturnType()->getPrimitiveSizeInBits();
655       assert((OperandWidth == 64 || OperandWidth == 128) &&
656              "Unexpected operand width");
657       LLVMContext &Ctx = F->getParent()->getContext();
658       std::array<Type *, 2> Tys {{
659         F->getReturnType(),
660         FixedVectorType::get(Type::getBFloatTy(Ctx), OperandWidth / 16)
661       }};
662       NewFn = Intrinsic::getDeclaration(F->getParent(), IID, Tys);
663       return true;
664     }
665 
666     // Changed in 12.0: bfmmla, bfmlalb and bfmlalt are not polymorphic anymore
667     // and accept v8bf16 instead of v16i8
668     if ((Name.startswith("arm.neon.bfm") ||
669          Name.startswith("aarch64.neon.bfm")) &&
670         Name.endswith(".v4f32.v16i8")) {
671       Intrinsic::ID IID =
672           StringSwitch<Intrinsic::ID>(Name)
673               .Case("arm.neon.bfmmla.v4f32.v16i8",
674                     Intrinsic::arm_neon_bfmmla)
675               .Case("arm.neon.bfmlalb.v4f32.v16i8",
676                     Intrinsic::arm_neon_bfmlalb)
677               .Case("arm.neon.bfmlalt.v4f32.v16i8",
678                     Intrinsic::arm_neon_bfmlalt)
679               .Case("aarch64.neon.bfmmla.v4f32.v16i8",
680                     Intrinsic::aarch64_neon_bfmmla)
681               .Case("aarch64.neon.bfmlalb.v4f32.v16i8",
682                     Intrinsic::aarch64_neon_bfmlalb)
683               .Case("aarch64.neon.bfmlalt.v4f32.v16i8",
684                     Intrinsic::aarch64_neon_bfmlalt)
685               .Default(Intrinsic::not_intrinsic);
686       if (IID == Intrinsic::not_intrinsic)
687         break;
688 
689       std::array<Type *, 0> Tys;
690       NewFn = Intrinsic::getDeclaration(F->getParent(), IID, Tys);
691       return true;
692     }
693     break;
694   }
695 
696   case 'c': {
697     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
698       rename(F);
699       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
700                                         F->arg_begin()->getType());
701       return true;
702     }
703     if (Name.startswith("cttz.") && F->arg_size() == 1) {
704       rename(F);
705       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
706                                         F->arg_begin()->getType());
707       return true;
708     }
709     break;
710   }
711   case 'd': {
712     if (Name == "dbg.value" && F->arg_size() == 4) {
713       rename(F);
714       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
715       return true;
716     }
717     break;
718   }
719   case 'e': {
720     SmallVector<StringRef, 2> Groups;
721     static const Regex R("^experimental.vector.reduce.([a-z]+)\\.[a-z][0-9]+");
722     if (R.match(Name, &Groups)) {
723       Intrinsic::ID ID;
724       ID = StringSwitch<Intrinsic::ID>(Groups[1])
725                .Case("add", Intrinsic::vector_reduce_add)
726                .Case("mul", Intrinsic::vector_reduce_mul)
727                .Case("and", Intrinsic::vector_reduce_and)
728                .Case("or", Intrinsic::vector_reduce_or)
729                .Case("xor", Intrinsic::vector_reduce_xor)
730                .Case("smax", Intrinsic::vector_reduce_smax)
731                .Case("smin", Intrinsic::vector_reduce_smin)
732                .Case("umax", Intrinsic::vector_reduce_umax)
733                .Case("umin", Intrinsic::vector_reduce_umin)
734                .Case("fmax", Intrinsic::vector_reduce_fmax)
735                .Case("fmin", Intrinsic::vector_reduce_fmin)
736                .Default(Intrinsic::not_intrinsic);
737       if (ID != Intrinsic::not_intrinsic) {
738         rename(F);
739         auto Args = F->getFunctionType()->params();
740         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, {Args[0]});
741         return true;
742       }
743     }
744     static const Regex R2(
745         "^experimental.vector.reduce.v2.([a-z]+)\\.[fi][0-9]+");
746     Groups.clear();
747     if (R2.match(Name, &Groups)) {
748       Intrinsic::ID ID = Intrinsic::not_intrinsic;
749       if (Groups[1] == "fadd")
750         ID = Intrinsic::vector_reduce_fadd;
751       if (Groups[1] == "fmul")
752         ID = Intrinsic::vector_reduce_fmul;
753       if (ID != Intrinsic::not_intrinsic) {
754         rename(F);
755         auto Args = F->getFunctionType()->params();
756         Type *Tys[] = {Args[1]};
757         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, Tys);
758         return true;
759       }
760     }
761     break;
762   }
763   case 'i':
764   case 'l': {
765     bool IsLifetimeStart = Name.startswith("lifetime.start");
766     if (IsLifetimeStart || Name.startswith("invariant.start")) {
767       Intrinsic::ID ID = IsLifetimeStart ?
768         Intrinsic::lifetime_start : Intrinsic::invariant_start;
769       auto Args = F->getFunctionType()->params();
770       Type* ObjectPtr[1] = {Args[1]};
771       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
772         rename(F);
773         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
774         return true;
775       }
776     }
777 
778     bool IsLifetimeEnd = Name.startswith("lifetime.end");
779     if (IsLifetimeEnd || Name.startswith("invariant.end")) {
780       Intrinsic::ID ID = IsLifetimeEnd ?
781         Intrinsic::lifetime_end : Intrinsic::invariant_end;
782 
783       auto Args = F->getFunctionType()->params();
784       Type* ObjectPtr[1] = {Args[IsLifetimeEnd ? 1 : 2]};
785       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
786         rename(F);
787         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
788         return true;
789       }
790     }
791     if (Name.startswith("invariant.group.barrier")) {
792       // Rename invariant.group.barrier to launder.invariant.group
793       auto Args = F->getFunctionType()->params();
794       Type* ObjectPtr[1] = {Args[0]};
795       rename(F);
796       NewFn = Intrinsic::getDeclaration(F->getParent(),
797           Intrinsic::launder_invariant_group, ObjectPtr);
798       return true;
799 
800     }
801 
802     break;
803   }
804   case 'm': {
805     if (Name.startswith("masked.load.")) {
806       Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
807       if (F->getName() != Intrinsic::getName(Intrinsic::masked_load, Tys)) {
808         rename(F);
809         NewFn = Intrinsic::getDeclaration(F->getParent(),
810                                           Intrinsic::masked_load,
811                                           Tys);
812         return true;
813       }
814     }
815     if (Name.startswith("masked.store.")) {
816       auto Args = F->getFunctionType()->params();
817       Type *Tys[] = { Args[0], Args[1] };
818       if (F->getName() != Intrinsic::getName(Intrinsic::masked_store, Tys)) {
819         rename(F);
820         NewFn = Intrinsic::getDeclaration(F->getParent(),
821                                           Intrinsic::masked_store,
822                                           Tys);
823         return true;
824       }
825     }
826     // Renaming gather/scatter intrinsics with no address space overloading
827     // to the new overload which includes an address space
828     if (Name.startswith("masked.gather.")) {
829       Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
830       if (F->getName() != Intrinsic::getName(Intrinsic::masked_gather, Tys)) {
831         rename(F);
832         NewFn = Intrinsic::getDeclaration(F->getParent(),
833                                           Intrinsic::masked_gather, Tys);
834         return true;
835       }
836     }
837     if (Name.startswith("masked.scatter.")) {
838       auto Args = F->getFunctionType()->params();
839       Type *Tys[] = {Args[0], Args[1]};
840       if (F->getName() != Intrinsic::getName(Intrinsic::masked_scatter, Tys)) {
841         rename(F);
842         NewFn = Intrinsic::getDeclaration(F->getParent(),
843                                           Intrinsic::masked_scatter, Tys);
844         return true;
845       }
846     }
847     // Updating the memory intrinsics (memcpy/memmove/memset) that have an
848     // alignment parameter to embedding the alignment as an attribute of
849     // the pointer args.
850     if (Name.startswith("memcpy.") && F->arg_size() == 5) {
851       rename(F);
852       // Get the types of dest, src, and len
853       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
854       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memcpy,
855                                         ParamTypes);
856       return true;
857     }
858     if (Name.startswith("memmove.") && F->arg_size() == 5) {
859       rename(F);
860       // Get the types of dest, src, and len
861       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
862       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memmove,
863                                         ParamTypes);
864       return true;
865     }
866     if (Name.startswith("memset.") && F->arg_size() == 5) {
867       rename(F);
868       // Get the types of dest, and len
869       const auto *FT = F->getFunctionType();
870       Type *ParamTypes[2] = {
871           FT->getParamType(0), // Dest
872           FT->getParamType(2)  // len
873       };
874       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memset,
875                                         ParamTypes);
876       return true;
877     }
878     break;
879   }
880   case 'n': {
881     if (Name.startswith("nvvm.")) {
882       Name = Name.substr(5);
883 
884       // The following nvvm intrinsics correspond exactly to an LLVM intrinsic.
885       Intrinsic::ID IID = StringSwitch<Intrinsic::ID>(Name)
886                               .Cases("brev32", "brev64", Intrinsic::bitreverse)
887                               .Case("clz.i", Intrinsic::ctlz)
888                               .Case("popc.i", Intrinsic::ctpop)
889                               .Default(Intrinsic::not_intrinsic);
890       if (IID != Intrinsic::not_intrinsic && F->arg_size() == 1) {
891         NewFn = Intrinsic::getDeclaration(F->getParent(), IID,
892                                           {F->getReturnType()});
893         return true;
894       }
895 
896       // The following nvvm intrinsics correspond exactly to an LLVM idiom, but
897       // not to an intrinsic alone.  We expand them in UpgradeIntrinsicCall.
898       //
899       // TODO: We could add lohi.i2d.
900       bool Expand = StringSwitch<bool>(Name)
901                         .Cases("abs.i", "abs.ll", true)
902                         .Cases("clz.ll", "popc.ll", "h2f", true)
903                         .Cases("max.i", "max.ll", "max.ui", "max.ull", true)
904                         .Cases("min.i", "min.ll", "min.ui", "min.ull", true)
905                         .StartsWith("atomic.load.add.f32.p", true)
906                         .StartsWith("atomic.load.add.f64.p", true)
907                         .Default(false);
908       if (Expand) {
909         NewFn = nullptr;
910         return true;
911       }
912     }
913     break;
914   }
915   case 'o':
916     // We only need to change the name to match the mangling including the
917     // address space.
918     if (Name.startswith("objectsize.")) {
919       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
920       if (F->arg_size() == 2 || F->arg_size() == 3 ||
921           F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
922         rename(F);
923         NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::objectsize,
924                                           Tys);
925         return true;
926       }
927     }
928     break;
929 
930   case 'p':
931     if (Name == "prefetch") {
932       // Handle address space overloading.
933       Type *Tys[] = {F->arg_begin()->getType()};
934       if (F->getName() != Intrinsic::getName(Intrinsic::prefetch, Tys)) {
935         rename(F);
936         NewFn =
937             Intrinsic::getDeclaration(F->getParent(), Intrinsic::prefetch, Tys);
938         return true;
939       }
940     }
941     break;
942 
943   case 's':
944     if (Name == "stackprotectorcheck") {
945       NewFn = nullptr;
946       return true;
947     }
948     break;
949 
950   case 'x':
951     if (UpgradeX86IntrinsicFunction(F, Name, NewFn))
952       return true;
953   }
954   // Remangle our intrinsic since we upgrade the mangling
955   auto Result = llvm::Intrinsic::remangleIntrinsicFunction(F);
956   if (Result != None) {
957     NewFn = Result.getValue();
958     return true;
959   }
960 
961   //  This may not belong here. This function is effectively being overloaded
962   //  to both detect an intrinsic which needs upgrading, and to provide the
963   //  upgraded form of the intrinsic. We should perhaps have two separate
964   //  functions for this.
965   return false;
966 }
967 
UpgradeIntrinsicFunction(Function * F,Function * & NewFn)968 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
969   NewFn = nullptr;
970   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
971   assert(F != NewFn && "Intrinsic function upgraded to the same function");
972 
973   // Upgrade intrinsic attributes.  This does not change the function.
974   if (NewFn)
975     F = NewFn;
976   if (Intrinsic::ID id = F->getIntrinsicID())
977     F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
978   return Upgraded;
979 }
980 
UpgradeGlobalVariable(GlobalVariable * GV)981 GlobalVariable *llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
982   if (!(GV->hasName() && (GV->getName() == "llvm.global_ctors" ||
983                           GV->getName() == "llvm.global_dtors")) ||
984       !GV->hasInitializer())
985     return nullptr;
986   ArrayType *ATy = dyn_cast<ArrayType>(GV->getValueType());
987   if (!ATy)
988     return nullptr;
989   StructType *STy = dyn_cast<StructType>(ATy->getElementType());
990   if (!STy || STy->getNumElements() != 2)
991     return nullptr;
992 
993   LLVMContext &C = GV->getContext();
994   IRBuilder<> IRB(C);
995   auto EltTy = StructType::get(STy->getElementType(0), STy->getElementType(1),
996                                IRB.getInt8PtrTy());
997   Constant *Init = GV->getInitializer();
998   unsigned N = Init->getNumOperands();
999   std::vector<Constant *> NewCtors(N);
1000   for (unsigned i = 0; i != N; ++i) {
1001     auto Ctor = cast<Constant>(Init->getOperand(i));
1002     NewCtors[i] = ConstantStruct::get(
1003         EltTy, Ctor->getAggregateElement(0u), Ctor->getAggregateElement(1),
1004         Constant::getNullValue(IRB.getInt8PtrTy()));
1005   }
1006   Constant *NewInit = ConstantArray::get(ArrayType::get(EltTy, N), NewCtors);
1007 
1008   return new GlobalVariable(NewInit->getType(), false, GV->getLinkage(),
1009                             NewInit, GV->getName());
1010 }
1011 
1012 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
1013 // to byte shuffles.
UpgradeX86PSLLDQIntrinsics(IRBuilder<> & Builder,Value * Op,unsigned Shift)1014 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
1015                                          Value *Op, unsigned Shift) {
1016   auto *ResultTy = cast<FixedVectorType>(Op->getType());
1017   unsigned NumElts = ResultTy->getNumElements() * 8;
1018 
1019   // Bitcast from a 64-bit element type to a byte element type.
1020   Type *VecTy = FixedVectorType::get(Builder.getInt8Ty(), NumElts);
1021   Op = Builder.CreateBitCast(Op, VecTy, "cast");
1022 
1023   // We'll be shuffling in zeroes.
1024   Value *Res = Constant::getNullValue(VecTy);
1025 
1026   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
1027   // we'll just return the zero vector.
1028   if (Shift < 16) {
1029     int Idxs[64];
1030     // 256/512-bit version is split into 2/4 16-byte lanes.
1031     for (unsigned l = 0; l != NumElts; l += 16)
1032       for (unsigned i = 0; i != 16; ++i) {
1033         unsigned Idx = NumElts + i - Shift;
1034         if (Idx < NumElts)
1035           Idx -= NumElts - 16; // end of lane, switch operand.
1036         Idxs[l + i] = Idx + l;
1037       }
1038 
1039     Res = Builder.CreateShuffleVector(Res, Op, makeArrayRef(Idxs, NumElts));
1040   }
1041 
1042   // Bitcast back to a 64-bit element type.
1043   return Builder.CreateBitCast(Res, ResultTy, "cast");
1044 }
1045 
1046 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
1047 // to byte shuffles.
UpgradeX86PSRLDQIntrinsics(IRBuilder<> & Builder,Value * Op,unsigned Shift)1048 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
1049                                          unsigned Shift) {
1050   auto *ResultTy = cast<FixedVectorType>(Op->getType());
1051   unsigned NumElts = ResultTy->getNumElements() * 8;
1052 
1053   // Bitcast from a 64-bit element type to a byte element type.
1054   Type *VecTy = FixedVectorType::get(Builder.getInt8Ty(), NumElts);
1055   Op = Builder.CreateBitCast(Op, VecTy, "cast");
1056 
1057   // We'll be shuffling in zeroes.
1058   Value *Res = Constant::getNullValue(VecTy);
1059 
1060   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
1061   // we'll just return the zero vector.
1062   if (Shift < 16) {
1063     int Idxs[64];
1064     // 256/512-bit version is split into 2/4 16-byte lanes.
1065     for (unsigned l = 0; l != NumElts; l += 16)
1066       for (unsigned i = 0; i != 16; ++i) {
1067         unsigned Idx = i + Shift;
1068         if (Idx >= 16)
1069           Idx += NumElts - 16; // end of lane, switch operand.
1070         Idxs[l + i] = Idx + l;
1071       }
1072 
1073     Res = Builder.CreateShuffleVector(Op, Res, makeArrayRef(Idxs, NumElts));
1074   }
1075 
1076   // Bitcast back to a 64-bit element type.
1077   return Builder.CreateBitCast(Res, ResultTy, "cast");
1078 }
1079 
getX86MaskVec(IRBuilder<> & Builder,Value * Mask,unsigned NumElts)1080 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
1081                             unsigned NumElts) {
1082   assert(isPowerOf2_32(NumElts) && "Expected power-of-2 mask elements");
1083   llvm::VectorType *MaskTy = FixedVectorType::get(
1084       Builder.getInt1Ty(), cast<IntegerType>(Mask->getType())->getBitWidth());
1085   Mask = Builder.CreateBitCast(Mask, MaskTy);
1086 
1087   // If we have less than 8 elements (1, 2 or 4), then the starting mask was an
1088   // i8 and we need to extract down to the right number of elements.
1089   if (NumElts <= 4) {
1090     int Indices[4];
1091     for (unsigned i = 0; i != NumElts; ++i)
1092       Indices[i] = i;
1093     Mask = Builder.CreateShuffleVector(
1094         Mask, Mask, makeArrayRef(Indices, NumElts), "extract");
1095   }
1096 
1097   return Mask;
1098 }
1099 
EmitX86Select(IRBuilder<> & Builder,Value * Mask,Value * Op0,Value * Op1)1100 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
1101                             Value *Op0, Value *Op1) {
1102   // If the mask is all ones just emit the first operation.
1103   if (const auto *C = dyn_cast<Constant>(Mask))
1104     if (C->isAllOnesValue())
1105       return Op0;
1106 
1107   Mask = getX86MaskVec(Builder, Mask,
1108                        cast<FixedVectorType>(Op0->getType())->getNumElements());
1109   return Builder.CreateSelect(Mask, Op0, Op1);
1110 }
1111 
EmitX86ScalarSelect(IRBuilder<> & Builder,Value * Mask,Value * Op0,Value * Op1)1112 static Value *EmitX86ScalarSelect(IRBuilder<> &Builder, Value *Mask,
1113                                   Value *Op0, Value *Op1) {
1114   // If the mask is all ones just emit the first operation.
1115   if (const auto *C = dyn_cast<Constant>(Mask))
1116     if (C->isAllOnesValue())
1117       return Op0;
1118 
1119   auto *MaskTy = FixedVectorType::get(Builder.getInt1Ty(),
1120                                       Mask->getType()->getIntegerBitWidth());
1121   Mask = Builder.CreateBitCast(Mask, MaskTy);
1122   Mask = Builder.CreateExtractElement(Mask, (uint64_t)0);
1123   return Builder.CreateSelect(Mask, Op0, Op1);
1124 }
1125 
1126 // Handle autoupgrade for masked PALIGNR and VALIGND/Q intrinsics.
1127 // PALIGNR handles large immediates by shifting while VALIGN masks the immediate
1128 // so we need to handle both cases. VALIGN also doesn't have 128-bit lanes.
UpgradeX86ALIGNIntrinsics(IRBuilder<> & Builder,Value * Op0,Value * Op1,Value * Shift,Value * Passthru,Value * Mask,bool IsVALIGN)1129 static Value *UpgradeX86ALIGNIntrinsics(IRBuilder<> &Builder, Value *Op0,
1130                                         Value *Op1, Value *Shift,
1131                                         Value *Passthru, Value *Mask,
1132                                         bool IsVALIGN) {
1133   unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
1134 
1135   unsigned NumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
1136   assert((IsVALIGN || NumElts % 16 == 0) && "Illegal NumElts for PALIGNR!");
1137   assert((!IsVALIGN || NumElts <= 16) && "NumElts too large for VALIGN!");
1138   assert(isPowerOf2_32(NumElts) && "NumElts not a power of 2!");
1139 
1140   // Mask the immediate for VALIGN.
1141   if (IsVALIGN)
1142     ShiftVal &= (NumElts - 1);
1143 
1144   // If palignr is shifting the pair of vectors more than the size of two
1145   // lanes, emit zero.
1146   if (ShiftVal >= 32)
1147     return llvm::Constant::getNullValue(Op0->getType());
1148 
1149   // If palignr is shifting the pair of input vectors more than one lane,
1150   // but less than two lanes, convert to shifting in zeroes.
1151   if (ShiftVal > 16) {
1152     ShiftVal -= 16;
1153     Op1 = Op0;
1154     Op0 = llvm::Constant::getNullValue(Op0->getType());
1155   }
1156 
1157   int Indices[64];
1158   // 256-bit palignr operates on 128-bit lanes so we need to handle that
1159   for (unsigned l = 0; l < NumElts; l += 16) {
1160     for (unsigned i = 0; i != 16; ++i) {
1161       unsigned Idx = ShiftVal + i;
1162       if (!IsVALIGN && Idx >= 16) // Disable wrap for VALIGN.
1163         Idx += NumElts - 16; // End of lane, switch operand.
1164       Indices[l + i] = Idx + l;
1165     }
1166   }
1167 
1168   Value *Align = Builder.CreateShuffleVector(Op1, Op0,
1169                                              makeArrayRef(Indices, NumElts),
1170                                              "palignr");
1171 
1172   return EmitX86Select(Builder, Mask, Align, Passthru);
1173 }
1174 
UpgradeX86VPERMT2Intrinsics(IRBuilder<> & Builder,CallInst & CI,bool ZeroMask,bool IndexForm)1175 static Value *UpgradeX86VPERMT2Intrinsics(IRBuilder<> &Builder, CallInst &CI,
1176                                           bool ZeroMask, bool IndexForm) {
1177   Type *Ty = CI.getType();
1178   unsigned VecWidth = Ty->getPrimitiveSizeInBits();
1179   unsigned EltWidth = Ty->getScalarSizeInBits();
1180   bool IsFloat = Ty->isFPOrFPVectorTy();
1181   Intrinsic::ID IID;
1182   if (VecWidth == 128 && EltWidth == 32 && IsFloat)
1183     IID = Intrinsic::x86_avx512_vpermi2var_ps_128;
1184   else if (VecWidth == 128 && EltWidth == 32 && !IsFloat)
1185     IID = Intrinsic::x86_avx512_vpermi2var_d_128;
1186   else if (VecWidth == 128 && EltWidth == 64 && IsFloat)
1187     IID = Intrinsic::x86_avx512_vpermi2var_pd_128;
1188   else if (VecWidth == 128 && EltWidth == 64 && !IsFloat)
1189     IID = Intrinsic::x86_avx512_vpermi2var_q_128;
1190   else if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1191     IID = Intrinsic::x86_avx512_vpermi2var_ps_256;
1192   else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1193     IID = Intrinsic::x86_avx512_vpermi2var_d_256;
1194   else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1195     IID = Intrinsic::x86_avx512_vpermi2var_pd_256;
1196   else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1197     IID = Intrinsic::x86_avx512_vpermi2var_q_256;
1198   else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1199     IID = Intrinsic::x86_avx512_vpermi2var_ps_512;
1200   else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1201     IID = Intrinsic::x86_avx512_vpermi2var_d_512;
1202   else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1203     IID = Intrinsic::x86_avx512_vpermi2var_pd_512;
1204   else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1205     IID = Intrinsic::x86_avx512_vpermi2var_q_512;
1206   else if (VecWidth == 128 && EltWidth == 16)
1207     IID = Intrinsic::x86_avx512_vpermi2var_hi_128;
1208   else if (VecWidth == 256 && EltWidth == 16)
1209     IID = Intrinsic::x86_avx512_vpermi2var_hi_256;
1210   else if (VecWidth == 512 && EltWidth == 16)
1211     IID = Intrinsic::x86_avx512_vpermi2var_hi_512;
1212   else if (VecWidth == 128 && EltWidth == 8)
1213     IID = Intrinsic::x86_avx512_vpermi2var_qi_128;
1214   else if (VecWidth == 256 && EltWidth == 8)
1215     IID = Intrinsic::x86_avx512_vpermi2var_qi_256;
1216   else if (VecWidth == 512 && EltWidth == 8)
1217     IID = Intrinsic::x86_avx512_vpermi2var_qi_512;
1218   else
1219     llvm_unreachable("Unexpected intrinsic");
1220 
1221   Value *Args[] = { CI.getArgOperand(0) , CI.getArgOperand(1),
1222                     CI.getArgOperand(2) };
1223 
1224   // If this isn't index form we need to swap operand 0 and 1.
1225   if (!IndexForm)
1226     std::swap(Args[0], Args[1]);
1227 
1228   Value *V = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1229                                 Args);
1230   Value *PassThru = ZeroMask ? ConstantAggregateZero::get(Ty)
1231                              : Builder.CreateBitCast(CI.getArgOperand(1),
1232                                                      Ty);
1233   return EmitX86Select(Builder, CI.getArgOperand(3), V, PassThru);
1234 }
1235 
UpgradeX86BinaryIntrinsics(IRBuilder<> & Builder,CallInst & CI,Intrinsic::ID IID)1236 static Value *UpgradeX86BinaryIntrinsics(IRBuilder<> &Builder, CallInst &CI,
1237                                          Intrinsic::ID IID) {
1238   Type *Ty = CI.getType();
1239   Value *Op0 = CI.getOperand(0);
1240   Value *Op1 = CI.getOperand(1);
1241   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1242   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1});
1243 
1244   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1245     Value *VecSrc = CI.getOperand(2);
1246     Value *Mask = CI.getOperand(3);
1247     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1248   }
1249   return Res;
1250 }
1251 
upgradeX86Rotate(IRBuilder<> & Builder,CallInst & CI,bool IsRotateRight)1252 static Value *upgradeX86Rotate(IRBuilder<> &Builder, CallInst &CI,
1253                                bool IsRotateRight) {
1254   Type *Ty = CI.getType();
1255   Value *Src = CI.getArgOperand(0);
1256   Value *Amt = CI.getArgOperand(1);
1257 
1258   // Amount may be scalar immediate, in which case create a splat vector.
1259   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1260   // we only care about the lowest log2 bits anyway.
1261   if (Amt->getType() != Ty) {
1262     unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1263     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1264     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1265   }
1266 
1267   Intrinsic::ID IID = IsRotateRight ? Intrinsic::fshr : Intrinsic::fshl;
1268   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1269   Value *Res = Builder.CreateCall(Intrin, {Src, Src, Amt});
1270 
1271   if (CI.getNumArgOperands() == 4) { // For masked intrinsics.
1272     Value *VecSrc = CI.getOperand(2);
1273     Value *Mask = CI.getOperand(3);
1274     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1275   }
1276   return Res;
1277 }
1278 
upgradeX86vpcom(IRBuilder<> & Builder,CallInst & CI,unsigned Imm,bool IsSigned)1279 static Value *upgradeX86vpcom(IRBuilder<> &Builder, CallInst &CI, unsigned Imm,
1280                               bool IsSigned) {
1281   Type *Ty = CI.getType();
1282   Value *LHS = CI.getArgOperand(0);
1283   Value *RHS = CI.getArgOperand(1);
1284 
1285   CmpInst::Predicate Pred;
1286   switch (Imm) {
1287   case 0x0:
1288     Pred = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
1289     break;
1290   case 0x1:
1291     Pred = IsSigned ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE;
1292     break;
1293   case 0x2:
1294     Pred = IsSigned ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT;
1295     break;
1296   case 0x3:
1297     Pred = IsSigned ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE;
1298     break;
1299   case 0x4:
1300     Pred = ICmpInst::ICMP_EQ;
1301     break;
1302   case 0x5:
1303     Pred = ICmpInst::ICMP_NE;
1304     break;
1305   case 0x6:
1306     return Constant::getNullValue(Ty); // FALSE
1307   case 0x7:
1308     return Constant::getAllOnesValue(Ty); // TRUE
1309   default:
1310     llvm_unreachable("Unknown XOP vpcom/vpcomu predicate");
1311   }
1312 
1313   Value *Cmp = Builder.CreateICmp(Pred, LHS, RHS);
1314   Value *Ext = Builder.CreateSExt(Cmp, Ty);
1315   return Ext;
1316 }
1317 
upgradeX86ConcatShift(IRBuilder<> & Builder,CallInst & CI,bool IsShiftRight,bool ZeroMask)1318 static Value *upgradeX86ConcatShift(IRBuilder<> &Builder, CallInst &CI,
1319                                     bool IsShiftRight, bool ZeroMask) {
1320   Type *Ty = CI.getType();
1321   Value *Op0 = CI.getArgOperand(0);
1322   Value *Op1 = CI.getArgOperand(1);
1323   Value *Amt = CI.getArgOperand(2);
1324 
1325   if (IsShiftRight)
1326     std::swap(Op0, Op1);
1327 
1328   // Amount may be scalar immediate, in which case create a splat vector.
1329   // Funnel shifts amounts are treated as modulo and types are all power-of-2 so
1330   // we only care about the lowest log2 bits anyway.
1331   if (Amt->getType() != Ty) {
1332     unsigned NumElts = cast<FixedVectorType>(Ty)->getNumElements();
1333     Amt = Builder.CreateIntCast(Amt, Ty->getScalarType(), false);
1334     Amt = Builder.CreateVectorSplat(NumElts, Amt);
1335   }
1336 
1337   Intrinsic::ID IID = IsShiftRight ? Intrinsic::fshr : Intrinsic::fshl;
1338   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID, Ty);
1339   Value *Res = Builder.CreateCall(Intrin, {Op0, Op1, Amt});
1340 
1341   unsigned NumArgs = CI.getNumArgOperands();
1342   if (NumArgs >= 4) { // For masked intrinsics.
1343     Value *VecSrc = NumArgs == 5 ? CI.getArgOperand(3) :
1344                     ZeroMask     ? ConstantAggregateZero::get(CI.getType()) :
1345                                    CI.getArgOperand(0);
1346     Value *Mask = CI.getOperand(NumArgs - 1);
1347     Res = EmitX86Select(Builder, Mask, Res, VecSrc);
1348   }
1349   return Res;
1350 }
1351 
UpgradeMaskedStore(IRBuilder<> & Builder,Value * Ptr,Value * Data,Value * Mask,bool Aligned)1352 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
1353                                  Value *Ptr, Value *Data, Value *Mask,
1354                                  bool Aligned) {
1355   // Cast the pointer to the right type.
1356   Ptr = Builder.CreateBitCast(Ptr,
1357                               llvm::PointerType::getUnqual(Data->getType()));
1358   const Align Alignment =
1359       Aligned
1360           ? Align(Data->getType()->getPrimitiveSizeInBits().getFixedSize() / 8)
1361           : Align(1);
1362 
1363   // If the mask is all ones just emit a regular store.
1364   if (const auto *C = dyn_cast<Constant>(Mask))
1365     if (C->isAllOnesValue())
1366       return Builder.CreateAlignedStore(Data, Ptr, Alignment);
1367 
1368   // Convert the mask from an integer type to a vector of i1.
1369   unsigned NumElts = cast<FixedVectorType>(Data->getType())->getNumElements();
1370   Mask = getX86MaskVec(Builder, Mask, NumElts);
1371   return Builder.CreateMaskedStore(Data, Ptr, Alignment, Mask);
1372 }
1373 
UpgradeMaskedLoad(IRBuilder<> & Builder,Value * Ptr,Value * Passthru,Value * Mask,bool Aligned)1374 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
1375                                 Value *Ptr, Value *Passthru, Value *Mask,
1376                                 bool Aligned) {
1377   Type *ValTy = Passthru->getType();
1378   // Cast the pointer to the right type.
1379   Ptr = Builder.CreateBitCast(Ptr, llvm::PointerType::getUnqual(ValTy));
1380   const Align Alignment =
1381       Aligned
1382           ? Align(Passthru->getType()->getPrimitiveSizeInBits().getFixedSize() /
1383                   8)
1384           : Align(1);
1385 
1386   // If the mask is all ones just emit a regular store.
1387   if (const auto *C = dyn_cast<Constant>(Mask))
1388     if (C->isAllOnesValue())
1389       return Builder.CreateAlignedLoad(ValTy, Ptr, Alignment);
1390 
1391   // Convert the mask from an integer type to a vector of i1.
1392   unsigned NumElts =
1393       cast<FixedVectorType>(Passthru->getType())->getNumElements();
1394   Mask = getX86MaskVec(Builder, Mask, NumElts);
1395   return Builder.CreateMaskedLoad(Ptr, Alignment, Mask, Passthru);
1396 }
1397 
upgradeAbs(IRBuilder<> & Builder,CallInst & CI)1398 static Value *upgradeAbs(IRBuilder<> &Builder, CallInst &CI) {
1399   Type *Ty = CI.getType();
1400   Value *Op0 = CI.getArgOperand(0);
1401   Function *F = Intrinsic::getDeclaration(CI.getModule(), Intrinsic::abs, Ty);
1402   Value *Res = Builder.CreateCall(F, {Op0, Builder.getInt1(false)});
1403   if (CI.getNumArgOperands() == 3)
1404     Res = EmitX86Select(Builder, CI.getArgOperand(2), Res, CI.getArgOperand(1));
1405   return Res;
1406 }
1407 
upgradePMULDQ(IRBuilder<> & Builder,CallInst & CI,bool IsSigned)1408 static Value *upgradePMULDQ(IRBuilder<> &Builder, CallInst &CI, bool IsSigned) {
1409   Type *Ty = CI.getType();
1410 
1411   // Arguments have a vXi32 type so cast to vXi64.
1412   Value *LHS = Builder.CreateBitCast(CI.getArgOperand(0), Ty);
1413   Value *RHS = Builder.CreateBitCast(CI.getArgOperand(1), Ty);
1414 
1415   if (IsSigned) {
1416     // Shift left then arithmetic shift right.
1417     Constant *ShiftAmt = ConstantInt::get(Ty, 32);
1418     LHS = Builder.CreateShl(LHS, ShiftAmt);
1419     LHS = Builder.CreateAShr(LHS, ShiftAmt);
1420     RHS = Builder.CreateShl(RHS, ShiftAmt);
1421     RHS = Builder.CreateAShr(RHS, ShiftAmt);
1422   } else {
1423     // Clear the upper bits.
1424     Constant *Mask = ConstantInt::get(Ty, 0xffffffff);
1425     LHS = Builder.CreateAnd(LHS, Mask);
1426     RHS = Builder.CreateAnd(RHS, Mask);
1427   }
1428 
1429   Value *Res = Builder.CreateMul(LHS, RHS);
1430 
1431   if (CI.getNumArgOperands() == 4)
1432     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
1433 
1434   return Res;
1435 }
1436 
1437 // Applying mask on vector of i1's and make sure result is at least 8 bits wide.
ApplyX86MaskOn1BitsVec(IRBuilder<> & Builder,Value * Vec,Value * Mask)1438 static Value *ApplyX86MaskOn1BitsVec(IRBuilder<> &Builder, Value *Vec,
1439                                      Value *Mask) {
1440   unsigned NumElts = cast<FixedVectorType>(Vec->getType())->getNumElements();
1441   if (Mask) {
1442     const auto *C = dyn_cast<Constant>(Mask);
1443     if (!C || !C->isAllOnesValue())
1444       Vec = Builder.CreateAnd(Vec, getX86MaskVec(Builder, Mask, NumElts));
1445   }
1446 
1447   if (NumElts < 8) {
1448     int Indices[8];
1449     for (unsigned i = 0; i != NumElts; ++i)
1450       Indices[i] = i;
1451     for (unsigned i = NumElts; i != 8; ++i)
1452       Indices[i] = NumElts + i % NumElts;
1453     Vec = Builder.CreateShuffleVector(Vec,
1454                                       Constant::getNullValue(Vec->getType()),
1455                                       Indices);
1456   }
1457   return Builder.CreateBitCast(Vec, Builder.getIntNTy(std::max(NumElts, 8U)));
1458 }
1459 
upgradeMaskedCompare(IRBuilder<> & Builder,CallInst & CI,unsigned CC,bool Signed)1460 static Value *upgradeMaskedCompare(IRBuilder<> &Builder, CallInst &CI,
1461                                    unsigned CC, bool Signed) {
1462   Value *Op0 = CI.getArgOperand(0);
1463   unsigned NumElts = cast<FixedVectorType>(Op0->getType())->getNumElements();
1464 
1465   Value *Cmp;
1466   if (CC == 3) {
1467     Cmp = Constant::getNullValue(
1468         FixedVectorType::get(Builder.getInt1Ty(), NumElts));
1469   } else if (CC == 7) {
1470     Cmp = Constant::getAllOnesValue(
1471         FixedVectorType::get(Builder.getInt1Ty(), NumElts));
1472   } else {
1473     ICmpInst::Predicate Pred;
1474     switch (CC) {
1475     default: llvm_unreachable("Unknown condition code");
1476     case 0: Pred = ICmpInst::ICMP_EQ;  break;
1477     case 1: Pred = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
1478     case 2: Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
1479     case 4: Pred = ICmpInst::ICMP_NE;  break;
1480     case 5: Pred = Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
1481     case 6: Pred = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
1482     }
1483     Cmp = Builder.CreateICmp(Pred, Op0, CI.getArgOperand(1));
1484   }
1485 
1486   Value *Mask = CI.getArgOperand(CI.getNumArgOperands() - 1);
1487 
1488   return ApplyX86MaskOn1BitsVec(Builder, Cmp, Mask);
1489 }
1490 
1491 // Replace a masked intrinsic with an older unmasked intrinsic.
UpgradeX86MaskedShift(IRBuilder<> & Builder,CallInst & CI,Intrinsic::ID IID)1492 static Value *UpgradeX86MaskedShift(IRBuilder<> &Builder, CallInst &CI,
1493                                     Intrinsic::ID IID) {
1494   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID);
1495   Value *Rep = Builder.CreateCall(Intrin,
1496                                  { CI.getArgOperand(0), CI.getArgOperand(1) });
1497   return EmitX86Select(Builder, CI.getArgOperand(3), Rep, CI.getArgOperand(2));
1498 }
1499 
upgradeMaskedMove(IRBuilder<> & Builder,CallInst & CI)1500 static Value* upgradeMaskedMove(IRBuilder<> &Builder, CallInst &CI) {
1501   Value* A = CI.getArgOperand(0);
1502   Value* B = CI.getArgOperand(1);
1503   Value* Src = CI.getArgOperand(2);
1504   Value* Mask = CI.getArgOperand(3);
1505 
1506   Value* AndNode = Builder.CreateAnd(Mask, APInt(8, 1));
1507   Value* Cmp = Builder.CreateIsNotNull(AndNode);
1508   Value* Extract1 = Builder.CreateExtractElement(B, (uint64_t)0);
1509   Value* Extract2 = Builder.CreateExtractElement(Src, (uint64_t)0);
1510   Value* Select = Builder.CreateSelect(Cmp, Extract1, Extract2);
1511   return Builder.CreateInsertElement(A, Select, (uint64_t)0);
1512 }
1513 
1514 
UpgradeMaskToInt(IRBuilder<> & Builder,CallInst & CI)1515 static Value* UpgradeMaskToInt(IRBuilder<> &Builder, CallInst &CI) {
1516   Value* Op = CI.getArgOperand(0);
1517   Type* ReturnOp = CI.getType();
1518   unsigned NumElts = cast<FixedVectorType>(CI.getType())->getNumElements();
1519   Value *Mask = getX86MaskVec(Builder, Op, NumElts);
1520   return Builder.CreateSExt(Mask, ReturnOp, "vpmovm2");
1521 }
1522 
1523 // Replace intrinsic with unmasked version and a select.
upgradeAVX512MaskToSelect(StringRef Name,IRBuilder<> & Builder,CallInst & CI,Value * & Rep)1524 static bool upgradeAVX512MaskToSelect(StringRef Name, IRBuilder<> &Builder,
1525                                       CallInst &CI, Value *&Rep) {
1526   Name = Name.substr(12); // Remove avx512.mask.
1527 
1528   unsigned VecWidth = CI.getType()->getPrimitiveSizeInBits();
1529   unsigned EltWidth = CI.getType()->getScalarSizeInBits();
1530   Intrinsic::ID IID;
1531   if (Name.startswith("max.p")) {
1532     if (VecWidth == 128 && EltWidth == 32)
1533       IID = Intrinsic::x86_sse_max_ps;
1534     else if (VecWidth == 128 && EltWidth == 64)
1535       IID = Intrinsic::x86_sse2_max_pd;
1536     else if (VecWidth == 256 && EltWidth == 32)
1537       IID = Intrinsic::x86_avx_max_ps_256;
1538     else if (VecWidth == 256 && EltWidth == 64)
1539       IID = Intrinsic::x86_avx_max_pd_256;
1540     else
1541       llvm_unreachable("Unexpected intrinsic");
1542   } else if (Name.startswith("min.p")) {
1543     if (VecWidth == 128 && EltWidth == 32)
1544       IID = Intrinsic::x86_sse_min_ps;
1545     else if (VecWidth == 128 && EltWidth == 64)
1546       IID = Intrinsic::x86_sse2_min_pd;
1547     else if (VecWidth == 256 && EltWidth == 32)
1548       IID = Intrinsic::x86_avx_min_ps_256;
1549     else if (VecWidth == 256 && EltWidth == 64)
1550       IID = Intrinsic::x86_avx_min_pd_256;
1551     else
1552       llvm_unreachable("Unexpected intrinsic");
1553   } else if (Name.startswith("pshuf.b.")) {
1554     if (VecWidth == 128)
1555       IID = Intrinsic::x86_ssse3_pshuf_b_128;
1556     else if (VecWidth == 256)
1557       IID = Intrinsic::x86_avx2_pshuf_b;
1558     else if (VecWidth == 512)
1559       IID = Intrinsic::x86_avx512_pshuf_b_512;
1560     else
1561       llvm_unreachable("Unexpected intrinsic");
1562   } else if (Name.startswith("pmul.hr.sw.")) {
1563     if (VecWidth == 128)
1564       IID = Intrinsic::x86_ssse3_pmul_hr_sw_128;
1565     else if (VecWidth == 256)
1566       IID = Intrinsic::x86_avx2_pmul_hr_sw;
1567     else if (VecWidth == 512)
1568       IID = Intrinsic::x86_avx512_pmul_hr_sw_512;
1569     else
1570       llvm_unreachable("Unexpected intrinsic");
1571   } else if (Name.startswith("pmulh.w.")) {
1572     if (VecWidth == 128)
1573       IID = Intrinsic::x86_sse2_pmulh_w;
1574     else if (VecWidth == 256)
1575       IID = Intrinsic::x86_avx2_pmulh_w;
1576     else if (VecWidth == 512)
1577       IID = Intrinsic::x86_avx512_pmulh_w_512;
1578     else
1579       llvm_unreachable("Unexpected intrinsic");
1580   } else if (Name.startswith("pmulhu.w.")) {
1581     if (VecWidth == 128)
1582       IID = Intrinsic::x86_sse2_pmulhu_w;
1583     else if (VecWidth == 256)
1584       IID = Intrinsic::x86_avx2_pmulhu_w;
1585     else if (VecWidth == 512)
1586       IID = Intrinsic::x86_avx512_pmulhu_w_512;
1587     else
1588       llvm_unreachable("Unexpected intrinsic");
1589   } else if (Name.startswith("pmaddw.d.")) {
1590     if (VecWidth == 128)
1591       IID = Intrinsic::x86_sse2_pmadd_wd;
1592     else if (VecWidth == 256)
1593       IID = Intrinsic::x86_avx2_pmadd_wd;
1594     else if (VecWidth == 512)
1595       IID = Intrinsic::x86_avx512_pmaddw_d_512;
1596     else
1597       llvm_unreachable("Unexpected intrinsic");
1598   } else if (Name.startswith("pmaddubs.w.")) {
1599     if (VecWidth == 128)
1600       IID = Intrinsic::x86_ssse3_pmadd_ub_sw_128;
1601     else if (VecWidth == 256)
1602       IID = Intrinsic::x86_avx2_pmadd_ub_sw;
1603     else if (VecWidth == 512)
1604       IID = Intrinsic::x86_avx512_pmaddubs_w_512;
1605     else
1606       llvm_unreachable("Unexpected intrinsic");
1607   } else if (Name.startswith("packsswb.")) {
1608     if (VecWidth == 128)
1609       IID = Intrinsic::x86_sse2_packsswb_128;
1610     else if (VecWidth == 256)
1611       IID = Intrinsic::x86_avx2_packsswb;
1612     else if (VecWidth == 512)
1613       IID = Intrinsic::x86_avx512_packsswb_512;
1614     else
1615       llvm_unreachable("Unexpected intrinsic");
1616   } else if (Name.startswith("packssdw.")) {
1617     if (VecWidth == 128)
1618       IID = Intrinsic::x86_sse2_packssdw_128;
1619     else if (VecWidth == 256)
1620       IID = Intrinsic::x86_avx2_packssdw;
1621     else if (VecWidth == 512)
1622       IID = Intrinsic::x86_avx512_packssdw_512;
1623     else
1624       llvm_unreachable("Unexpected intrinsic");
1625   } else if (Name.startswith("packuswb.")) {
1626     if (VecWidth == 128)
1627       IID = Intrinsic::x86_sse2_packuswb_128;
1628     else if (VecWidth == 256)
1629       IID = Intrinsic::x86_avx2_packuswb;
1630     else if (VecWidth == 512)
1631       IID = Intrinsic::x86_avx512_packuswb_512;
1632     else
1633       llvm_unreachable("Unexpected intrinsic");
1634   } else if (Name.startswith("packusdw.")) {
1635     if (VecWidth == 128)
1636       IID = Intrinsic::x86_sse41_packusdw;
1637     else if (VecWidth == 256)
1638       IID = Intrinsic::x86_avx2_packusdw;
1639     else if (VecWidth == 512)
1640       IID = Intrinsic::x86_avx512_packusdw_512;
1641     else
1642       llvm_unreachable("Unexpected intrinsic");
1643   } else if (Name.startswith("vpermilvar.")) {
1644     if (VecWidth == 128 && EltWidth == 32)
1645       IID = Intrinsic::x86_avx_vpermilvar_ps;
1646     else if (VecWidth == 128 && EltWidth == 64)
1647       IID = Intrinsic::x86_avx_vpermilvar_pd;
1648     else if (VecWidth == 256 && EltWidth == 32)
1649       IID = Intrinsic::x86_avx_vpermilvar_ps_256;
1650     else if (VecWidth == 256 && EltWidth == 64)
1651       IID = Intrinsic::x86_avx_vpermilvar_pd_256;
1652     else if (VecWidth == 512 && EltWidth == 32)
1653       IID = Intrinsic::x86_avx512_vpermilvar_ps_512;
1654     else if (VecWidth == 512 && EltWidth == 64)
1655       IID = Intrinsic::x86_avx512_vpermilvar_pd_512;
1656     else
1657       llvm_unreachable("Unexpected intrinsic");
1658   } else if (Name == "cvtpd2dq.256") {
1659     IID = Intrinsic::x86_avx_cvt_pd2dq_256;
1660   } else if (Name == "cvtpd2ps.256") {
1661     IID = Intrinsic::x86_avx_cvt_pd2_ps_256;
1662   } else if (Name == "cvttpd2dq.256") {
1663     IID = Intrinsic::x86_avx_cvtt_pd2dq_256;
1664   } else if (Name == "cvttps2dq.128") {
1665     IID = Intrinsic::x86_sse2_cvttps2dq;
1666   } else if (Name == "cvttps2dq.256") {
1667     IID = Intrinsic::x86_avx_cvtt_ps2dq_256;
1668   } else if (Name.startswith("permvar.")) {
1669     bool IsFloat = CI.getType()->isFPOrFPVectorTy();
1670     if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1671       IID = Intrinsic::x86_avx2_permps;
1672     else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1673       IID = Intrinsic::x86_avx2_permd;
1674     else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1675       IID = Intrinsic::x86_avx512_permvar_df_256;
1676     else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1677       IID = Intrinsic::x86_avx512_permvar_di_256;
1678     else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1679       IID = Intrinsic::x86_avx512_permvar_sf_512;
1680     else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1681       IID = Intrinsic::x86_avx512_permvar_si_512;
1682     else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1683       IID = Intrinsic::x86_avx512_permvar_df_512;
1684     else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1685       IID = Intrinsic::x86_avx512_permvar_di_512;
1686     else if (VecWidth == 128 && EltWidth == 16)
1687       IID = Intrinsic::x86_avx512_permvar_hi_128;
1688     else if (VecWidth == 256 && EltWidth == 16)
1689       IID = Intrinsic::x86_avx512_permvar_hi_256;
1690     else if (VecWidth == 512 && EltWidth == 16)
1691       IID = Intrinsic::x86_avx512_permvar_hi_512;
1692     else if (VecWidth == 128 && EltWidth == 8)
1693       IID = Intrinsic::x86_avx512_permvar_qi_128;
1694     else if (VecWidth == 256 && EltWidth == 8)
1695       IID = Intrinsic::x86_avx512_permvar_qi_256;
1696     else if (VecWidth == 512 && EltWidth == 8)
1697       IID = Intrinsic::x86_avx512_permvar_qi_512;
1698     else
1699       llvm_unreachable("Unexpected intrinsic");
1700   } else if (Name.startswith("dbpsadbw.")) {
1701     if (VecWidth == 128)
1702       IID = Intrinsic::x86_avx512_dbpsadbw_128;
1703     else if (VecWidth == 256)
1704       IID = Intrinsic::x86_avx512_dbpsadbw_256;
1705     else if (VecWidth == 512)
1706       IID = Intrinsic::x86_avx512_dbpsadbw_512;
1707     else
1708       llvm_unreachable("Unexpected intrinsic");
1709   } else if (Name.startswith("pmultishift.qb.")) {
1710     if (VecWidth == 128)
1711       IID = Intrinsic::x86_avx512_pmultishift_qb_128;
1712     else if (VecWidth == 256)
1713       IID = Intrinsic::x86_avx512_pmultishift_qb_256;
1714     else if (VecWidth == 512)
1715       IID = Intrinsic::x86_avx512_pmultishift_qb_512;
1716     else
1717       llvm_unreachable("Unexpected intrinsic");
1718   } else if (Name.startswith("conflict.")) {
1719     if (Name[9] == 'd' && VecWidth == 128)
1720       IID = Intrinsic::x86_avx512_conflict_d_128;
1721     else if (Name[9] == 'd' && VecWidth == 256)
1722       IID = Intrinsic::x86_avx512_conflict_d_256;
1723     else if (Name[9] == 'd' && VecWidth == 512)
1724       IID = Intrinsic::x86_avx512_conflict_d_512;
1725     else if (Name[9] == 'q' && VecWidth == 128)
1726       IID = Intrinsic::x86_avx512_conflict_q_128;
1727     else if (Name[9] == 'q' && VecWidth == 256)
1728       IID = Intrinsic::x86_avx512_conflict_q_256;
1729     else if (Name[9] == 'q' && VecWidth == 512)
1730       IID = Intrinsic::x86_avx512_conflict_q_512;
1731     else
1732       llvm_unreachable("Unexpected intrinsic");
1733   } else if (Name.startswith("pavg.")) {
1734     if (Name[5] == 'b' && VecWidth == 128)
1735       IID = Intrinsic::x86_sse2_pavg_b;
1736     else if (Name[5] == 'b' && VecWidth == 256)
1737       IID = Intrinsic::x86_avx2_pavg_b;
1738     else if (Name[5] == 'b' && VecWidth == 512)
1739       IID = Intrinsic::x86_avx512_pavg_b_512;
1740     else if (Name[5] == 'w' && VecWidth == 128)
1741       IID = Intrinsic::x86_sse2_pavg_w;
1742     else if (Name[5] == 'w' && VecWidth == 256)
1743       IID = Intrinsic::x86_avx2_pavg_w;
1744     else if (Name[5] == 'w' && VecWidth == 512)
1745       IID = Intrinsic::x86_avx512_pavg_w_512;
1746     else
1747       llvm_unreachable("Unexpected intrinsic");
1748   } else
1749     return false;
1750 
1751   SmallVector<Value *, 4> Args(CI.arg_operands().begin(),
1752                                CI.arg_operands().end());
1753   Args.pop_back();
1754   Args.pop_back();
1755   Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1756                            Args);
1757   unsigned NumArgs = CI.getNumArgOperands();
1758   Rep = EmitX86Select(Builder, CI.getArgOperand(NumArgs - 1), Rep,
1759                       CI.getArgOperand(NumArgs - 2));
1760   return true;
1761 }
1762 
1763 /// Upgrade comment in call to inline asm that represents an objc retain release
1764 /// marker.
UpgradeInlineAsmString(std::string * AsmStr)1765 void llvm::UpgradeInlineAsmString(std::string *AsmStr) {
1766   size_t Pos;
1767   if (AsmStr->find("mov\tfp") == 0 &&
1768       AsmStr->find("objc_retainAutoreleaseReturnValue") != std::string::npos &&
1769       (Pos = AsmStr->find("# marker")) != std::string::npos) {
1770     AsmStr->replace(Pos, 1, ";");
1771   }
1772   return;
1773 }
1774 
1775 /// Upgrade a call to an old intrinsic. All argument and return casting must be
1776 /// provided to seamlessly integrate with existing context.
UpgradeIntrinsicCall(CallInst * CI,Function * NewFn)1777 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
1778   Function *F = CI->getCalledFunction();
1779   LLVMContext &C = CI->getContext();
1780   IRBuilder<> Builder(C);
1781   Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
1782 
1783   assert(F && "Intrinsic call is not direct?");
1784 
1785   if (!NewFn) {
1786     // Get the Function's name.
1787     StringRef Name = F->getName();
1788 
1789     assert(Name.startswith("llvm.") && "Intrinsic doesn't start with 'llvm.'");
1790     Name = Name.substr(5);
1791 
1792     bool IsX86 = Name.startswith("x86.");
1793     if (IsX86)
1794       Name = Name.substr(4);
1795     bool IsNVVM = Name.startswith("nvvm.");
1796     if (IsNVVM)
1797       Name = Name.substr(5);
1798 
1799     if (IsX86 && Name.startswith("sse4a.movnt.")) {
1800       Module *M = F->getParent();
1801       SmallVector<Metadata *, 1> Elts;
1802       Elts.push_back(
1803           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1804       MDNode *Node = MDNode::get(C, Elts);
1805 
1806       Value *Arg0 = CI->getArgOperand(0);
1807       Value *Arg1 = CI->getArgOperand(1);
1808 
1809       // Nontemporal (unaligned) store of the 0'th element of the float/double
1810       // vector.
1811       Type *SrcEltTy = cast<VectorType>(Arg1->getType())->getElementType();
1812       PointerType *EltPtrTy = PointerType::getUnqual(SrcEltTy);
1813       Value *Addr = Builder.CreateBitCast(Arg0, EltPtrTy, "cast");
1814       Value *Extract =
1815           Builder.CreateExtractElement(Arg1, (uint64_t)0, "extractelement");
1816 
1817       StoreInst *SI = Builder.CreateAlignedStore(Extract, Addr, Align(1));
1818       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1819 
1820       // Remove intrinsic.
1821       CI->eraseFromParent();
1822       return;
1823     }
1824 
1825     if (IsX86 && (Name.startswith("avx.movnt.") ||
1826                   Name.startswith("avx512.storent."))) {
1827       Module *M = F->getParent();
1828       SmallVector<Metadata *, 1> Elts;
1829       Elts.push_back(
1830           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1831       MDNode *Node = MDNode::get(C, Elts);
1832 
1833       Value *Arg0 = CI->getArgOperand(0);
1834       Value *Arg1 = CI->getArgOperand(1);
1835 
1836       // Convert the type of the pointer to a pointer to the stored type.
1837       Value *BC = Builder.CreateBitCast(Arg0,
1838                                         PointerType::getUnqual(Arg1->getType()),
1839                                         "cast");
1840       StoreInst *SI = Builder.CreateAlignedStore(
1841           Arg1, BC,
1842           Align(Arg1->getType()->getPrimitiveSizeInBits().getFixedSize() / 8));
1843       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1844 
1845       // Remove intrinsic.
1846       CI->eraseFromParent();
1847       return;
1848     }
1849 
1850     if (IsX86 && Name == "sse2.storel.dq") {
1851       Value *Arg0 = CI->getArgOperand(0);
1852       Value *Arg1 = CI->getArgOperand(1);
1853 
1854       auto *NewVecTy = FixedVectorType::get(Type::getInt64Ty(C), 2);
1855       Value *BC0 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
1856       Value *Elt = Builder.CreateExtractElement(BC0, (uint64_t)0);
1857       Value *BC = Builder.CreateBitCast(Arg0,
1858                                         PointerType::getUnqual(Elt->getType()),
1859                                         "cast");
1860       Builder.CreateAlignedStore(Elt, BC, Align(1));
1861 
1862       // Remove intrinsic.
1863       CI->eraseFromParent();
1864       return;
1865     }
1866 
1867     if (IsX86 && (Name.startswith("sse.storeu.") ||
1868                   Name.startswith("sse2.storeu.") ||
1869                   Name.startswith("avx.storeu."))) {
1870       Value *Arg0 = CI->getArgOperand(0);
1871       Value *Arg1 = CI->getArgOperand(1);
1872 
1873       Arg0 = Builder.CreateBitCast(Arg0,
1874                                    PointerType::getUnqual(Arg1->getType()),
1875                                    "cast");
1876       Builder.CreateAlignedStore(Arg1, Arg0, Align(1));
1877 
1878       // Remove intrinsic.
1879       CI->eraseFromParent();
1880       return;
1881     }
1882 
1883     if (IsX86 && Name == "avx512.mask.store.ss") {
1884       Value *Mask = Builder.CreateAnd(CI->getArgOperand(2), Builder.getInt8(1));
1885       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1886                          Mask, false);
1887 
1888       // Remove intrinsic.
1889       CI->eraseFromParent();
1890       return;
1891     }
1892 
1893     if (IsX86 && (Name.startswith("avx512.mask.store"))) {
1894       // "avx512.mask.storeu." or "avx512.mask.store."
1895       bool Aligned = Name[17] != 'u'; // "avx512.mask.storeu".
1896       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1897                          CI->getArgOperand(2), Aligned);
1898 
1899       // Remove intrinsic.
1900       CI->eraseFromParent();
1901       return;
1902     }
1903 
1904     Value *Rep;
1905     // Upgrade packed integer vector compare intrinsics to compare instructions.
1906     if (IsX86 && (Name.startswith("sse2.pcmp") ||
1907                   Name.startswith("avx2.pcmp"))) {
1908       // "sse2.pcpmpeq." "sse2.pcmpgt." "avx2.pcmpeq." or "avx2.pcmpgt."
1909       bool CmpEq = Name[9] == 'e';
1910       Rep = Builder.CreateICmp(CmpEq ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_SGT,
1911                                CI->getArgOperand(0), CI->getArgOperand(1));
1912       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
1913     } else if (IsX86 && (Name.startswith("avx512.broadcastm"))) {
1914       Type *ExtTy = Type::getInt32Ty(C);
1915       if (CI->getOperand(0)->getType()->isIntegerTy(8))
1916         ExtTy = Type::getInt64Ty(C);
1917       unsigned NumElts = CI->getType()->getPrimitiveSizeInBits() /
1918                          ExtTy->getPrimitiveSizeInBits();
1919       Rep = Builder.CreateZExt(CI->getArgOperand(0), ExtTy);
1920       Rep = Builder.CreateVectorSplat(NumElts, Rep);
1921     } else if (IsX86 && (Name == "sse.sqrt.ss" ||
1922                          Name == "sse2.sqrt.sd")) {
1923       Value *Vec = CI->getArgOperand(0);
1924       Value *Elt0 = Builder.CreateExtractElement(Vec, (uint64_t)0);
1925       Function *Intr = Intrinsic::getDeclaration(F->getParent(),
1926                                                  Intrinsic::sqrt, Elt0->getType());
1927       Elt0 = Builder.CreateCall(Intr, Elt0);
1928       Rep = Builder.CreateInsertElement(Vec, Elt0, (uint64_t)0);
1929     } else if (IsX86 && (Name.startswith("avx.sqrt.p") ||
1930                          Name.startswith("sse2.sqrt.p") ||
1931                          Name.startswith("sse.sqrt.p"))) {
1932       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
1933                                                          Intrinsic::sqrt,
1934                                                          CI->getType()),
1935                                {CI->getArgOperand(0)});
1936     } else if (IsX86 && (Name.startswith("avx512.mask.sqrt.p"))) {
1937       if (CI->getNumArgOperands() == 4 &&
1938           (!isa<ConstantInt>(CI->getArgOperand(3)) ||
1939            cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
1940         Intrinsic::ID IID = Name[18] == 's' ? Intrinsic::x86_avx512_sqrt_ps_512
1941                                             : Intrinsic::x86_avx512_sqrt_pd_512;
1942 
1943         Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(3) };
1944         Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
1945                                                            IID), Args);
1946       } else {
1947         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
1948                                                            Intrinsic::sqrt,
1949                                                            CI->getType()),
1950                                  {CI->getArgOperand(0)});
1951       }
1952       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1953                           CI->getArgOperand(1));
1954     } else if (IsX86 && (Name.startswith("avx512.ptestm") ||
1955                          Name.startswith("avx512.ptestnm"))) {
1956       Value *Op0 = CI->getArgOperand(0);
1957       Value *Op1 = CI->getArgOperand(1);
1958       Value *Mask = CI->getArgOperand(2);
1959       Rep = Builder.CreateAnd(Op0, Op1);
1960       llvm::Type *Ty = Op0->getType();
1961       Value *Zero = llvm::Constant::getNullValue(Ty);
1962       ICmpInst::Predicate Pred =
1963         Name.startswith("avx512.ptestm") ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
1964       Rep = Builder.CreateICmp(Pred, Rep, Zero);
1965       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, Mask);
1966     } else if (IsX86 && (Name.startswith("avx512.mask.pbroadcast"))){
1967       unsigned NumElts = cast<FixedVectorType>(CI->getArgOperand(1)->getType())
1968                              ->getNumElements();
1969       Rep = Builder.CreateVectorSplat(NumElts, CI->getArgOperand(0));
1970       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1971                           CI->getArgOperand(1));
1972     } else if (IsX86 && (Name.startswith("avx512.kunpck"))) {
1973       unsigned NumElts = CI->getType()->getScalarSizeInBits();
1974       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), NumElts);
1975       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), NumElts);
1976       int Indices[64];
1977       for (unsigned i = 0; i != NumElts; ++i)
1978         Indices[i] = i;
1979 
1980       // First extract half of each vector. This gives better codegen than
1981       // doing it in a single shuffle.
1982       LHS = Builder.CreateShuffleVector(LHS, LHS,
1983                                         makeArrayRef(Indices, NumElts / 2));
1984       RHS = Builder.CreateShuffleVector(RHS, RHS,
1985                                         makeArrayRef(Indices, NumElts / 2));
1986       // Concat the vectors.
1987       // NOTE: Operands have to be swapped to match intrinsic definition.
1988       Rep = Builder.CreateShuffleVector(RHS, LHS,
1989                                         makeArrayRef(Indices, NumElts));
1990       Rep = Builder.CreateBitCast(Rep, CI->getType());
1991     } else if (IsX86 && Name == "avx512.kand.w") {
1992       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1993       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1994       Rep = Builder.CreateAnd(LHS, RHS);
1995       Rep = Builder.CreateBitCast(Rep, CI->getType());
1996     } else if (IsX86 && Name == "avx512.kandn.w") {
1997       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1998       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1999       LHS = Builder.CreateNot(LHS);
2000       Rep = Builder.CreateAnd(LHS, RHS);
2001       Rep = Builder.CreateBitCast(Rep, CI->getType());
2002     } else if (IsX86 && Name == "avx512.kor.w") {
2003       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2004       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2005       Rep = Builder.CreateOr(LHS, RHS);
2006       Rep = Builder.CreateBitCast(Rep, CI->getType());
2007     } else if (IsX86 && Name == "avx512.kxor.w") {
2008       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2009       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2010       Rep = Builder.CreateXor(LHS, RHS);
2011       Rep = Builder.CreateBitCast(Rep, CI->getType());
2012     } else if (IsX86 && Name == "avx512.kxnor.w") {
2013       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2014       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2015       LHS = Builder.CreateNot(LHS);
2016       Rep = Builder.CreateXor(LHS, RHS);
2017       Rep = Builder.CreateBitCast(Rep, CI->getType());
2018     } else if (IsX86 && Name == "avx512.knot.w") {
2019       Rep = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2020       Rep = Builder.CreateNot(Rep);
2021       Rep = Builder.CreateBitCast(Rep, CI->getType());
2022     } else if (IsX86 &&
2023                (Name == "avx512.kortestz.w" || Name == "avx512.kortestc.w")) {
2024       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
2025       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
2026       Rep = Builder.CreateOr(LHS, RHS);
2027       Rep = Builder.CreateBitCast(Rep, Builder.getInt16Ty());
2028       Value *C;
2029       if (Name[14] == 'c')
2030         C = ConstantInt::getAllOnesValue(Builder.getInt16Ty());
2031       else
2032         C = ConstantInt::getNullValue(Builder.getInt16Ty());
2033       Rep = Builder.CreateICmpEQ(Rep, C);
2034       Rep = Builder.CreateZExt(Rep, Builder.getInt32Ty());
2035     } else if (IsX86 && (Name == "sse.add.ss" || Name == "sse2.add.sd" ||
2036                          Name == "sse.sub.ss" || Name == "sse2.sub.sd" ||
2037                          Name == "sse.mul.ss" || Name == "sse2.mul.sd" ||
2038                          Name == "sse.div.ss" || Name == "sse2.div.sd")) {
2039       Type *I32Ty = Type::getInt32Ty(C);
2040       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
2041                                                  ConstantInt::get(I32Ty, 0));
2042       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
2043                                                  ConstantInt::get(I32Ty, 0));
2044       Value *EltOp;
2045       if (Name.contains(".add."))
2046         EltOp = Builder.CreateFAdd(Elt0, Elt1);
2047       else if (Name.contains(".sub."))
2048         EltOp = Builder.CreateFSub(Elt0, Elt1);
2049       else if (Name.contains(".mul."))
2050         EltOp = Builder.CreateFMul(Elt0, Elt1);
2051       else
2052         EltOp = Builder.CreateFDiv(Elt0, Elt1);
2053       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), EltOp,
2054                                         ConstantInt::get(I32Ty, 0));
2055     } else if (IsX86 && Name.startswith("avx512.mask.pcmp")) {
2056       // "avx512.mask.pcmpeq." or "avx512.mask.pcmpgt."
2057       bool CmpEq = Name[16] == 'e';
2058       Rep = upgradeMaskedCompare(Builder, *CI, CmpEq ? 0 : 6, true);
2059     } else if (IsX86 && Name.startswith("avx512.mask.vpshufbitqmb.")) {
2060       Type *OpTy = CI->getArgOperand(0)->getType();
2061       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2062       Intrinsic::ID IID;
2063       switch (VecWidth) {
2064       default: llvm_unreachable("Unexpected intrinsic");
2065       case 128: IID = Intrinsic::x86_avx512_vpshufbitqmb_128; break;
2066       case 256: IID = Intrinsic::x86_avx512_vpshufbitqmb_256; break;
2067       case 512: IID = Intrinsic::x86_avx512_vpshufbitqmb_512; break;
2068       }
2069 
2070       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2071                                { CI->getOperand(0), CI->getArgOperand(1) });
2072       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
2073     } else if (IsX86 && Name.startswith("avx512.mask.fpclass.p")) {
2074       Type *OpTy = CI->getArgOperand(0)->getType();
2075       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2076       unsigned EltWidth = OpTy->getScalarSizeInBits();
2077       Intrinsic::ID IID;
2078       if (VecWidth == 128 && EltWidth == 32)
2079         IID = Intrinsic::x86_avx512_fpclass_ps_128;
2080       else if (VecWidth == 256 && EltWidth == 32)
2081         IID = Intrinsic::x86_avx512_fpclass_ps_256;
2082       else if (VecWidth == 512 && EltWidth == 32)
2083         IID = Intrinsic::x86_avx512_fpclass_ps_512;
2084       else if (VecWidth == 128 && EltWidth == 64)
2085         IID = Intrinsic::x86_avx512_fpclass_pd_128;
2086       else if (VecWidth == 256 && EltWidth == 64)
2087         IID = Intrinsic::x86_avx512_fpclass_pd_256;
2088       else if (VecWidth == 512 && EltWidth == 64)
2089         IID = Intrinsic::x86_avx512_fpclass_pd_512;
2090       else
2091         llvm_unreachable("Unexpected intrinsic");
2092 
2093       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2094                                { CI->getOperand(0), CI->getArgOperand(1) });
2095       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, CI->getArgOperand(2));
2096     } else if (IsX86 && Name.startswith("avx512.cmp.p")) {
2097       SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2098                                    CI->arg_operands().end());
2099       Type *OpTy = Args[0]->getType();
2100       unsigned VecWidth = OpTy->getPrimitiveSizeInBits();
2101       unsigned EltWidth = OpTy->getScalarSizeInBits();
2102       Intrinsic::ID IID;
2103       if (VecWidth == 128 && EltWidth == 32)
2104         IID = Intrinsic::x86_avx512_mask_cmp_ps_128;
2105       else if (VecWidth == 256 && EltWidth == 32)
2106         IID = Intrinsic::x86_avx512_mask_cmp_ps_256;
2107       else if (VecWidth == 512 && EltWidth == 32)
2108         IID = Intrinsic::x86_avx512_mask_cmp_ps_512;
2109       else if (VecWidth == 128 && EltWidth == 64)
2110         IID = Intrinsic::x86_avx512_mask_cmp_pd_128;
2111       else if (VecWidth == 256 && EltWidth == 64)
2112         IID = Intrinsic::x86_avx512_mask_cmp_pd_256;
2113       else if (VecWidth == 512 && EltWidth == 64)
2114         IID = Intrinsic::x86_avx512_mask_cmp_pd_512;
2115       else
2116         llvm_unreachable("Unexpected intrinsic");
2117 
2118       Value *Mask = Constant::getAllOnesValue(CI->getType());
2119       if (VecWidth == 512)
2120         std::swap(Mask, Args.back());
2121       Args.push_back(Mask);
2122 
2123       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2124                                Args);
2125     } else if (IsX86 && Name.startswith("avx512.mask.cmp.")) {
2126       // Integer compare intrinsics.
2127       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2128       Rep = upgradeMaskedCompare(Builder, *CI, Imm, true);
2129     } else if (IsX86 && Name.startswith("avx512.mask.ucmp.")) {
2130       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2131       Rep = upgradeMaskedCompare(Builder, *CI, Imm, false);
2132     } else if (IsX86 && (Name.startswith("avx512.cvtb2mask.") ||
2133                          Name.startswith("avx512.cvtw2mask.") ||
2134                          Name.startswith("avx512.cvtd2mask.") ||
2135                          Name.startswith("avx512.cvtq2mask."))) {
2136       Value *Op = CI->getArgOperand(0);
2137       Value *Zero = llvm::Constant::getNullValue(Op->getType());
2138       Rep = Builder.CreateICmp(ICmpInst::ICMP_SLT, Op, Zero);
2139       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, nullptr);
2140     } else if(IsX86 && (Name == "ssse3.pabs.b.128" ||
2141                         Name == "ssse3.pabs.w.128" ||
2142                         Name == "ssse3.pabs.d.128" ||
2143                         Name.startswith("avx2.pabs") ||
2144                         Name.startswith("avx512.mask.pabs"))) {
2145       Rep = upgradeAbs(Builder, *CI);
2146     } else if (IsX86 && (Name == "sse41.pmaxsb" ||
2147                          Name == "sse2.pmaxs.w" ||
2148                          Name == "sse41.pmaxsd" ||
2149                          Name.startswith("avx2.pmaxs") ||
2150                          Name.startswith("avx512.mask.pmaxs"))) {
2151       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::smax);
2152     } else if (IsX86 && (Name == "sse2.pmaxu.b" ||
2153                          Name == "sse41.pmaxuw" ||
2154                          Name == "sse41.pmaxud" ||
2155                          Name.startswith("avx2.pmaxu") ||
2156                          Name.startswith("avx512.mask.pmaxu"))) {
2157       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::umax);
2158     } else if (IsX86 && (Name == "sse41.pminsb" ||
2159                          Name == "sse2.pmins.w" ||
2160                          Name == "sse41.pminsd" ||
2161                          Name.startswith("avx2.pmins") ||
2162                          Name.startswith("avx512.mask.pmins"))) {
2163       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::smin);
2164     } else if (IsX86 && (Name == "sse2.pminu.b" ||
2165                          Name == "sse41.pminuw" ||
2166                          Name == "sse41.pminud" ||
2167                          Name.startswith("avx2.pminu") ||
2168                          Name.startswith("avx512.mask.pminu"))) {
2169       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::umin);
2170     } else if (IsX86 && (Name == "sse2.pmulu.dq" ||
2171                          Name == "avx2.pmulu.dq" ||
2172                          Name == "avx512.pmulu.dq.512" ||
2173                          Name.startswith("avx512.mask.pmulu.dq."))) {
2174       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/false);
2175     } else if (IsX86 && (Name == "sse41.pmuldq" ||
2176                          Name == "avx2.pmul.dq" ||
2177                          Name == "avx512.pmul.dq.512" ||
2178                          Name.startswith("avx512.mask.pmul.dq."))) {
2179       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/true);
2180     } else if (IsX86 && (Name == "sse.cvtsi2ss" ||
2181                          Name == "sse2.cvtsi2sd" ||
2182                          Name == "sse.cvtsi642ss" ||
2183                          Name == "sse2.cvtsi642sd")) {
2184       Rep = Builder.CreateSIToFP(
2185           CI->getArgOperand(1),
2186           cast<VectorType>(CI->getType())->getElementType());
2187       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2188     } else if (IsX86 && Name == "avx512.cvtusi2sd") {
2189       Rep = Builder.CreateUIToFP(
2190           CI->getArgOperand(1),
2191           cast<VectorType>(CI->getType())->getElementType());
2192       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2193     } else if (IsX86 && Name == "sse2.cvtss2sd") {
2194       Rep = Builder.CreateExtractElement(CI->getArgOperand(1), (uint64_t)0);
2195       Rep = Builder.CreateFPExt(
2196           Rep, cast<VectorType>(CI->getType())->getElementType());
2197       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
2198     } else if (IsX86 && (Name == "sse2.cvtdq2pd" ||
2199                          Name == "sse2.cvtdq2ps" ||
2200                          Name == "avx.cvtdq2.pd.256" ||
2201                          Name == "avx.cvtdq2.ps.256" ||
2202                          Name.startswith("avx512.mask.cvtdq2pd.") ||
2203                          Name.startswith("avx512.mask.cvtudq2pd.") ||
2204                          Name.startswith("avx512.mask.cvtdq2ps.") ||
2205                          Name.startswith("avx512.mask.cvtudq2ps.") ||
2206                          Name.startswith("avx512.mask.cvtqq2pd.") ||
2207                          Name.startswith("avx512.mask.cvtuqq2pd.") ||
2208                          Name == "avx512.mask.cvtqq2ps.256" ||
2209                          Name == "avx512.mask.cvtqq2ps.512" ||
2210                          Name == "avx512.mask.cvtuqq2ps.256" ||
2211                          Name == "avx512.mask.cvtuqq2ps.512" ||
2212                          Name == "sse2.cvtps2pd" ||
2213                          Name == "avx.cvt.ps2.pd.256" ||
2214                          Name == "avx512.mask.cvtps2pd.128" ||
2215                          Name == "avx512.mask.cvtps2pd.256")) {
2216       auto *DstTy = cast<FixedVectorType>(CI->getType());
2217       Rep = CI->getArgOperand(0);
2218       auto *SrcTy = cast<FixedVectorType>(Rep->getType());
2219 
2220       unsigned NumDstElts = DstTy->getNumElements();
2221       if (NumDstElts < SrcTy->getNumElements()) {
2222         assert(NumDstElts == 2 && "Unexpected vector size");
2223         Rep = Builder.CreateShuffleVector(Rep, Rep, ArrayRef<int>{0, 1});
2224       }
2225 
2226       bool IsPS2PD = SrcTy->getElementType()->isFloatTy();
2227       bool IsUnsigned = (StringRef::npos != Name.find("cvtu"));
2228       if (IsPS2PD)
2229         Rep = Builder.CreateFPExt(Rep, DstTy, "cvtps2pd");
2230       else if (CI->getNumArgOperands() == 4 &&
2231                (!isa<ConstantInt>(CI->getArgOperand(3)) ||
2232                 cast<ConstantInt>(CI->getArgOperand(3))->getZExtValue() != 4)) {
2233         Intrinsic::ID IID = IsUnsigned ? Intrinsic::x86_avx512_uitofp_round
2234                                        : Intrinsic::x86_avx512_sitofp_round;
2235         Function *F = Intrinsic::getDeclaration(CI->getModule(), IID,
2236                                                 { DstTy, SrcTy });
2237         Rep = Builder.CreateCall(F, { Rep, CI->getArgOperand(3) });
2238       } else {
2239         Rep = IsUnsigned ? Builder.CreateUIToFP(Rep, DstTy, "cvt")
2240                          : Builder.CreateSIToFP(Rep, DstTy, "cvt");
2241       }
2242 
2243       if (CI->getNumArgOperands() >= 3)
2244         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2245                             CI->getArgOperand(1));
2246     } else if (IsX86 && (Name.startswith("avx512.mask.vcvtph2ps.") ||
2247                          Name.startswith("vcvtph2ps."))) {
2248       auto *DstTy = cast<FixedVectorType>(CI->getType());
2249       Rep = CI->getArgOperand(0);
2250       auto *SrcTy = cast<FixedVectorType>(Rep->getType());
2251       unsigned NumDstElts = DstTy->getNumElements();
2252       if (NumDstElts != SrcTy->getNumElements()) {
2253         assert(NumDstElts == 4 && "Unexpected vector size");
2254         Rep = Builder.CreateShuffleVector(Rep, Rep, ArrayRef<int>{0, 1, 2, 3});
2255       }
2256       Rep = Builder.CreateBitCast(
2257           Rep, FixedVectorType::get(Type::getHalfTy(C), NumDstElts));
2258       Rep = Builder.CreateFPExt(Rep, DstTy, "cvtph2ps");
2259       if (CI->getNumArgOperands() >= 3)
2260         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2261                             CI->getArgOperand(1));
2262     } else if (IsX86 && (Name.startswith("avx512.mask.loadu."))) {
2263       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
2264                               CI->getArgOperand(1), CI->getArgOperand(2),
2265                               /*Aligned*/false);
2266     } else if (IsX86 && (Name.startswith("avx512.mask.load."))) {
2267       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
2268                               CI->getArgOperand(1),CI->getArgOperand(2),
2269                               /*Aligned*/true);
2270     } else if (IsX86 && Name.startswith("avx512.mask.expand.load.")) {
2271       auto *ResultTy = cast<FixedVectorType>(CI->getType());
2272       Type *PtrTy = ResultTy->getElementType();
2273 
2274       // Cast the pointer to element type.
2275       Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2276                                          llvm::PointerType::getUnqual(PtrTy));
2277 
2278       Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2279                                      ResultTy->getNumElements());
2280 
2281       Function *ELd = Intrinsic::getDeclaration(F->getParent(),
2282                                                 Intrinsic::masked_expandload,
2283                                                 ResultTy);
2284       Rep = Builder.CreateCall(ELd, { Ptr, MaskVec, CI->getOperand(1) });
2285     } else if (IsX86 && Name.startswith("avx512.mask.compress.store.")) {
2286       auto *ResultTy = cast<VectorType>(CI->getArgOperand(1)->getType());
2287       Type *PtrTy = ResultTy->getElementType();
2288 
2289       // Cast the pointer to element type.
2290       Value *Ptr = Builder.CreateBitCast(CI->getOperand(0),
2291                                          llvm::PointerType::getUnqual(PtrTy));
2292 
2293       Value *MaskVec =
2294           getX86MaskVec(Builder, CI->getArgOperand(2),
2295                         cast<FixedVectorType>(ResultTy)->getNumElements());
2296 
2297       Function *CSt = Intrinsic::getDeclaration(F->getParent(),
2298                                                 Intrinsic::masked_compressstore,
2299                                                 ResultTy);
2300       Rep = Builder.CreateCall(CSt, { CI->getArgOperand(1), Ptr, MaskVec });
2301     } else if (IsX86 && (Name.startswith("avx512.mask.compress.") ||
2302                          Name.startswith("avx512.mask.expand."))) {
2303       auto *ResultTy = cast<FixedVectorType>(CI->getType());
2304 
2305       Value *MaskVec = getX86MaskVec(Builder, CI->getArgOperand(2),
2306                                      ResultTy->getNumElements());
2307 
2308       bool IsCompress = Name[12] == 'c';
2309       Intrinsic::ID IID = IsCompress ? Intrinsic::x86_avx512_mask_compress
2310                                      : Intrinsic::x86_avx512_mask_expand;
2311       Function *Intr = Intrinsic::getDeclaration(F->getParent(), IID, ResultTy);
2312       Rep = Builder.CreateCall(Intr, { CI->getOperand(0), CI->getOperand(1),
2313                                        MaskVec });
2314     } else if (IsX86 && Name.startswith("xop.vpcom")) {
2315       bool IsSigned;
2316       if (Name.endswith("ub") || Name.endswith("uw") || Name.endswith("ud") ||
2317           Name.endswith("uq"))
2318         IsSigned = false;
2319       else if (Name.endswith("b") || Name.endswith("w") || Name.endswith("d") ||
2320                Name.endswith("q"))
2321         IsSigned = true;
2322       else
2323         llvm_unreachable("Unknown suffix");
2324 
2325       unsigned Imm;
2326       if (CI->getNumArgOperands() == 3) {
2327         Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2328       } else {
2329         Name = Name.substr(9); // strip off "xop.vpcom"
2330         if (Name.startswith("lt"))
2331           Imm = 0;
2332         else if (Name.startswith("le"))
2333           Imm = 1;
2334         else if (Name.startswith("gt"))
2335           Imm = 2;
2336         else if (Name.startswith("ge"))
2337           Imm = 3;
2338         else if (Name.startswith("eq"))
2339           Imm = 4;
2340         else if (Name.startswith("ne"))
2341           Imm = 5;
2342         else if (Name.startswith("false"))
2343           Imm = 6;
2344         else if (Name.startswith("true"))
2345           Imm = 7;
2346         else
2347           llvm_unreachable("Unknown condition");
2348       }
2349 
2350       Rep = upgradeX86vpcom(Builder, *CI, Imm, IsSigned);
2351     } else if (IsX86 && Name.startswith("xop.vpcmov")) {
2352       Value *Sel = CI->getArgOperand(2);
2353       Value *NotSel = Builder.CreateNot(Sel);
2354       Value *Sel0 = Builder.CreateAnd(CI->getArgOperand(0), Sel);
2355       Value *Sel1 = Builder.CreateAnd(CI->getArgOperand(1), NotSel);
2356       Rep = Builder.CreateOr(Sel0, Sel1);
2357     } else if (IsX86 && (Name.startswith("xop.vprot") ||
2358                          Name.startswith("avx512.prol") ||
2359                          Name.startswith("avx512.mask.prol"))) {
2360       Rep = upgradeX86Rotate(Builder, *CI, false);
2361     } else if (IsX86 && (Name.startswith("avx512.pror") ||
2362                          Name.startswith("avx512.mask.pror"))) {
2363       Rep = upgradeX86Rotate(Builder, *CI, true);
2364     } else if (IsX86 && (Name.startswith("avx512.vpshld.") ||
2365                          Name.startswith("avx512.mask.vpshld") ||
2366                          Name.startswith("avx512.maskz.vpshld"))) {
2367       bool ZeroMask = Name[11] == 'z';
2368       Rep = upgradeX86ConcatShift(Builder, *CI, false, ZeroMask);
2369     } else if (IsX86 && (Name.startswith("avx512.vpshrd.") ||
2370                          Name.startswith("avx512.mask.vpshrd") ||
2371                          Name.startswith("avx512.maskz.vpshrd"))) {
2372       bool ZeroMask = Name[11] == 'z';
2373       Rep = upgradeX86ConcatShift(Builder, *CI, true, ZeroMask);
2374     } else if (IsX86 && Name == "sse42.crc32.64.8") {
2375       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
2376                                                Intrinsic::x86_sse42_crc32_32_8);
2377       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
2378       Rep = Builder.CreateCall(CRC32, {Trunc0, CI->getArgOperand(1)});
2379       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
2380     } else if (IsX86 && (Name.startswith("avx.vbroadcast.s") ||
2381                          Name.startswith("avx512.vbroadcast.s"))) {
2382       // Replace broadcasts with a series of insertelements.
2383       auto *VecTy = cast<FixedVectorType>(CI->getType());
2384       Type *EltTy = VecTy->getElementType();
2385       unsigned EltNum = VecTy->getNumElements();
2386       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
2387                                           EltTy->getPointerTo());
2388       Value *Load = Builder.CreateLoad(EltTy, Cast);
2389       Type *I32Ty = Type::getInt32Ty(C);
2390       Rep = UndefValue::get(VecTy);
2391       for (unsigned I = 0; I < EltNum; ++I)
2392         Rep = Builder.CreateInsertElement(Rep, Load,
2393                                           ConstantInt::get(I32Ty, I));
2394     } else if (IsX86 && (Name.startswith("sse41.pmovsx") ||
2395                          Name.startswith("sse41.pmovzx") ||
2396                          Name.startswith("avx2.pmovsx") ||
2397                          Name.startswith("avx2.pmovzx") ||
2398                          Name.startswith("avx512.mask.pmovsx") ||
2399                          Name.startswith("avx512.mask.pmovzx"))) {
2400       auto *SrcTy = cast<FixedVectorType>(CI->getArgOperand(0)->getType());
2401       auto *DstTy = cast<FixedVectorType>(CI->getType());
2402       unsigned NumDstElts = DstTy->getNumElements();
2403 
2404       // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
2405       SmallVector<int, 8> ShuffleMask(NumDstElts);
2406       for (unsigned i = 0; i != NumDstElts; ++i)
2407         ShuffleMask[i] = i;
2408 
2409       Value *SV = Builder.CreateShuffleVector(
2410           CI->getArgOperand(0), UndefValue::get(SrcTy), ShuffleMask);
2411 
2412       bool DoSext = (StringRef::npos != Name.find("pmovsx"));
2413       Rep = DoSext ? Builder.CreateSExt(SV, DstTy)
2414                    : Builder.CreateZExt(SV, DstTy);
2415       // If there are 3 arguments, it's a masked intrinsic so we need a select.
2416       if (CI->getNumArgOperands() == 3)
2417         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2418                             CI->getArgOperand(1));
2419     } else if (Name == "avx512.mask.pmov.qd.256" ||
2420                Name == "avx512.mask.pmov.qd.512" ||
2421                Name == "avx512.mask.pmov.wb.256" ||
2422                Name == "avx512.mask.pmov.wb.512") {
2423       Type *Ty = CI->getArgOperand(1)->getType();
2424       Rep = Builder.CreateTrunc(CI->getArgOperand(0), Ty);
2425       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2426                           CI->getArgOperand(1));
2427     } else if (IsX86 && (Name.startswith("avx.vbroadcastf128") ||
2428                          Name == "avx2.vbroadcasti128")) {
2429       // Replace vbroadcastf128/vbroadcasti128 with a vector load+shuffle.
2430       Type *EltTy = cast<VectorType>(CI->getType())->getElementType();
2431       unsigned NumSrcElts = 128 / EltTy->getPrimitiveSizeInBits();
2432       auto *VT = FixedVectorType::get(EltTy, NumSrcElts);
2433       Value *Op = Builder.CreatePointerCast(CI->getArgOperand(0),
2434                                             PointerType::getUnqual(VT));
2435       Value *Load = Builder.CreateAlignedLoad(VT, Op, Align(1));
2436       if (NumSrcElts == 2)
2437         Rep = Builder.CreateShuffleVector(
2438             Load, UndefValue::get(Load->getType()), ArrayRef<int>{0, 1, 0, 1});
2439       else
2440         Rep =
2441             Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
2442                                         ArrayRef<int>{0, 1, 2, 3, 0, 1, 2, 3});
2443     } else if (IsX86 && (Name.startswith("avx512.mask.shuf.i") ||
2444                          Name.startswith("avx512.mask.shuf.f"))) {
2445       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2446       Type *VT = CI->getType();
2447       unsigned NumLanes = VT->getPrimitiveSizeInBits() / 128;
2448       unsigned NumElementsInLane = 128 / VT->getScalarSizeInBits();
2449       unsigned ControlBitsMask = NumLanes - 1;
2450       unsigned NumControlBits = NumLanes / 2;
2451       SmallVector<int, 8> ShuffleMask(0);
2452 
2453       for (unsigned l = 0; l != NumLanes; ++l) {
2454         unsigned LaneMask = (Imm >> (l * NumControlBits)) & ControlBitsMask;
2455         // We actually need the other source.
2456         if (l >= NumLanes / 2)
2457           LaneMask += NumLanes;
2458         for (unsigned i = 0; i != NumElementsInLane; ++i)
2459           ShuffleMask.push_back(LaneMask * NumElementsInLane + i);
2460       }
2461       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
2462                                         CI->getArgOperand(1), ShuffleMask);
2463       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2464                           CI->getArgOperand(3));
2465     }else if (IsX86 && (Name.startswith("avx512.mask.broadcastf") ||
2466                          Name.startswith("avx512.mask.broadcasti"))) {
2467       unsigned NumSrcElts =
2468           cast<FixedVectorType>(CI->getArgOperand(0)->getType())
2469               ->getNumElements();
2470       unsigned NumDstElts =
2471           cast<FixedVectorType>(CI->getType())->getNumElements();
2472 
2473       SmallVector<int, 8> ShuffleMask(NumDstElts);
2474       for (unsigned i = 0; i != NumDstElts; ++i)
2475         ShuffleMask[i] = i % NumSrcElts;
2476 
2477       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
2478                                         CI->getArgOperand(0),
2479                                         ShuffleMask);
2480       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2481                           CI->getArgOperand(1));
2482     } else if (IsX86 && (Name.startswith("avx2.pbroadcast") ||
2483                          Name.startswith("avx2.vbroadcast") ||
2484                          Name.startswith("avx512.pbroadcast") ||
2485                          Name.startswith("avx512.mask.broadcast.s"))) {
2486       // Replace vp?broadcasts with a vector shuffle.
2487       Value *Op = CI->getArgOperand(0);
2488       ElementCount EC = cast<VectorType>(CI->getType())->getElementCount();
2489       Type *MaskTy = VectorType::get(Type::getInt32Ty(C), EC);
2490       Rep = Builder.CreateShuffleVector(Op, UndefValue::get(Op->getType()),
2491                                         Constant::getNullValue(MaskTy));
2492 
2493       if (CI->getNumArgOperands() == 3)
2494         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2495                             CI->getArgOperand(1));
2496     } else if (IsX86 && (Name.startswith("sse2.padds.") ||
2497                          Name.startswith("avx2.padds.") ||
2498                          Name.startswith("avx512.padds.") ||
2499                          Name.startswith("avx512.mask.padds."))) {
2500       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::sadd_sat);
2501     } else if (IsX86 && (Name.startswith("sse2.psubs.") ||
2502                          Name.startswith("avx2.psubs.") ||
2503                          Name.startswith("avx512.psubs.") ||
2504                          Name.startswith("avx512.mask.psubs."))) {
2505       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::ssub_sat);
2506     } else if (IsX86 && (Name.startswith("sse2.paddus.") ||
2507                          Name.startswith("avx2.paddus.") ||
2508                          Name.startswith("avx512.mask.paddus."))) {
2509       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::uadd_sat);
2510     } else if (IsX86 && (Name.startswith("sse2.psubus.") ||
2511                          Name.startswith("avx2.psubus.") ||
2512                          Name.startswith("avx512.mask.psubus."))) {
2513       Rep = UpgradeX86BinaryIntrinsics(Builder, *CI, Intrinsic::usub_sat);
2514     } else if (IsX86 && Name.startswith("avx512.mask.palignr.")) {
2515       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2516                                       CI->getArgOperand(1),
2517                                       CI->getArgOperand(2),
2518                                       CI->getArgOperand(3),
2519                                       CI->getArgOperand(4),
2520                                       false);
2521     } else if (IsX86 && Name.startswith("avx512.mask.valign.")) {
2522       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
2523                                       CI->getArgOperand(1),
2524                                       CI->getArgOperand(2),
2525                                       CI->getArgOperand(3),
2526                                       CI->getArgOperand(4),
2527                                       true);
2528     } else if (IsX86 && (Name == "sse2.psll.dq" ||
2529                          Name == "avx2.psll.dq")) {
2530       // 128/256-bit shift left specified in bits.
2531       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2532       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0),
2533                                        Shift / 8); // Shift is in bits.
2534     } else if (IsX86 && (Name == "sse2.psrl.dq" ||
2535                          Name == "avx2.psrl.dq")) {
2536       // 128/256-bit shift right specified in bits.
2537       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2538       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0),
2539                                        Shift / 8); // Shift is in bits.
2540     } else if (IsX86 && (Name == "sse2.psll.dq.bs" ||
2541                          Name == "avx2.psll.dq.bs" ||
2542                          Name == "avx512.psll.dq.512")) {
2543       // 128/256/512-bit shift left specified in bytes.
2544       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2545       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2546     } else if (IsX86 && (Name == "sse2.psrl.dq.bs" ||
2547                          Name == "avx2.psrl.dq.bs" ||
2548                          Name == "avx512.psrl.dq.512")) {
2549       // 128/256/512-bit shift right specified in bytes.
2550       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2551       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
2552     } else if (IsX86 && (Name == "sse41.pblendw" ||
2553                          Name.startswith("sse41.blendp") ||
2554                          Name.startswith("avx.blend.p") ||
2555                          Name == "avx2.pblendw" ||
2556                          Name.startswith("avx2.pblendd."))) {
2557       Value *Op0 = CI->getArgOperand(0);
2558       Value *Op1 = CI->getArgOperand(1);
2559       unsigned Imm = cast <ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2560       auto *VecTy = cast<FixedVectorType>(CI->getType());
2561       unsigned NumElts = VecTy->getNumElements();
2562 
2563       SmallVector<int, 16> Idxs(NumElts);
2564       for (unsigned i = 0; i != NumElts; ++i)
2565         Idxs[i] = ((Imm >> (i%8)) & 1) ? i + NumElts : i;
2566 
2567       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2568     } else if (IsX86 && (Name.startswith("avx.vinsertf128.") ||
2569                          Name == "avx2.vinserti128" ||
2570                          Name.startswith("avx512.mask.insert"))) {
2571       Value *Op0 = CI->getArgOperand(0);
2572       Value *Op1 = CI->getArgOperand(1);
2573       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2574       unsigned DstNumElts =
2575           cast<FixedVectorType>(CI->getType())->getNumElements();
2576       unsigned SrcNumElts =
2577           cast<FixedVectorType>(Op1->getType())->getNumElements();
2578       unsigned Scale = DstNumElts / SrcNumElts;
2579 
2580       // Mask off the high bits of the immediate value; hardware ignores those.
2581       Imm = Imm % Scale;
2582 
2583       // Extend the second operand into a vector the size of the destination.
2584       Value *UndefV = UndefValue::get(Op1->getType());
2585       SmallVector<int, 8> Idxs(DstNumElts);
2586       for (unsigned i = 0; i != SrcNumElts; ++i)
2587         Idxs[i] = i;
2588       for (unsigned i = SrcNumElts; i != DstNumElts; ++i)
2589         Idxs[i] = SrcNumElts;
2590       Rep = Builder.CreateShuffleVector(Op1, UndefV, Idxs);
2591 
2592       // Insert the second operand into the first operand.
2593 
2594       // Note that there is no guarantee that instruction lowering will actually
2595       // produce a vinsertf128 instruction for the created shuffles. In
2596       // particular, the 0 immediate case involves no lane changes, so it can
2597       // be handled as a blend.
2598 
2599       // Example of shuffle mask for 32-bit elements:
2600       // Imm = 1  <i32 0, i32 1, i32 2,  i32 3,  i32 8, i32 9, i32 10, i32 11>
2601       // Imm = 0  <i32 8, i32 9, i32 10, i32 11, i32 4, i32 5, i32 6,  i32 7 >
2602 
2603       // First fill with identify mask.
2604       for (unsigned i = 0; i != DstNumElts; ++i)
2605         Idxs[i] = i;
2606       // Then replace the elements where we need to insert.
2607       for (unsigned i = 0; i != SrcNumElts; ++i)
2608         Idxs[i + Imm * SrcNumElts] = i + DstNumElts;
2609       Rep = Builder.CreateShuffleVector(Op0, Rep, Idxs);
2610 
2611       // If the intrinsic has a mask operand, handle that.
2612       if (CI->getNumArgOperands() == 5)
2613         Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2614                             CI->getArgOperand(3));
2615     } else if (IsX86 && (Name.startswith("avx.vextractf128.") ||
2616                          Name == "avx2.vextracti128" ||
2617                          Name.startswith("avx512.mask.vextract"))) {
2618       Value *Op0 = CI->getArgOperand(0);
2619       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2620       unsigned DstNumElts =
2621           cast<FixedVectorType>(CI->getType())->getNumElements();
2622       unsigned SrcNumElts =
2623           cast<FixedVectorType>(Op0->getType())->getNumElements();
2624       unsigned Scale = SrcNumElts / DstNumElts;
2625 
2626       // Mask off the high bits of the immediate value; hardware ignores those.
2627       Imm = Imm % Scale;
2628 
2629       // Get indexes for the subvector of the input vector.
2630       SmallVector<int, 8> Idxs(DstNumElts);
2631       for (unsigned i = 0; i != DstNumElts; ++i) {
2632         Idxs[i] = i + (Imm * DstNumElts);
2633       }
2634       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2635 
2636       // If the intrinsic has a mask operand, handle that.
2637       if (CI->getNumArgOperands() == 4)
2638         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2639                             CI->getArgOperand(2));
2640     } else if (!IsX86 && Name == "stackprotectorcheck") {
2641       Rep = nullptr;
2642     } else if (IsX86 && (Name.startswith("avx512.mask.perm.df.") ||
2643                          Name.startswith("avx512.mask.perm.di."))) {
2644       Value *Op0 = CI->getArgOperand(0);
2645       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2646       auto *VecTy = cast<FixedVectorType>(CI->getType());
2647       unsigned NumElts = VecTy->getNumElements();
2648 
2649       SmallVector<int, 8> Idxs(NumElts);
2650       for (unsigned i = 0; i != NumElts; ++i)
2651         Idxs[i] = (i & ~0x3) + ((Imm >> (2 * (i & 0x3))) & 3);
2652 
2653       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2654 
2655       if (CI->getNumArgOperands() == 4)
2656         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2657                             CI->getArgOperand(2));
2658     } else if (IsX86 && (Name.startswith("avx.vperm2f128.") ||
2659                          Name == "avx2.vperm2i128")) {
2660       // The immediate permute control byte looks like this:
2661       //    [1:0] - select 128 bits from sources for low half of destination
2662       //    [2]   - ignore
2663       //    [3]   - zero low half of destination
2664       //    [5:4] - select 128 bits from sources for high half of destination
2665       //    [6]   - ignore
2666       //    [7]   - zero high half of destination
2667 
2668       uint8_t Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2669 
2670       unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2671       unsigned HalfSize = NumElts / 2;
2672       SmallVector<int, 8> ShuffleMask(NumElts);
2673 
2674       // Determine which operand(s) are actually in use for this instruction.
2675       Value *V0 = (Imm & 0x02) ? CI->getArgOperand(1) : CI->getArgOperand(0);
2676       Value *V1 = (Imm & 0x20) ? CI->getArgOperand(1) : CI->getArgOperand(0);
2677 
2678       // If needed, replace operands based on zero mask.
2679       V0 = (Imm & 0x08) ? ConstantAggregateZero::get(CI->getType()) : V0;
2680       V1 = (Imm & 0x80) ? ConstantAggregateZero::get(CI->getType()) : V1;
2681 
2682       // Permute low half of result.
2683       unsigned StartIndex = (Imm & 0x01) ? HalfSize : 0;
2684       for (unsigned i = 0; i < HalfSize; ++i)
2685         ShuffleMask[i] = StartIndex + i;
2686 
2687       // Permute high half of result.
2688       StartIndex = (Imm & 0x10) ? HalfSize : 0;
2689       for (unsigned i = 0; i < HalfSize; ++i)
2690         ShuffleMask[i + HalfSize] = NumElts + StartIndex + i;
2691 
2692       Rep = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2693 
2694     } else if (IsX86 && (Name.startswith("avx.vpermil.") ||
2695                          Name == "sse2.pshuf.d" ||
2696                          Name.startswith("avx512.mask.vpermil.p") ||
2697                          Name.startswith("avx512.mask.pshuf.d."))) {
2698       Value *Op0 = CI->getArgOperand(0);
2699       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2700       auto *VecTy = cast<FixedVectorType>(CI->getType());
2701       unsigned NumElts = VecTy->getNumElements();
2702       // Calculate the size of each index in the immediate.
2703       unsigned IdxSize = 64 / VecTy->getScalarSizeInBits();
2704       unsigned IdxMask = ((1 << IdxSize) - 1);
2705 
2706       SmallVector<int, 8> Idxs(NumElts);
2707       // Lookup the bits for this element, wrapping around the immediate every
2708       // 8-bits. Elements are grouped into sets of 2 or 4 elements so we need
2709       // to offset by the first index of each group.
2710       for (unsigned i = 0; i != NumElts; ++i)
2711         Idxs[i] = ((Imm >> ((i * IdxSize) % 8)) & IdxMask) | (i & ~IdxMask);
2712 
2713       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2714 
2715       if (CI->getNumArgOperands() == 4)
2716         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2717                             CI->getArgOperand(2));
2718     } else if (IsX86 && (Name == "sse2.pshufl.w" ||
2719                          Name.startswith("avx512.mask.pshufl.w."))) {
2720       Value *Op0 = CI->getArgOperand(0);
2721       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2722       unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2723 
2724       SmallVector<int, 16> Idxs(NumElts);
2725       for (unsigned l = 0; l != NumElts; l += 8) {
2726         for (unsigned i = 0; i != 4; ++i)
2727           Idxs[i + l] = ((Imm >> (2 * i)) & 0x3) + l;
2728         for (unsigned i = 4; i != 8; ++i)
2729           Idxs[i + l] = i + l;
2730       }
2731 
2732       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2733 
2734       if (CI->getNumArgOperands() == 4)
2735         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2736                             CI->getArgOperand(2));
2737     } else if (IsX86 && (Name == "sse2.pshufh.w" ||
2738                          Name.startswith("avx512.mask.pshufh.w."))) {
2739       Value *Op0 = CI->getArgOperand(0);
2740       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2741       unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2742 
2743       SmallVector<int, 16> Idxs(NumElts);
2744       for (unsigned l = 0; l != NumElts; l += 8) {
2745         for (unsigned i = 0; i != 4; ++i)
2746           Idxs[i + l] = i + l;
2747         for (unsigned i = 0; i != 4; ++i)
2748           Idxs[i + l + 4] = ((Imm >> (2 * i)) & 0x3) + 4 + l;
2749       }
2750 
2751       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2752 
2753       if (CI->getNumArgOperands() == 4)
2754         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2755                             CI->getArgOperand(2));
2756     } else if (IsX86 && Name.startswith("avx512.mask.shuf.p")) {
2757       Value *Op0 = CI->getArgOperand(0);
2758       Value *Op1 = CI->getArgOperand(1);
2759       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2760       unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2761 
2762       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2763       unsigned HalfLaneElts = NumLaneElts / 2;
2764 
2765       SmallVector<int, 16> Idxs(NumElts);
2766       for (unsigned i = 0; i != NumElts; ++i) {
2767         // Base index is the starting element of the lane.
2768         Idxs[i] = i - (i % NumLaneElts);
2769         // If we are half way through the lane switch to the other source.
2770         if ((i % NumLaneElts) >= HalfLaneElts)
2771           Idxs[i] += NumElts;
2772         // Now select the specific element. By adding HalfLaneElts bits from
2773         // the immediate. Wrapping around the immediate every 8-bits.
2774         Idxs[i] += (Imm >> ((i * HalfLaneElts) % 8)) & ((1 << HalfLaneElts) - 1);
2775       }
2776 
2777       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2778 
2779       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2780                           CI->getArgOperand(3));
2781     } else if (IsX86 && (Name.startswith("avx512.mask.movddup") ||
2782                          Name.startswith("avx512.mask.movshdup") ||
2783                          Name.startswith("avx512.mask.movsldup"))) {
2784       Value *Op0 = CI->getArgOperand(0);
2785       unsigned NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2786       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2787 
2788       unsigned Offset = 0;
2789       if (Name.startswith("avx512.mask.movshdup."))
2790         Offset = 1;
2791 
2792       SmallVector<int, 16> Idxs(NumElts);
2793       for (unsigned l = 0; l != NumElts; l += NumLaneElts)
2794         for (unsigned i = 0; i != NumLaneElts; i += 2) {
2795           Idxs[i + l + 0] = i + l + Offset;
2796           Idxs[i + l + 1] = i + l + Offset;
2797         }
2798 
2799       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2800 
2801       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2802                           CI->getArgOperand(1));
2803     } else if (IsX86 && (Name.startswith("avx512.mask.punpckl") ||
2804                          Name.startswith("avx512.mask.unpckl."))) {
2805       Value *Op0 = CI->getArgOperand(0);
2806       Value *Op1 = CI->getArgOperand(1);
2807       int NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2808       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2809 
2810       SmallVector<int, 64> Idxs(NumElts);
2811       for (int l = 0; l != NumElts; l += NumLaneElts)
2812         for (int i = 0; i != NumLaneElts; ++i)
2813           Idxs[i + l] = l + (i / 2) + NumElts * (i % 2);
2814 
2815       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2816 
2817       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2818                           CI->getArgOperand(2));
2819     } else if (IsX86 && (Name.startswith("avx512.mask.punpckh") ||
2820                          Name.startswith("avx512.mask.unpckh."))) {
2821       Value *Op0 = CI->getArgOperand(0);
2822       Value *Op1 = CI->getArgOperand(1);
2823       int NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
2824       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2825 
2826       SmallVector<int, 64> Idxs(NumElts);
2827       for (int l = 0; l != NumElts; l += NumLaneElts)
2828         for (int i = 0; i != NumLaneElts; ++i)
2829           Idxs[i + l] = (NumLaneElts / 2) + l + (i / 2) + NumElts * (i % 2);
2830 
2831       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2832 
2833       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2834                           CI->getArgOperand(2));
2835     } else if (IsX86 && (Name.startswith("avx512.mask.and.") ||
2836                          Name.startswith("avx512.mask.pand."))) {
2837       VectorType *FTy = cast<VectorType>(CI->getType());
2838       VectorType *ITy = VectorType::getInteger(FTy);
2839       Rep = Builder.CreateAnd(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2840                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2841       Rep = Builder.CreateBitCast(Rep, FTy);
2842       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2843                           CI->getArgOperand(2));
2844     } else if (IsX86 && (Name.startswith("avx512.mask.andn.") ||
2845                          Name.startswith("avx512.mask.pandn."))) {
2846       VectorType *FTy = cast<VectorType>(CI->getType());
2847       VectorType *ITy = VectorType::getInteger(FTy);
2848       Rep = Builder.CreateNot(Builder.CreateBitCast(CI->getArgOperand(0), ITy));
2849       Rep = Builder.CreateAnd(Rep,
2850                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2851       Rep = Builder.CreateBitCast(Rep, FTy);
2852       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2853                           CI->getArgOperand(2));
2854     } else if (IsX86 && (Name.startswith("avx512.mask.or.") ||
2855                          Name.startswith("avx512.mask.por."))) {
2856       VectorType *FTy = cast<VectorType>(CI->getType());
2857       VectorType *ITy = VectorType::getInteger(FTy);
2858       Rep = Builder.CreateOr(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2859                              Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2860       Rep = Builder.CreateBitCast(Rep, FTy);
2861       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2862                           CI->getArgOperand(2));
2863     } else if (IsX86 && (Name.startswith("avx512.mask.xor.") ||
2864                          Name.startswith("avx512.mask.pxor."))) {
2865       VectorType *FTy = cast<VectorType>(CI->getType());
2866       VectorType *ITy = VectorType::getInteger(FTy);
2867       Rep = Builder.CreateXor(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2868                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2869       Rep = Builder.CreateBitCast(Rep, FTy);
2870       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2871                           CI->getArgOperand(2));
2872     } else if (IsX86 && Name.startswith("avx512.mask.padd.")) {
2873       Rep = Builder.CreateAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2874       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2875                           CI->getArgOperand(2));
2876     } else if (IsX86 && Name.startswith("avx512.mask.psub.")) {
2877       Rep = Builder.CreateSub(CI->getArgOperand(0), CI->getArgOperand(1));
2878       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2879                           CI->getArgOperand(2));
2880     } else if (IsX86 && Name.startswith("avx512.mask.pmull.")) {
2881       Rep = Builder.CreateMul(CI->getArgOperand(0), CI->getArgOperand(1));
2882       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2883                           CI->getArgOperand(2));
2884     } else if (IsX86 && Name.startswith("avx512.mask.add.p")) {
2885       if (Name.endswith(".512")) {
2886         Intrinsic::ID IID;
2887         if (Name[17] == 's')
2888           IID = Intrinsic::x86_avx512_add_ps_512;
2889         else
2890           IID = Intrinsic::x86_avx512_add_pd_512;
2891 
2892         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2893                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2894                                    CI->getArgOperand(4) });
2895       } else {
2896         Rep = Builder.CreateFAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2897       }
2898       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2899                           CI->getArgOperand(2));
2900     } else if (IsX86 && Name.startswith("avx512.mask.div.p")) {
2901       if (Name.endswith(".512")) {
2902         Intrinsic::ID IID;
2903         if (Name[17] == 's')
2904           IID = Intrinsic::x86_avx512_div_ps_512;
2905         else
2906           IID = Intrinsic::x86_avx512_div_pd_512;
2907 
2908         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2909                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2910                                    CI->getArgOperand(4) });
2911       } else {
2912         Rep = Builder.CreateFDiv(CI->getArgOperand(0), CI->getArgOperand(1));
2913       }
2914       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2915                           CI->getArgOperand(2));
2916     } else if (IsX86 && Name.startswith("avx512.mask.mul.p")) {
2917       if (Name.endswith(".512")) {
2918         Intrinsic::ID IID;
2919         if (Name[17] == 's')
2920           IID = Intrinsic::x86_avx512_mul_ps_512;
2921         else
2922           IID = Intrinsic::x86_avx512_mul_pd_512;
2923 
2924         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2925                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2926                                    CI->getArgOperand(4) });
2927       } else {
2928         Rep = Builder.CreateFMul(CI->getArgOperand(0), CI->getArgOperand(1));
2929       }
2930       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2931                           CI->getArgOperand(2));
2932     } else if (IsX86 && Name.startswith("avx512.mask.sub.p")) {
2933       if (Name.endswith(".512")) {
2934         Intrinsic::ID IID;
2935         if (Name[17] == 's')
2936           IID = Intrinsic::x86_avx512_sub_ps_512;
2937         else
2938           IID = Intrinsic::x86_avx512_sub_pd_512;
2939 
2940         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2941                                  { CI->getArgOperand(0), CI->getArgOperand(1),
2942                                    CI->getArgOperand(4) });
2943       } else {
2944         Rep = Builder.CreateFSub(CI->getArgOperand(0), CI->getArgOperand(1));
2945       }
2946       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2947                           CI->getArgOperand(2));
2948     } else if (IsX86 && (Name.startswith("avx512.mask.max.p") ||
2949                          Name.startswith("avx512.mask.min.p")) &&
2950                Name.drop_front(18) == ".512") {
2951       bool IsDouble = Name[17] == 'd';
2952       bool IsMin = Name[13] == 'i';
2953       static const Intrinsic::ID MinMaxTbl[2][2] = {
2954         { Intrinsic::x86_avx512_max_ps_512, Intrinsic::x86_avx512_max_pd_512 },
2955         { Intrinsic::x86_avx512_min_ps_512, Intrinsic::x86_avx512_min_pd_512 }
2956       };
2957       Intrinsic::ID IID = MinMaxTbl[IsMin][IsDouble];
2958 
2959       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
2960                                { CI->getArgOperand(0), CI->getArgOperand(1),
2961                                  CI->getArgOperand(4) });
2962       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2963                           CI->getArgOperand(2));
2964     } else if (IsX86 && Name.startswith("avx512.mask.lzcnt.")) {
2965       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
2966                                                          Intrinsic::ctlz,
2967                                                          CI->getType()),
2968                                { CI->getArgOperand(0), Builder.getInt1(false) });
2969       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2970                           CI->getArgOperand(1));
2971     } else if (IsX86 && Name.startswith("avx512.mask.psll")) {
2972       bool IsImmediate = Name[16] == 'i' ||
2973                          (Name.size() > 18 && Name[18] == 'i');
2974       bool IsVariable = Name[16] == 'v';
2975       char Size = Name[16] == '.' ? Name[17] :
2976                   Name[17] == '.' ? Name[18] :
2977                   Name[18] == '.' ? Name[19] :
2978                                     Name[20];
2979 
2980       Intrinsic::ID IID;
2981       if (IsVariable && Name[17] != '.') {
2982         if (Size == 'd' && Name[17] == '2') // avx512.mask.psllv2.di
2983           IID = Intrinsic::x86_avx2_psllv_q;
2984         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psllv4.di
2985           IID = Intrinsic::x86_avx2_psllv_q_256;
2986         else if (Size == 's' && Name[17] == '4') // avx512.mask.psllv4.si
2987           IID = Intrinsic::x86_avx2_psllv_d;
2988         else if (Size == 's' && Name[17] == '8') // avx512.mask.psllv8.si
2989           IID = Intrinsic::x86_avx2_psllv_d_256;
2990         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psllv8.hi
2991           IID = Intrinsic::x86_avx512_psllv_w_128;
2992         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psllv16.hi
2993           IID = Intrinsic::x86_avx512_psllv_w_256;
2994         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psllv32hi
2995           IID = Intrinsic::x86_avx512_psllv_w_512;
2996         else
2997           llvm_unreachable("Unexpected size");
2998       } else if (Name.endswith(".128")) {
2999         if (Size == 'd') // avx512.mask.psll.d.128, avx512.mask.psll.di.128
3000           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_d
3001                             : Intrinsic::x86_sse2_psll_d;
3002         else if (Size == 'q') // avx512.mask.psll.q.128, avx512.mask.psll.qi.128
3003           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_q
3004                             : Intrinsic::x86_sse2_psll_q;
3005         else if (Size == 'w') // avx512.mask.psll.w.128, avx512.mask.psll.wi.128
3006           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_w
3007                             : Intrinsic::x86_sse2_psll_w;
3008         else
3009           llvm_unreachable("Unexpected size");
3010       } else if (Name.endswith(".256")) {
3011         if (Size == 'd') // avx512.mask.psll.d.256, avx512.mask.psll.di.256
3012           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_d
3013                             : Intrinsic::x86_avx2_psll_d;
3014         else if (Size == 'q') // avx512.mask.psll.q.256, avx512.mask.psll.qi.256
3015           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_q
3016                             : Intrinsic::x86_avx2_psll_q;
3017         else if (Size == 'w') // avx512.mask.psll.w.256, avx512.mask.psll.wi.256
3018           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_w
3019                             : Intrinsic::x86_avx2_psll_w;
3020         else
3021           llvm_unreachable("Unexpected size");
3022       } else {
3023         if (Size == 'd') // psll.di.512, pslli.d, psll.d, psllv.d.512
3024           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_d_512 :
3025                 IsVariable  ? Intrinsic::x86_avx512_psllv_d_512 :
3026                               Intrinsic::x86_avx512_psll_d_512;
3027         else if (Size == 'q') // psll.qi.512, pslli.q, psll.q, psllv.q.512
3028           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_q_512 :
3029                 IsVariable  ? Intrinsic::x86_avx512_psllv_q_512 :
3030                               Intrinsic::x86_avx512_psll_q_512;
3031         else if (Size == 'w') // psll.wi.512, pslli.w, psll.w
3032           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_w_512
3033                             : Intrinsic::x86_avx512_psll_w_512;
3034         else
3035           llvm_unreachable("Unexpected size");
3036       }
3037 
3038       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
3039     } else if (IsX86 && Name.startswith("avx512.mask.psrl")) {
3040       bool IsImmediate = Name[16] == 'i' ||
3041                          (Name.size() > 18 && Name[18] == 'i');
3042       bool IsVariable = Name[16] == 'v';
3043       char Size = Name[16] == '.' ? Name[17] :
3044                   Name[17] == '.' ? Name[18] :
3045                   Name[18] == '.' ? Name[19] :
3046                                     Name[20];
3047 
3048       Intrinsic::ID IID;
3049       if (IsVariable && Name[17] != '.') {
3050         if (Size == 'd' && Name[17] == '2') // avx512.mask.psrlv2.di
3051           IID = Intrinsic::x86_avx2_psrlv_q;
3052         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psrlv4.di
3053           IID = Intrinsic::x86_avx2_psrlv_q_256;
3054         else if (Size == 's' && Name[17] == '4') // avx512.mask.psrlv4.si
3055           IID = Intrinsic::x86_avx2_psrlv_d;
3056         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrlv8.si
3057           IID = Intrinsic::x86_avx2_psrlv_d_256;
3058         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrlv8.hi
3059           IID = Intrinsic::x86_avx512_psrlv_w_128;
3060         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrlv16.hi
3061           IID = Intrinsic::x86_avx512_psrlv_w_256;
3062         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrlv32hi
3063           IID = Intrinsic::x86_avx512_psrlv_w_512;
3064         else
3065           llvm_unreachable("Unexpected size");
3066       } else if (Name.endswith(".128")) {
3067         if (Size == 'd') // avx512.mask.psrl.d.128, avx512.mask.psrl.di.128
3068           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_d
3069                             : Intrinsic::x86_sse2_psrl_d;
3070         else if (Size == 'q') // avx512.mask.psrl.q.128, avx512.mask.psrl.qi.128
3071           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_q
3072                             : Intrinsic::x86_sse2_psrl_q;
3073         else if (Size == 'w') // avx512.mask.psrl.w.128, avx512.mask.psrl.wi.128
3074           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_w
3075                             : Intrinsic::x86_sse2_psrl_w;
3076         else
3077           llvm_unreachable("Unexpected size");
3078       } else if (Name.endswith(".256")) {
3079         if (Size == 'd') // avx512.mask.psrl.d.256, avx512.mask.psrl.di.256
3080           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_d
3081                             : Intrinsic::x86_avx2_psrl_d;
3082         else if (Size == 'q') // avx512.mask.psrl.q.256, avx512.mask.psrl.qi.256
3083           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_q
3084                             : Intrinsic::x86_avx2_psrl_q;
3085         else if (Size == 'w') // avx512.mask.psrl.w.256, avx512.mask.psrl.wi.256
3086           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_w
3087                             : Intrinsic::x86_avx2_psrl_w;
3088         else
3089           llvm_unreachable("Unexpected size");
3090       } else {
3091         if (Size == 'd') // psrl.di.512, psrli.d, psrl.d, psrl.d.512
3092           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_d_512 :
3093                 IsVariable  ? Intrinsic::x86_avx512_psrlv_d_512 :
3094                               Intrinsic::x86_avx512_psrl_d_512;
3095         else if (Size == 'q') // psrl.qi.512, psrli.q, psrl.q, psrl.q.512
3096           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_q_512 :
3097                 IsVariable  ? Intrinsic::x86_avx512_psrlv_q_512 :
3098                               Intrinsic::x86_avx512_psrl_q_512;
3099         else if (Size == 'w') // psrl.wi.512, psrli.w, psrl.w)
3100           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_w_512
3101                             : Intrinsic::x86_avx512_psrl_w_512;
3102         else
3103           llvm_unreachable("Unexpected size");
3104       }
3105 
3106       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
3107     } else if (IsX86 && Name.startswith("avx512.mask.psra")) {
3108       bool IsImmediate = Name[16] == 'i' ||
3109                          (Name.size() > 18 && Name[18] == 'i');
3110       bool IsVariable = Name[16] == 'v';
3111       char Size = Name[16] == '.' ? Name[17] :
3112                   Name[17] == '.' ? Name[18] :
3113                   Name[18] == '.' ? Name[19] :
3114                                     Name[20];
3115 
3116       Intrinsic::ID IID;
3117       if (IsVariable && Name[17] != '.') {
3118         if (Size == 's' && Name[17] == '4') // avx512.mask.psrav4.si
3119           IID = Intrinsic::x86_avx2_psrav_d;
3120         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrav8.si
3121           IID = Intrinsic::x86_avx2_psrav_d_256;
3122         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrav8.hi
3123           IID = Intrinsic::x86_avx512_psrav_w_128;
3124         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrav16.hi
3125           IID = Intrinsic::x86_avx512_psrav_w_256;
3126         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrav32hi
3127           IID = Intrinsic::x86_avx512_psrav_w_512;
3128         else
3129           llvm_unreachable("Unexpected size");
3130       } else if (Name.endswith(".128")) {
3131         if (Size == 'd') // avx512.mask.psra.d.128, avx512.mask.psra.di.128
3132           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_d
3133                             : Intrinsic::x86_sse2_psra_d;
3134         else if (Size == 'q') // avx512.mask.psra.q.128, avx512.mask.psra.qi.128
3135           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_128 :
3136                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_128 :
3137                               Intrinsic::x86_avx512_psra_q_128;
3138         else if (Size == 'w') // avx512.mask.psra.w.128, avx512.mask.psra.wi.128
3139           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_w
3140                             : Intrinsic::x86_sse2_psra_w;
3141         else
3142           llvm_unreachable("Unexpected size");
3143       } else if (Name.endswith(".256")) {
3144         if (Size == 'd') // avx512.mask.psra.d.256, avx512.mask.psra.di.256
3145           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_d
3146                             : Intrinsic::x86_avx2_psra_d;
3147         else if (Size == 'q') // avx512.mask.psra.q.256, avx512.mask.psra.qi.256
3148           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_256 :
3149                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_256 :
3150                               Intrinsic::x86_avx512_psra_q_256;
3151         else if (Size == 'w') // avx512.mask.psra.w.256, avx512.mask.psra.wi.256
3152           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_w
3153                             : Intrinsic::x86_avx2_psra_w;
3154         else
3155           llvm_unreachable("Unexpected size");
3156       } else {
3157         if (Size == 'd') // psra.di.512, psrai.d, psra.d, psrav.d.512
3158           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_d_512 :
3159                 IsVariable  ? Intrinsic::x86_avx512_psrav_d_512 :
3160                               Intrinsic::x86_avx512_psra_d_512;
3161         else if (Size == 'q') // psra.qi.512, psrai.q, psra.q
3162           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_512 :
3163                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_512 :
3164                               Intrinsic::x86_avx512_psra_q_512;
3165         else if (Size == 'w') // psra.wi.512, psrai.w, psra.w
3166           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_w_512
3167                             : Intrinsic::x86_avx512_psra_w_512;
3168         else
3169           llvm_unreachable("Unexpected size");
3170       }
3171 
3172       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
3173     } else if (IsX86 && Name.startswith("avx512.mask.move.s")) {
3174       Rep = upgradeMaskedMove(Builder, *CI);
3175     } else if (IsX86 && Name.startswith("avx512.cvtmask2")) {
3176       Rep = UpgradeMaskToInt(Builder, *CI);
3177     } else if (IsX86 && Name.endswith(".movntdqa")) {
3178       Module *M = F->getParent();
3179       MDNode *Node = MDNode::get(
3180           C, ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
3181 
3182       Value *Ptr = CI->getArgOperand(0);
3183 
3184       // Convert the type of the pointer to a pointer to the stored type.
3185       Value *BC = Builder.CreateBitCast(
3186           Ptr, PointerType::getUnqual(CI->getType()), "cast");
3187       LoadInst *LI = Builder.CreateAlignedLoad(
3188           CI->getType(), BC,
3189           Align(CI->getType()->getPrimitiveSizeInBits().getFixedSize() / 8));
3190       LI->setMetadata(M->getMDKindID("nontemporal"), Node);
3191       Rep = LI;
3192     } else if (IsX86 && (Name.startswith("fma.vfmadd.") ||
3193                          Name.startswith("fma.vfmsub.") ||
3194                          Name.startswith("fma.vfnmadd.") ||
3195                          Name.startswith("fma.vfnmsub."))) {
3196       bool NegMul = Name[6] == 'n';
3197       bool NegAcc = NegMul ? Name[8] == 's' : Name[7] == 's';
3198       bool IsScalar = NegMul ? Name[12] == 's' : Name[11] == 's';
3199 
3200       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3201                        CI->getArgOperand(2) };
3202 
3203       if (IsScalar) {
3204         Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3205         Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3206         Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3207       }
3208 
3209       if (NegMul && !IsScalar)
3210         Ops[0] = Builder.CreateFNeg(Ops[0]);
3211       if (NegMul && IsScalar)
3212         Ops[1] = Builder.CreateFNeg(Ops[1]);
3213       if (NegAcc)
3214         Ops[2] = Builder.CreateFNeg(Ops[2]);
3215 
3216       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3217                                                          Intrinsic::fma,
3218                                                          Ops[0]->getType()),
3219                                Ops);
3220 
3221       if (IsScalar)
3222         Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep,
3223                                           (uint64_t)0);
3224     } else if (IsX86 && Name.startswith("fma4.vfmadd.s")) {
3225       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3226                        CI->getArgOperand(2) };
3227 
3228       Ops[0] = Builder.CreateExtractElement(Ops[0], (uint64_t)0);
3229       Ops[1] = Builder.CreateExtractElement(Ops[1], (uint64_t)0);
3230       Ops[2] = Builder.CreateExtractElement(Ops[2], (uint64_t)0);
3231 
3232       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(),
3233                                                          Intrinsic::fma,
3234                                                          Ops[0]->getType()),
3235                                Ops);
3236 
3237       Rep = Builder.CreateInsertElement(Constant::getNullValue(CI->getType()),
3238                                         Rep, (uint64_t)0);
3239     } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.s") ||
3240                          Name.startswith("avx512.maskz.vfmadd.s") ||
3241                          Name.startswith("avx512.mask3.vfmadd.s") ||
3242                          Name.startswith("avx512.mask3.vfmsub.s") ||
3243                          Name.startswith("avx512.mask3.vfnmsub.s"))) {
3244       bool IsMask3 = Name[11] == '3';
3245       bool IsMaskZ = Name[11] == 'z';
3246       // Drop the "avx512.mask." to make it easier.
3247       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3248       bool NegMul = Name[2] == 'n';
3249       bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3250 
3251       Value *A = CI->getArgOperand(0);
3252       Value *B = CI->getArgOperand(1);
3253       Value *C = CI->getArgOperand(2);
3254 
3255       if (NegMul && (IsMask3 || IsMaskZ))
3256         A = Builder.CreateFNeg(A);
3257       if (NegMul && !(IsMask3 || IsMaskZ))
3258         B = Builder.CreateFNeg(B);
3259       if (NegAcc)
3260         C = Builder.CreateFNeg(C);
3261 
3262       A = Builder.CreateExtractElement(A, (uint64_t)0);
3263       B = Builder.CreateExtractElement(B, (uint64_t)0);
3264       C = Builder.CreateExtractElement(C, (uint64_t)0);
3265 
3266       if (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3267           cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4) {
3268         Value *Ops[] = { A, B, C, CI->getArgOperand(4) };
3269 
3270         Intrinsic::ID IID;
3271         if (Name.back() == 'd')
3272           IID = Intrinsic::x86_avx512_vfmadd_f64;
3273         else
3274           IID = Intrinsic::x86_avx512_vfmadd_f32;
3275         Function *FMA = Intrinsic::getDeclaration(CI->getModule(), IID);
3276         Rep = Builder.CreateCall(FMA, Ops);
3277       } else {
3278         Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3279                                                   Intrinsic::fma,
3280                                                   A->getType());
3281         Rep = Builder.CreateCall(FMA, { A, B, C });
3282       }
3283 
3284       Value *PassThru = IsMaskZ ? Constant::getNullValue(Rep->getType()) :
3285                         IsMask3 ? C : A;
3286 
3287       // For Mask3 with NegAcc, we need to create a new extractelement that
3288       // avoids the negation above.
3289       if (NegAcc && IsMask3)
3290         PassThru = Builder.CreateExtractElement(CI->getArgOperand(2),
3291                                                 (uint64_t)0);
3292 
3293       Rep = EmitX86ScalarSelect(Builder, CI->getArgOperand(3),
3294                                 Rep, PassThru);
3295       Rep = Builder.CreateInsertElement(CI->getArgOperand(IsMask3 ? 2 : 0),
3296                                         Rep, (uint64_t)0);
3297     } else if (IsX86 && (Name.startswith("avx512.mask.vfmadd.p") ||
3298                          Name.startswith("avx512.mask.vfnmadd.p") ||
3299                          Name.startswith("avx512.mask.vfnmsub.p") ||
3300                          Name.startswith("avx512.mask3.vfmadd.p") ||
3301                          Name.startswith("avx512.mask3.vfmsub.p") ||
3302                          Name.startswith("avx512.mask3.vfnmsub.p") ||
3303                          Name.startswith("avx512.maskz.vfmadd.p"))) {
3304       bool IsMask3 = Name[11] == '3';
3305       bool IsMaskZ = Name[11] == 'z';
3306       // Drop the "avx512.mask." to make it easier.
3307       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3308       bool NegMul = Name[2] == 'n';
3309       bool NegAcc = NegMul ? Name[4] == 's' : Name[3] == 's';
3310 
3311       Value *A = CI->getArgOperand(0);
3312       Value *B = CI->getArgOperand(1);
3313       Value *C = CI->getArgOperand(2);
3314 
3315       if (NegMul && (IsMask3 || IsMaskZ))
3316         A = Builder.CreateFNeg(A);
3317       if (NegMul && !(IsMask3 || IsMaskZ))
3318         B = Builder.CreateFNeg(B);
3319       if (NegAcc)
3320         C = Builder.CreateFNeg(C);
3321 
3322       if (CI->getNumArgOperands() == 5 &&
3323           (!isa<ConstantInt>(CI->getArgOperand(4)) ||
3324            cast<ConstantInt>(CI->getArgOperand(4))->getZExtValue() != 4)) {
3325         Intrinsic::ID IID;
3326         // Check the character before ".512" in string.
3327         if (Name[Name.size()-5] == 's')
3328           IID = Intrinsic::x86_avx512_vfmadd_ps_512;
3329         else
3330           IID = Intrinsic::x86_avx512_vfmadd_pd_512;
3331 
3332         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3333                                  { A, B, C, CI->getArgOperand(4) });
3334       } else {
3335         Function *FMA = Intrinsic::getDeclaration(CI->getModule(),
3336                                                   Intrinsic::fma,
3337                                                   A->getType());
3338         Rep = Builder.CreateCall(FMA, { A, B, C });
3339       }
3340 
3341       Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3342                         IsMask3 ? CI->getArgOperand(2) :
3343                                   CI->getArgOperand(0);
3344 
3345       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3346     } else if (IsX86 &&  Name.startswith("fma.vfmsubadd.p")) {
3347       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3348       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
3349       Intrinsic::ID IID;
3350       if (VecWidth == 128 && EltWidth == 32)
3351         IID = Intrinsic::x86_fma_vfmaddsub_ps;
3352       else if (VecWidth == 256 && EltWidth == 32)
3353         IID = Intrinsic::x86_fma_vfmaddsub_ps_256;
3354       else if (VecWidth == 128 && EltWidth == 64)
3355         IID = Intrinsic::x86_fma_vfmaddsub_pd;
3356       else if (VecWidth == 256 && EltWidth == 64)
3357         IID = Intrinsic::x86_fma_vfmaddsub_pd_256;
3358       else
3359         llvm_unreachable("Unexpected intrinsic");
3360 
3361       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3362                        CI->getArgOperand(2) };
3363       Ops[2] = Builder.CreateFNeg(Ops[2]);
3364       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3365                                Ops);
3366     } else if (IsX86 && (Name.startswith("avx512.mask.vfmaddsub.p") ||
3367                          Name.startswith("avx512.mask3.vfmaddsub.p") ||
3368                          Name.startswith("avx512.maskz.vfmaddsub.p") ||
3369                          Name.startswith("avx512.mask3.vfmsubadd.p"))) {
3370       bool IsMask3 = Name[11] == '3';
3371       bool IsMaskZ = Name[11] == 'z';
3372       // Drop the "avx512.mask." to make it easier.
3373       Name = Name.drop_front(IsMask3 || IsMaskZ ? 13 : 12);
3374       bool IsSubAdd = Name[3] == 's';
3375       if (CI->getNumArgOperands() == 5) {
3376         Intrinsic::ID IID;
3377         // Check the character before ".512" in string.
3378         if (Name[Name.size()-5] == 's')
3379           IID = Intrinsic::x86_avx512_vfmaddsub_ps_512;
3380         else
3381           IID = Intrinsic::x86_avx512_vfmaddsub_pd_512;
3382 
3383         Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3384                          CI->getArgOperand(2), CI->getArgOperand(4) };
3385         if (IsSubAdd)
3386           Ops[2] = Builder.CreateFNeg(Ops[2]);
3387 
3388         Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(), IID),
3389                                  Ops);
3390       } else {
3391         int NumElts = cast<FixedVectorType>(CI->getType())->getNumElements();
3392 
3393         Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3394                          CI->getArgOperand(2) };
3395 
3396         Function *FMA = Intrinsic::getDeclaration(CI->getModule(), Intrinsic::fma,
3397                                                   Ops[0]->getType());
3398         Value *Odd = Builder.CreateCall(FMA, Ops);
3399         Ops[2] = Builder.CreateFNeg(Ops[2]);
3400         Value *Even = Builder.CreateCall(FMA, Ops);
3401 
3402         if (IsSubAdd)
3403           std::swap(Even, Odd);
3404 
3405         SmallVector<int, 32> Idxs(NumElts);
3406         for (int i = 0; i != NumElts; ++i)
3407           Idxs[i] = i + (i % 2) * NumElts;
3408 
3409         Rep = Builder.CreateShuffleVector(Even, Odd, Idxs);
3410       }
3411 
3412       Value *PassThru = IsMaskZ ? llvm::Constant::getNullValue(CI->getType()) :
3413                         IsMask3 ? CI->getArgOperand(2) :
3414                                   CI->getArgOperand(0);
3415 
3416       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3417     } else if (IsX86 && (Name.startswith("avx512.mask.pternlog.") ||
3418                          Name.startswith("avx512.maskz.pternlog."))) {
3419       bool ZeroMask = Name[11] == 'z';
3420       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3421       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
3422       Intrinsic::ID IID;
3423       if (VecWidth == 128 && EltWidth == 32)
3424         IID = Intrinsic::x86_avx512_pternlog_d_128;
3425       else if (VecWidth == 256 && EltWidth == 32)
3426         IID = Intrinsic::x86_avx512_pternlog_d_256;
3427       else if (VecWidth == 512 && EltWidth == 32)
3428         IID = Intrinsic::x86_avx512_pternlog_d_512;
3429       else if (VecWidth == 128 && EltWidth == 64)
3430         IID = Intrinsic::x86_avx512_pternlog_q_128;
3431       else if (VecWidth == 256 && EltWidth == 64)
3432         IID = Intrinsic::x86_avx512_pternlog_q_256;
3433       else if (VecWidth == 512 && EltWidth == 64)
3434         IID = Intrinsic::x86_avx512_pternlog_q_512;
3435       else
3436         llvm_unreachable("Unexpected intrinsic");
3437 
3438       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3439                         CI->getArgOperand(2), CI->getArgOperand(3) };
3440       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3441                                Args);
3442       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3443                                  : CI->getArgOperand(0);
3444       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep, PassThru);
3445     } else if (IsX86 && (Name.startswith("avx512.mask.vpmadd52") ||
3446                          Name.startswith("avx512.maskz.vpmadd52"))) {
3447       bool ZeroMask = Name[11] == 'z';
3448       bool High = Name[20] == 'h' || Name[21] == 'h';
3449       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3450       Intrinsic::ID IID;
3451       if (VecWidth == 128 && !High)
3452         IID = Intrinsic::x86_avx512_vpmadd52l_uq_128;
3453       else if (VecWidth == 256 && !High)
3454         IID = Intrinsic::x86_avx512_vpmadd52l_uq_256;
3455       else if (VecWidth == 512 && !High)
3456         IID = Intrinsic::x86_avx512_vpmadd52l_uq_512;
3457       else if (VecWidth == 128 && High)
3458         IID = Intrinsic::x86_avx512_vpmadd52h_uq_128;
3459       else if (VecWidth == 256 && High)
3460         IID = Intrinsic::x86_avx512_vpmadd52h_uq_256;
3461       else if (VecWidth == 512 && High)
3462         IID = Intrinsic::x86_avx512_vpmadd52h_uq_512;
3463       else
3464         llvm_unreachable("Unexpected intrinsic");
3465 
3466       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
3467                         CI->getArgOperand(2) };
3468       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3469                                Args);
3470       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3471                                  : CI->getArgOperand(0);
3472       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3473     } else if (IsX86 && (Name.startswith("avx512.mask.vpermi2var.") ||
3474                          Name.startswith("avx512.mask.vpermt2var.") ||
3475                          Name.startswith("avx512.maskz.vpermt2var."))) {
3476       bool ZeroMask = Name[11] == 'z';
3477       bool IndexForm = Name[17] == 'i';
3478       Rep = UpgradeX86VPERMT2Intrinsics(Builder, *CI, ZeroMask, IndexForm);
3479     } else if (IsX86 && (Name.startswith("avx512.mask.vpdpbusd.") ||
3480                          Name.startswith("avx512.maskz.vpdpbusd.") ||
3481                          Name.startswith("avx512.mask.vpdpbusds.") ||
3482                          Name.startswith("avx512.maskz.vpdpbusds."))) {
3483       bool ZeroMask = Name[11] == 'z';
3484       bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3485       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3486       Intrinsic::ID IID;
3487       if (VecWidth == 128 && !IsSaturating)
3488         IID = Intrinsic::x86_avx512_vpdpbusd_128;
3489       else if (VecWidth == 256 && !IsSaturating)
3490         IID = Intrinsic::x86_avx512_vpdpbusd_256;
3491       else if (VecWidth == 512 && !IsSaturating)
3492         IID = Intrinsic::x86_avx512_vpdpbusd_512;
3493       else if (VecWidth == 128 && IsSaturating)
3494         IID = Intrinsic::x86_avx512_vpdpbusds_128;
3495       else if (VecWidth == 256 && IsSaturating)
3496         IID = Intrinsic::x86_avx512_vpdpbusds_256;
3497       else if (VecWidth == 512 && IsSaturating)
3498         IID = Intrinsic::x86_avx512_vpdpbusds_512;
3499       else
3500         llvm_unreachable("Unexpected intrinsic");
3501 
3502       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3503                         CI->getArgOperand(2)  };
3504       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3505                                Args);
3506       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3507                                  : CI->getArgOperand(0);
3508       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3509     } else if (IsX86 && (Name.startswith("avx512.mask.vpdpwssd.") ||
3510                          Name.startswith("avx512.maskz.vpdpwssd.") ||
3511                          Name.startswith("avx512.mask.vpdpwssds.") ||
3512                          Name.startswith("avx512.maskz.vpdpwssds."))) {
3513       bool ZeroMask = Name[11] == 'z';
3514       bool IsSaturating = Name[ZeroMask ? 21 : 20] == 's';
3515       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
3516       Intrinsic::ID IID;
3517       if (VecWidth == 128 && !IsSaturating)
3518         IID = Intrinsic::x86_avx512_vpdpwssd_128;
3519       else if (VecWidth == 256 && !IsSaturating)
3520         IID = Intrinsic::x86_avx512_vpdpwssd_256;
3521       else if (VecWidth == 512 && !IsSaturating)
3522         IID = Intrinsic::x86_avx512_vpdpwssd_512;
3523       else if (VecWidth == 128 && IsSaturating)
3524         IID = Intrinsic::x86_avx512_vpdpwssds_128;
3525       else if (VecWidth == 256 && IsSaturating)
3526         IID = Intrinsic::x86_avx512_vpdpwssds_256;
3527       else if (VecWidth == 512 && IsSaturating)
3528         IID = Intrinsic::x86_avx512_vpdpwssds_512;
3529       else
3530         llvm_unreachable("Unexpected intrinsic");
3531 
3532       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3533                         CI->getArgOperand(2)  };
3534       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
3535                                Args);
3536       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
3537                                  : CI->getArgOperand(0);
3538       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
3539     } else if (IsX86 && (Name == "addcarryx.u32" || Name == "addcarryx.u64" ||
3540                          Name == "addcarry.u32" || Name == "addcarry.u64" ||
3541                          Name == "subborrow.u32" || Name == "subborrow.u64")) {
3542       Intrinsic::ID IID;
3543       if (Name[0] == 'a' && Name.back() == '2')
3544         IID = Intrinsic::x86_addcarry_32;
3545       else if (Name[0] == 'a' && Name.back() == '4')
3546         IID = Intrinsic::x86_addcarry_64;
3547       else if (Name[0] == 's' && Name.back() == '2')
3548         IID = Intrinsic::x86_subborrow_32;
3549       else if (Name[0] == 's' && Name.back() == '4')
3550         IID = Intrinsic::x86_subborrow_64;
3551       else
3552         llvm_unreachable("Unexpected intrinsic");
3553 
3554       // Make a call with 3 operands.
3555       Value *Args[] = { CI->getArgOperand(0), CI->getArgOperand(1),
3556                         CI->getArgOperand(2)};
3557       Value *NewCall = Builder.CreateCall(
3558                                 Intrinsic::getDeclaration(CI->getModule(), IID),
3559                                 Args);
3560 
3561       // Extract the second result and store it.
3562       Value *Data = Builder.CreateExtractValue(NewCall, 1);
3563       // Cast the pointer to the right type.
3564       Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(3),
3565                                  llvm::PointerType::getUnqual(Data->getType()));
3566       Builder.CreateAlignedStore(Data, Ptr, Align(1));
3567       // Replace the original call result with the first result of the new call.
3568       Value *CF = Builder.CreateExtractValue(NewCall, 0);
3569 
3570       CI->replaceAllUsesWith(CF);
3571       Rep = nullptr;
3572     } else if (IsX86 && Name.startswith("avx512.mask.") &&
3573                upgradeAVX512MaskToSelect(Name, Builder, *CI, Rep)) {
3574       // Rep will be updated by the call in the condition.
3575     } else if (IsNVVM && (Name == "abs.i" || Name == "abs.ll")) {
3576       Value *Arg = CI->getArgOperand(0);
3577       Value *Neg = Builder.CreateNeg(Arg, "neg");
3578       Value *Cmp = Builder.CreateICmpSGE(
3579           Arg, llvm::Constant::getNullValue(Arg->getType()), "abs.cond");
3580       Rep = Builder.CreateSelect(Cmp, Arg, Neg, "abs");
3581     } else if (IsNVVM && (Name.startswith("atomic.load.add.f32.p") ||
3582                           Name.startswith("atomic.load.add.f64.p"))) {
3583       Value *Ptr = CI->getArgOperand(0);
3584       Value *Val = CI->getArgOperand(1);
3585       Rep = Builder.CreateAtomicRMW(AtomicRMWInst::FAdd, Ptr, Val,
3586                                     AtomicOrdering::SequentiallyConsistent);
3587     } else if (IsNVVM && (Name == "max.i" || Name == "max.ll" ||
3588                           Name == "max.ui" || Name == "max.ull")) {
3589       Value *Arg0 = CI->getArgOperand(0);
3590       Value *Arg1 = CI->getArgOperand(1);
3591       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3592                        ? Builder.CreateICmpUGE(Arg0, Arg1, "max.cond")
3593                        : Builder.CreateICmpSGE(Arg0, Arg1, "max.cond");
3594       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "max");
3595     } else if (IsNVVM && (Name == "min.i" || Name == "min.ll" ||
3596                           Name == "min.ui" || Name == "min.ull")) {
3597       Value *Arg0 = CI->getArgOperand(0);
3598       Value *Arg1 = CI->getArgOperand(1);
3599       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
3600                        ? Builder.CreateICmpULE(Arg0, Arg1, "min.cond")
3601                        : Builder.CreateICmpSLE(Arg0, Arg1, "min.cond");
3602       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "min");
3603     } else if (IsNVVM && Name == "clz.ll") {
3604       // llvm.nvvm.clz.ll returns an i32, but llvm.ctlz.i64 and returns an i64.
3605       Value *Arg = CI->getArgOperand(0);
3606       Value *Ctlz = Builder.CreateCall(
3607           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
3608                                     {Arg->getType()}),
3609           {Arg, Builder.getFalse()}, "ctlz");
3610       Rep = Builder.CreateTrunc(Ctlz, Builder.getInt32Ty(), "ctlz.trunc");
3611     } else if (IsNVVM && Name == "popc.ll") {
3612       // llvm.nvvm.popc.ll returns an i32, but llvm.ctpop.i64 and returns an
3613       // i64.
3614       Value *Arg = CI->getArgOperand(0);
3615       Value *Popc = Builder.CreateCall(
3616           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
3617                                     {Arg->getType()}),
3618           Arg, "ctpop");
3619       Rep = Builder.CreateTrunc(Popc, Builder.getInt32Ty(), "ctpop.trunc");
3620     } else if (IsNVVM && Name == "h2f") {
3621       Rep = Builder.CreateCall(Intrinsic::getDeclaration(
3622                                    F->getParent(), Intrinsic::convert_from_fp16,
3623                                    {Builder.getFloatTy()}),
3624                                CI->getArgOperand(0), "h2f");
3625     } else {
3626       llvm_unreachable("Unknown function for CallInst upgrade.");
3627     }
3628 
3629     if (Rep)
3630       CI->replaceAllUsesWith(Rep);
3631     CI->eraseFromParent();
3632     return;
3633   }
3634 
3635   const auto &DefaultCase = [&NewFn, &CI]() -> void {
3636     // Handle generic mangling change, but nothing else
3637     assert(
3638         (CI->getCalledFunction()->getName() != NewFn->getName()) &&
3639         "Unknown function for CallInst upgrade and isn't just a name change");
3640     CI->setCalledFunction(NewFn);
3641   };
3642   CallInst *NewCall = nullptr;
3643   switch (NewFn->getIntrinsicID()) {
3644   default: {
3645     DefaultCase();
3646     return;
3647   }
3648   case Intrinsic::arm_neon_vld1:
3649   case Intrinsic::arm_neon_vld2:
3650   case Intrinsic::arm_neon_vld3:
3651   case Intrinsic::arm_neon_vld4:
3652   case Intrinsic::arm_neon_vld2lane:
3653   case Intrinsic::arm_neon_vld3lane:
3654   case Intrinsic::arm_neon_vld4lane:
3655   case Intrinsic::arm_neon_vst1:
3656   case Intrinsic::arm_neon_vst2:
3657   case Intrinsic::arm_neon_vst3:
3658   case Intrinsic::arm_neon_vst4:
3659   case Intrinsic::arm_neon_vst2lane:
3660   case Intrinsic::arm_neon_vst3lane:
3661   case Intrinsic::arm_neon_vst4lane: {
3662     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3663                                  CI->arg_operands().end());
3664     NewCall = Builder.CreateCall(NewFn, Args);
3665     break;
3666   }
3667 
3668   case Intrinsic::arm_neon_bfdot:
3669   case Intrinsic::arm_neon_bfmmla:
3670   case Intrinsic::arm_neon_bfmlalb:
3671   case Intrinsic::arm_neon_bfmlalt:
3672   case Intrinsic::aarch64_neon_bfdot:
3673   case Intrinsic::aarch64_neon_bfmmla:
3674   case Intrinsic::aarch64_neon_bfmlalb:
3675   case Intrinsic::aarch64_neon_bfmlalt: {
3676     SmallVector<Value *, 3> Args;
3677     assert(CI->getNumArgOperands() == 3 &&
3678            "Mismatch between function args and call args");
3679     size_t OperandWidth =
3680         CI->getArgOperand(1)->getType()->getPrimitiveSizeInBits();
3681     assert((OperandWidth == 64 || OperandWidth == 128) &&
3682            "Unexpected operand width");
3683     Type *NewTy = FixedVectorType::get(Type::getBFloatTy(C), OperandWidth / 16);
3684     auto Iter = CI->arg_operands().begin();
3685     Args.push_back(*Iter++);
3686     Args.push_back(Builder.CreateBitCast(*Iter++, NewTy));
3687     Args.push_back(Builder.CreateBitCast(*Iter++, NewTy));
3688     NewCall = Builder.CreateCall(NewFn, Args);
3689     break;
3690   }
3691 
3692   case Intrinsic::bitreverse:
3693     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3694     break;
3695 
3696   case Intrinsic::ctlz:
3697   case Intrinsic::cttz:
3698     assert(CI->getNumArgOperands() == 1 &&
3699            "Mismatch between function args and call args");
3700     NewCall =
3701         Builder.CreateCall(NewFn, {CI->getArgOperand(0), Builder.getFalse()});
3702     break;
3703 
3704   case Intrinsic::objectsize: {
3705     Value *NullIsUnknownSize = CI->getNumArgOperands() == 2
3706                                    ? Builder.getFalse()
3707                                    : CI->getArgOperand(2);
3708     Value *Dynamic =
3709         CI->getNumArgOperands() < 4 ? Builder.getFalse() : CI->getArgOperand(3);
3710     NewCall = Builder.CreateCall(
3711         NewFn, {CI->getArgOperand(0), CI->getArgOperand(1), NullIsUnknownSize, Dynamic});
3712     break;
3713   }
3714 
3715   case Intrinsic::ctpop:
3716     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3717     break;
3718 
3719   case Intrinsic::convert_from_fp16:
3720     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
3721     break;
3722 
3723   case Intrinsic::dbg_value:
3724     // Upgrade from the old version that had an extra offset argument.
3725     assert(CI->getNumArgOperands() == 4);
3726     // Drop nonzero offsets instead of attempting to upgrade them.
3727     if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
3728       if (Offset->isZeroValue()) {
3729         NewCall = Builder.CreateCall(
3730             NewFn,
3731             {CI->getArgOperand(0), CI->getArgOperand(2), CI->getArgOperand(3)});
3732         break;
3733       }
3734     CI->eraseFromParent();
3735     return;
3736 
3737   case Intrinsic::x86_xop_vfrcz_ss:
3738   case Intrinsic::x86_xop_vfrcz_sd:
3739     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(1)});
3740     break;
3741 
3742   case Intrinsic::x86_xop_vpermil2pd:
3743   case Intrinsic::x86_xop_vpermil2ps:
3744   case Intrinsic::x86_xop_vpermil2pd_256:
3745   case Intrinsic::x86_xop_vpermil2ps_256: {
3746     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3747                                  CI->arg_operands().end());
3748     VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
3749     VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
3750     Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
3751     NewCall = Builder.CreateCall(NewFn, Args);
3752     break;
3753   }
3754 
3755   case Intrinsic::x86_sse41_ptestc:
3756   case Intrinsic::x86_sse41_ptestz:
3757   case Intrinsic::x86_sse41_ptestnzc: {
3758     // The arguments for these intrinsics used to be v4f32, and changed
3759     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
3760     // So, the only thing required is a bitcast for both arguments.
3761     // First, check the arguments have the old type.
3762     Value *Arg0 = CI->getArgOperand(0);
3763     if (Arg0->getType() != FixedVectorType::get(Type::getFloatTy(C), 4))
3764       return;
3765 
3766     // Old intrinsic, add bitcasts
3767     Value *Arg1 = CI->getArgOperand(1);
3768 
3769     auto *NewVecTy = FixedVectorType::get(Type::getInt64Ty(C), 2);
3770 
3771     Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
3772     Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
3773 
3774     NewCall = Builder.CreateCall(NewFn, {BC0, BC1});
3775     break;
3776   }
3777 
3778   case Intrinsic::x86_rdtscp: {
3779     // This used to take 1 arguments. If we have no arguments, it is already
3780     // upgraded.
3781     if (CI->getNumOperands() == 0)
3782       return;
3783 
3784     NewCall = Builder.CreateCall(NewFn);
3785     // Extract the second result and store it.
3786     Value *Data = Builder.CreateExtractValue(NewCall, 1);
3787     // Cast the pointer to the right type.
3788     Value *Ptr = Builder.CreateBitCast(CI->getArgOperand(0),
3789                                  llvm::PointerType::getUnqual(Data->getType()));
3790     Builder.CreateAlignedStore(Data, Ptr, Align(1));
3791     // Replace the original call result with the first result of the new call.
3792     Value *TSC = Builder.CreateExtractValue(NewCall, 0);
3793 
3794     NewCall->takeName(CI);
3795     CI->replaceAllUsesWith(TSC);
3796     CI->eraseFromParent();
3797     return;
3798   }
3799 
3800   case Intrinsic::x86_sse41_insertps:
3801   case Intrinsic::x86_sse41_dppd:
3802   case Intrinsic::x86_sse41_dpps:
3803   case Intrinsic::x86_sse41_mpsadbw:
3804   case Intrinsic::x86_avx_dp_ps_256:
3805   case Intrinsic::x86_avx2_mpsadbw: {
3806     // Need to truncate the last argument from i32 to i8 -- this argument models
3807     // an inherently 8-bit immediate operand to these x86 instructions.
3808     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3809                                  CI->arg_operands().end());
3810 
3811     // Replace the last argument with a trunc.
3812     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
3813     NewCall = Builder.CreateCall(NewFn, Args);
3814     break;
3815   }
3816 
3817   case Intrinsic::x86_avx512_mask_cmp_pd_128:
3818   case Intrinsic::x86_avx512_mask_cmp_pd_256:
3819   case Intrinsic::x86_avx512_mask_cmp_pd_512:
3820   case Intrinsic::x86_avx512_mask_cmp_ps_128:
3821   case Intrinsic::x86_avx512_mask_cmp_ps_256:
3822   case Intrinsic::x86_avx512_mask_cmp_ps_512: {
3823     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3824                                  CI->arg_operands().end());
3825     unsigned NumElts =
3826         cast<FixedVectorType>(Args[0]->getType())->getNumElements();
3827     Args[3] = getX86MaskVec(Builder, Args[3], NumElts);
3828 
3829     NewCall = Builder.CreateCall(NewFn, Args);
3830     Value *Res = ApplyX86MaskOn1BitsVec(Builder, NewCall, nullptr);
3831 
3832     NewCall->takeName(CI);
3833     CI->replaceAllUsesWith(Res);
3834     CI->eraseFromParent();
3835     return;
3836   }
3837 
3838   case Intrinsic::thread_pointer: {
3839     NewCall = Builder.CreateCall(NewFn, {});
3840     break;
3841   }
3842 
3843   case Intrinsic::invariant_start:
3844   case Intrinsic::invariant_end:
3845   case Intrinsic::masked_load:
3846   case Intrinsic::masked_store:
3847   case Intrinsic::masked_gather:
3848   case Intrinsic::masked_scatter: {
3849     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
3850                                  CI->arg_operands().end());
3851     NewCall = Builder.CreateCall(NewFn, Args);
3852     break;
3853   }
3854 
3855   case Intrinsic::memcpy:
3856   case Intrinsic::memmove:
3857   case Intrinsic::memset: {
3858     // We have to make sure that the call signature is what we're expecting.
3859     // We only want to change the old signatures by removing the alignment arg:
3860     //  @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i32, i1)
3861     //    -> @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i1)
3862     //  @llvm.memset...(i8*, i8, i[32|64], i32, i1)
3863     //    -> @llvm.memset...(i8*, i8, i[32|64], i1)
3864     // Note: i8*'s in the above can be any pointer type
3865     if (CI->getNumArgOperands() != 5) {
3866       DefaultCase();
3867       return;
3868     }
3869     // Remove alignment argument (3), and add alignment attributes to the
3870     // dest/src pointers.
3871     Value *Args[4] = {CI->getArgOperand(0), CI->getArgOperand(1),
3872                       CI->getArgOperand(2), CI->getArgOperand(4)};
3873     NewCall = Builder.CreateCall(NewFn, Args);
3874     auto *MemCI = cast<MemIntrinsic>(NewCall);
3875     // All mem intrinsics support dest alignment.
3876     const ConstantInt *Align = cast<ConstantInt>(CI->getArgOperand(3));
3877     MemCI->setDestAlignment(Align->getMaybeAlignValue());
3878     // Memcpy/Memmove also support source alignment.
3879     if (auto *MTI = dyn_cast<MemTransferInst>(MemCI))
3880       MTI->setSourceAlignment(Align->getMaybeAlignValue());
3881     break;
3882   }
3883   }
3884   assert(NewCall && "Should have either set this variable or returned through "
3885                     "the default case");
3886   NewCall->takeName(CI);
3887   CI->replaceAllUsesWith(NewCall);
3888   CI->eraseFromParent();
3889 }
3890 
UpgradeCallsToIntrinsic(Function * F)3891 void llvm::UpgradeCallsToIntrinsic(Function *F) {
3892   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
3893 
3894   // Check if this function should be upgraded and get the replacement function
3895   // if there is one.
3896   Function *NewFn;
3897   if (UpgradeIntrinsicFunction(F, NewFn)) {
3898     // Replace all users of the old function with the new function or new
3899     // instructions. This is not a range loop because the call is deleted.
3900     for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; )
3901       if (CallInst *CI = dyn_cast<CallInst>(*UI++))
3902         UpgradeIntrinsicCall(CI, NewFn);
3903 
3904     // Remove old function, no longer used, from the module.
3905     F->eraseFromParent();
3906   }
3907 }
3908 
UpgradeTBAANode(MDNode & MD)3909 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
3910   // Check if the tag uses struct-path aware TBAA format.
3911   if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
3912     return &MD;
3913 
3914   auto &Context = MD.getContext();
3915   if (MD.getNumOperands() == 3) {
3916     Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
3917     MDNode *ScalarType = MDNode::get(Context, Elts);
3918     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
3919     Metadata *Elts2[] = {ScalarType, ScalarType,
3920                          ConstantAsMetadata::get(
3921                              Constant::getNullValue(Type::getInt64Ty(Context))),
3922                          MD.getOperand(2)};
3923     return MDNode::get(Context, Elts2);
3924   }
3925   // Create a MDNode <MD, MD, offset 0>
3926   Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
3927                                     Type::getInt64Ty(Context)))};
3928   return MDNode::get(Context, Elts);
3929 }
3930 
UpgradeBitCastInst(unsigned Opc,Value * V,Type * DestTy,Instruction * & Temp)3931 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
3932                                       Instruction *&Temp) {
3933   if (Opc != Instruction::BitCast)
3934     return nullptr;
3935 
3936   Temp = nullptr;
3937   Type *SrcTy = V->getType();
3938   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3939       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3940     LLVMContext &Context = V->getContext();
3941 
3942     // We have no information about target data layout, so we assume that
3943     // the maximum pointer size is 64bit.
3944     Type *MidTy = Type::getInt64Ty(Context);
3945     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
3946 
3947     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
3948   }
3949 
3950   return nullptr;
3951 }
3952 
UpgradeBitCastExpr(unsigned Opc,Constant * C,Type * DestTy)3953 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
3954   if (Opc != Instruction::BitCast)
3955     return nullptr;
3956 
3957   Type *SrcTy = C->getType();
3958   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3959       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3960     LLVMContext &Context = C->getContext();
3961 
3962     // We have no information about target data layout, so we assume that
3963     // the maximum pointer size is 64bit.
3964     Type *MidTy = Type::getInt64Ty(Context);
3965 
3966     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
3967                                      DestTy);
3968   }
3969 
3970   return nullptr;
3971 }
3972 
3973 /// Check the debug info version number, if it is out-dated, drop the debug
3974 /// info. Return true if module is modified.
UpgradeDebugInfo(Module & M)3975 bool llvm::UpgradeDebugInfo(Module &M) {
3976   unsigned Version = getDebugMetadataVersionFromModule(M);
3977   if (Version == DEBUG_METADATA_VERSION) {
3978     bool BrokenDebugInfo = false;
3979     if (verifyModule(M, &llvm::errs(), &BrokenDebugInfo))
3980       report_fatal_error("Broken module found, compilation aborted!");
3981     if (!BrokenDebugInfo)
3982       // Everything is ok.
3983       return false;
3984     else {
3985       // Diagnose malformed debug info.
3986       DiagnosticInfoIgnoringInvalidDebugMetadata Diag(M);
3987       M.getContext().diagnose(Diag);
3988     }
3989   }
3990   bool Modified = StripDebugInfo(M);
3991   if (Modified && Version != DEBUG_METADATA_VERSION) {
3992     // Diagnose a version mismatch.
3993     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
3994     M.getContext().diagnose(DiagVersion);
3995   }
3996   return Modified;
3997 }
3998 
3999 /// This checks for objc retain release marker which should be upgraded. It
4000 /// returns true if module is modified.
UpgradeRetainReleaseMarker(Module & M)4001 static bool UpgradeRetainReleaseMarker(Module &M) {
4002   bool Changed = false;
4003   const char *MarkerKey = "clang.arc.retainAutoreleasedReturnValueMarker";
4004   NamedMDNode *ModRetainReleaseMarker = M.getNamedMetadata(MarkerKey);
4005   if (ModRetainReleaseMarker) {
4006     MDNode *Op = ModRetainReleaseMarker->getOperand(0);
4007     if (Op) {
4008       MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
4009       if (ID) {
4010         SmallVector<StringRef, 4> ValueComp;
4011         ID->getString().split(ValueComp, "#");
4012         if (ValueComp.size() == 2) {
4013           std::string NewValue = ValueComp[0].str() + ";" + ValueComp[1].str();
4014           ID = MDString::get(M.getContext(), NewValue);
4015         }
4016         M.addModuleFlag(Module::Error, MarkerKey, ID);
4017         M.eraseNamedMetadata(ModRetainReleaseMarker);
4018         Changed = true;
4019       }
4020     }
4021   }
4022   return Changed;
4023 }
4024 
UpgradeARCRuntime(Module & M)4025 void llvm::UpgradeARCRuntime(Module &M) {
4026   // This lambda converts normal function calls to ARC runtime functions to
4027   // intrinsic calls.
4028   auto UpgradeToIntrinsic = [&](const char *OldFunc,
4029                                 llvm::Intrinsic::ID IntrinsicFunc) {
4030     Function *Fn = M.getFunction(OldFunc);
4031 
4032     if (!Fn)
4033       return;
4034 
4035     Function *NewFn = llvm::Intrinsic::getDeclaration(&M, IntrinsicFunc);
4036 
4037     for (auto I = Fn->user_begin(), E = Fn->user_end(); I != E;) {
4038       CallInst *CI = dyn_cast<CallInst>(*I++);
4039       if (!CI || CI->getCalledFunction() != Fn)
4040         continue;
4041 
4042       IRBuilder<> Builder(CI->getParent(), CI->getIterator());
4043       FunctionType *NewFuncTy = NewFn->getFunctionType();
4044       SmallVector<Value *, 2> Args;
4045 
4046       // Don't upgrade the intrinsic if it's not valid to bitcast the return
4047       // value to the return type of the old function.
4048       if (NewFuncTy->getReturnType() != CI->getType() &&
4049           !CastInst::castIsValid(Instruction::BitCast, CI,
4050                                  NewFuncTy->getReturnType()))
4051         continue;
4052 
4053       bool InvalidCast = false;
4054 
4055       for (unsigned I = 0, E = CI->getNumArgOperands(); I != E; ++I) {
4056         Value *Arg = CI->getArgOperand(I);
4057 
4058         // Bitcast argument to the parameter type of the new function if it's
4059         // not a variadic argument.
4060         if (I < NewFuncTy->getNumParams()) {
4061           // Don't upgrade the intrinsic if it's not valid to bitcast the argument
4062           // to the parameter type of the new function.
4063           if (!CastInst::castIsValid(Instruction::BitCast, Arg,
4064                                      NewFuncTy->getParamType(I))) {
4065             InvalidCast = true;
4066             break;
4067           }
4068           Arg = Builder.CreateBitCast(Arg, NewFuncTy->getParamType(I));
4069         }
4070         Args.push_back(Arg);
4071       }
4072 
4073       if (InvalidCast)
4074         continue;
4075 
4076       // Create a call instruction that calls the new function.
4077       CallInst *NewCall = Builder.CreateCall(NewFuncTy, NewFn, Args);
4078       NewCall->setTailCallKind(cast<CallInst>(CI)->getTailCallKind());
4079       NewCall->takeName(CI);
4080 
4081       // Bitcast the return value back to the type of the old call.
4082       Value *NewRetVal = Builder.CreateBitCast(NewCall, CI->getType());
4083 
4084       if (!CI->use_empty())
4085         CI->replaceAllUsesWith(NewRetVal);
4086       CI->eraseFromParent();
4087     }
4088 
4089     if (Fn->use_empty())
4090       Fn->eraseFromParent();
4091   };
4092 
4093   // Unconditionally convert a call to "clang.arc.use" to a call to
4094   // "llvm.objc.clang.arc.use".
4095   UpgradeToIntrinsic("clang.arc.use", llvm::Intrinsic::objc_clang_arc_use);
4096 
4097   // Upgrade the retain release marker. If there is no need to upgrade
4098   // the marker, that means either the module is already new enough to contain
4099   // new intrinsics or it is not ARC. There is no need to upgrade runtime call.
4100   if (!UpgradeRetainReleaseMarker(M))
4101     return;
4102 
4103   std::pair<const char *, llvm::Intrinsic::ID> RuntimeFuncs[] = {
4104       {"objc_autorelease", llvm::Intrinsic::objc_autorelease},
4105       {"objc_autoreleasePoolPop", llvm::Intrinsic::objc_autoreleasePoolPop},
4106       {"objc_autoreleasePoolPush", llvm::Intrinsic::objc_autoreleasePoolPush},
4107       {"objc_autoreleaseReturnValue",
4108        llvm::Intrinsic::objc_autoreleaseReturnValue},
4109       {"objc_copyWeak", llvm::Intrinsic::objc_copyWeak},
4110       {"objc_destroyWeak", llvm::Intrinsic::objc_destroyWeak},
4111       {"objc_initWeak", llvm::Intrinsic::objc_initWeak},
4112       {"objc_loadWeak", llvm::Intrinsic::objc_loadWeak},
4113       {"objc_loadWeakRetained", llvm::Intrinsic::objc_loadWeakRetained},
4114       {"objc_moveWeak", llvm::Intrinsic::objc_moveWeak},
4115       {"objc_release", llvm::Intrinsic::objc_release},
4116       {"objc_retain", llvm::Intrinsic::objc_retain},
4117       {"objc_retainAutorelease", llvm::Intrinsic::objc_retainAutorelease},
4118       {"objc_retainAutoreleaseReturnValue",
4119        llvm::Intrinsic::objc_retainAutoreleaseReturnValue},
4120       {"objc_retainAutoreleasedReturnValue",
4121        llvm::Intrinsic::objc_retainAutoreleasedReturnValue},
4122       {"objc_retainBlock", llvm::Intrinsic::objc_retainBlock},
4123       {"objc_storeStrong", llvm::Intrinsic::objc_storeStrong},
4124       {"objc_storeWeak", llvm::Intrinsic::objc_storeWeak},
4125       {"objc_unsafeClaimAutoreleasedReturnValue",
4126        llvm::Intrinsic::objc_unsafeClaimAutoreleasedReturnValue},
4127       {"objc_retainedObject", llvm::Intrinsic::objc_retainedObject},
4128       {"objc_unretainedObject", llvm::Intrinsic::objc_unretainedObject},
4129       {"objc_unretainedPointer", llvm::Intrinsic::objc_unretainedPointer},
4130       {"objc_retain_autorelease", llvm::Intrinsic::objc_retain_autorelease},
4131       {"objc_sync_enter", llvm::Intrinsic::objc_sync_enter},
4132       {"objc_sync_exit", llvm::Intrinsic::objc_sync_exit},
4133       {"objc_arc_annotation_topdown_bbstart",
4134        llvm::Intrinsic::objc_arc_annotation_topdown_bbstart},
4135       {"objc_arc_annotation_topdown_bbend",
4136        llvm::Intrinsic::objc_arc_annotation_topdown_bbend},
4137       {"objc_arc_annotation_bottomup_bbstart",
4138        llvm::Intrinsic::objc_arc_annotation_bottomup_bbstart},
4139       {"objc_arc_annotation_bottomup_bbend",
4140        llvm::Intrinsic::objc_arc_annotation_bottomup_bbend}};
4141 
4142   for (auto &I : RuntimeFuncs)
4143     UpgradeToIntrinsic(I.first, I.second);
4144 }
4145 
UpgradeModuleFlags(Module & M)4146 bool llvm::UpgradeModuleFlags(Module &M) {
4147   NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
4148   if (!ModFlags)
4149     return false;
4150 
4151   bool HasObjCFlag = false, HasClassProperties = false, Changed = false;
4152   bool HasSwiftVersionFlag = false;
4153   uint8_t SwiftMajorVersion, SwiftMinorVersion;
4154   uint32_t SwiftABIVersion;
4155   auto Int8Ty = Type::getInt8Ty(M.getContext());
4156   auto Int32Ty = Type::getInt32Ty(M.getContext());
4157 
4158   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
4159     MDNode *Op = ModFlags->getOperand(I);
4160     if (Op->getNumOperands() != 3)
4161       continue;
4162     MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
4163     if (!ID)
4164       continue;
4165     if (ID->getString() == "Objective-C Image Info Version")
4166       HasObjCFlag = true;
4167     if (ID->getString() == "Objective-C Class Properties")
4168       HasClassProperties = true;
4169     // Upgrade PIC/PIE Module Flags. The module flag behavior for these two
4170     // field was Error and now they are Max.
4171     if (ID->getString() == "PIC Level" || ID->getString() == "PIE Level") {
4172       if (auto *Behavior =
4173               mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
4174         if (Behavior->getLimitedValue() == Module::Error) {
4175           Type *Int32Ty = Type::getInt32Ty(M.getContext());
4176           Metadata *Ops[3] = {
4177               ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Module::Max)),
4178               MDString::get(M.getContext(), ID->getString()),
4179               Op->getOperand(2)};
4180           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4181           Changed = true;
4182         }
4183       }
4184     }
4185     // Upgrade Objective-C Image Info Section. Removed the whitespce in the
4186     // section name so that llvm-lto will not complain about mismatching
4187     // module flags that is functionally the same.
4188     if (ID->getString() == "Objective-C Image Info Section") {
4189       if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
4190         SmallVector<StringRef, 4> ValueComp;
4191         Value->getString().split(ValueComp, " ");
4192         if (ValueComp.size() != 1) {
4193           std::string NewValue;
4194           for (auto &S : ValueComp)
4195             NewValue += S.str();
4196           Metadata *Ops[3] = {Op->getOperand(0), Op->getOperand(1),
4197                               MDString::get(M.getContext(), NewValue)};
4198           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4199           Changed = true;
4200         }
4201       }
4202     }
4203 
4204     // IRUpgrader turns a i32 type "Objective-C Garbage Collection" into i8 value.
4205     // If the higher bits are set, it adds new module flag for swift info.
4206     if (ID->getString() == "Objective-C Garbage Collection") {
4207       auto Md = dyn_cast<ConstantAsMetadata>(Op->getOperand(2));
4208       if (Md) {
4209         assert(Md->getValue() && "Expected non-empty metadata");
4210         auto Type = Md->getValue()->getType();
4211         if (Type == Int8Ty)
4212           continue;
4213         unsigned Val = Md->getValue()->getUniqueInteger().getZExtValue();
4214         if ((Val & 0xff) != Val) {
4215           HasSwiftVersionFlag = true;
4216           SwiftABIVersion = (Val & 0xff00) >> 8;
4217           SwiftMajorVersion = (Val & 0xff000000) >> 24;
4218           SwiftMinorVersion = (Val & 0xff0000) >> 16;
4219         }
4220         Metadata *Ops[3] = {
4221           ConstantAsMetadata::get(ConstantInt::get(Int32Ty,Module::Error)),
4222           Op->getOperand(1),
4223           ConstantAsMetadata::get(ConstantInt::get(Int8Ty,Val & 0xff))};
4224         ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
4225         Changed = true;
4226       }
4227     }
4228   }
4229 
4230   // "Objective-C Class Properties" is recently added for Objective-C. We
4231   // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
4232   // flag of value 0, so we can correclty downgrade this flag when trying to
4233   // link an ObjC bitcode without this module flag with an ObjC bitcode with
4234   // this module flag.
4235   if (HasObjCFlag && !HasClassProperties) {
4236     M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
4237                     (uint32_t)0);
4238     Changed = true;
4239   }
4240 
4241   if (HasSwiftVersionFlag) {
4242     M.addModuleFlag(Module::Error, "Swift ABI Version",
4243                     SwiftABIVersion);
4244     M.addModuleFlag(Module::Error, "Swift Major Version",
4245                     ConstantInt::get(Int8Ty, SwiftMajorVersion));
4246     M.addModuleFlag(Module::Error, "Swift Minor Version",
4247                     ConstantInt::get(Int8Ty, SwiftMinorVersion));
4248     Changed = true;
4249   }
4250 
4251   return Changed;
4252 }
4253 
UpgradeSectionAttributes(Module & M)4254 void llvm::UpgradeSectionAttributes(Module &M) {
4255   auto TrimSpaces = [](StringRef Section) -> std::string {
4256     SmallVector<StringRef, 5> Components;
4257     Section.split(Components, ',');
4258 
4259     SmallString<32> Buffer;
4260     raw_svector_ostream OS(Buffer);
4261 
4262     for (auto Component : Components)
4263       OS << ',' << Component.trim();
4264 
4265     return std::string(OS.str().substr(1));
4266   };
4267 
4268   for (auto &GV : M.globals()) {
4269     if (!GV.hasSection())
4270       continue;
4271 
4272     StringRef Section = GV.getSection();
4273 
4274     if (!Section.startswith("__DATA, __objc_catlist"))
4275       continue;
4276 
4277     // __DATA, __objc_catlist, regular, no_dead_strip
4278     // __DATA,__objc_catlist,regular,no_dead_strip
4279     GV.setSection(TrimSpaces(Section));
4280   }
4281 }
4282 
4283 namespace {
4284 // Prior to LLVM 10.0, the strictfp attribute could be used on individual
4285 // callsites within a function that did not also have the strictfp attribute.
4286 // Since 10.0, if strict FP semantics are needed within a function, the
4287 // function must have the strictfp attribute and all calls within the function
4288 // must also have the strictfp attribute. This latter restriction is
4289 // necessary to prevent unwanted libcall simplification when a function is
4290 // being cloned (such as for inlining).
4291 //
4292 // The "dangling" strictfp attribute usage was only used to prevent constant
4293 // folding and other libcall simplification. The nobuiltin attribute on the
4294 // callsite has the same effect.
4295 struct StrictFPUpgradeVisitor : public InstVisitor<StrictFPUpgradeVisitor> {
StrictFPUpgradeVisitor__anon10d60d340411::StrictFPUpgradeVisitor4296   StrictFPUpgradeVisitor() {}
4297 
visitCallBase__anon10d60d340411::StrictFPUpgradeVisitor4298   void visitCallBase(CallBase &Call) {
4299     if (!Call.isStrictFP())
4300       return;
4301     if (isa<ConstrainedFPIntrinsic>(&Call))
4302       return;
4303     // If we get here, the caller doesn't have the strictfp attribute
4304     // but this callsite does. Replace the strictfp attribute with nobuiltin.
4305     Call.removeAttribute(AttributeList::FunctionIndex, Attribute::StrictFP);
4306     Call.addAttribute(AttributeList::FunctionIndex, Attribute::NoBuiltin);
4307   }
4308 };
4309 } // namespace
4310 
UpgradeFunctionAttributes(Function & F)4311 void llvm::UpgradeFunctionAttributes(Function &F) {
4312   // If a function definition doesn't have the strictfp attribute,
4313   // convert any callsite strictfp attributes to nobuiltin.
4314   if (!F.isDeclaration() && !F.hasFnAttribute(Attribute::StrictFP)) {
4315     StrictFPUpgradeVisitor SFPV;
4316     SFPV.visit(F);
4317   }
4318 }
4319 
isOldLoopArgument(Metadata * MD)4320 static bool isOldLoopArgument(Metadata *MD) {
4321   auto *T = dyn_cast_or_null<MDTuple>(MD);
4322   if (!T)
4323     return false;
4324   if (T->getNumOperands() < 1)
4325     return false;
4326   auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
4327   if (!S)
4328     return false;
4329   return S->getString().startswith("llvm.vectorizer.");
4330 }
4331 
upgradeLoopTag(LLVMContext & C,StringRef OldTag)4332 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
4333   StringRef OldPrefix = "llvm.vectorizer.";
4334   assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
4335 
4336   if (OldTag == "llvm.vectorizer.unroll")
4337     return MDString::get(C, "llvm.loop.interleave.count");
4338 
4339   return MDString::get(
4340       C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
4341              .str());
4342 }
4343 
upgradeLoopArgument(Metadata * MD)4344 static Metadata *upgradeLoopArgument(Metadata *MD) {
4345   auto *T = dyn_cast_or_null<MDTuple>(MD);
4346   if (!T)
4347     return MD;
4348   if (T->getNumOperands() < 1)
4349     return MD;
4350   auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
4351   if (!OldTag)
4352     return MD;
4353   if (!OldTag->getString().startswith("llvm.vectorizer."))
4354     return MD;
4355 
4356   // This has an old tag.  Upgrade it.
4357   SmallVector<Metadata *, 8> Ops;
4358   Ops.reserve(T->getNumOperands());
4359   Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
4360   for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
4361     Ops.push_back(T->getOperand(I));
4362 
4363   return MDTuple::get(T->getContext(), Ops);
4364 }
4365 
upgradeInstructionLoopAttachment(MDNode & N)4366 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
4367   auto *T = dyn_cast<MDTuple>(&N);
4368   if (!T)
4369     return &N;
4370 
4371   if (none_of(T->operands(), isOldLoopArgument))
4372     return &N;
4373 
4374   SmallVector<Metadata *, 8> Ops;
4375   Ops.reserve(T->getNumOperands());
4376   for (Metadata *MD : T->operands())
4377     Ops.push_back(upgradeLoopArgument(MD));
4378 
4379   return MDTuple::get(T->getContext(), Ops);
4380 }
4381 
UpgradeDataLayoutString(StringRef DL,StringRef TT)4382 std::string llvm::UpgradeDataLayoutString(StringRef DL, StringRef TT) {
4383   StringRef AddrSpaces = "-p270:32:32-p271:32:32-p272:64:64";
4384 
4385   // If X86, and the datalayout matches the expected format, add pointer size
4386   // address spaces to the datalayout.
4387   if (!Triple(TT).isX86() || DL.contains(AddrSpaces))
4388     return std::string(DL);
4389 
4390   SmallVector<StringRef, 4> Groups;
4391   Regex R("(e-m:[a-z](-p:32:32)?)(-[if]64:.*$)");
4392   if (!R.match(DL, &Groups))
4393     return std::string(DL);
4394 
4395   return (Groups[1] + AddrSpaces + Groups[3]).str();
4396 }
4397 
UpgradeAttributes(AttrBuilder & B)4398 void llvm::UpgradeAttributes(AttrBuilder &B) {
4399   StringRef FramePointer;
4400   if (B.contains("no-frame-pointer-elim")) {
4401     // The value can be "true" or "false".
4402     for (const auto &I : B.td_attrs())
4403       if (I.first == "no-frame-pointer-elim")
4404         FramePointer = I.second == "true" ? "all" : "none";
4405     B.removeAttribute("no-frame-pointer-elim");
4406   }
4407   if (B.contains("no-frame-pointer-elim-non-leaf")) {
4408     // The value is ignored. "no-frame-pointer-elim"="true" takes priority.
4409     if (FramePointer != "all")
4410       FramePointer = "non-leaf";
4411     B.removeAttribute("no-frame-pointer-elim-non-leaf");
4412   }
4413   if (!FramePointer.empty())
4414     B.addAttribute("frame-pointer", FramePointer);
4415 
4416   if (B.contains("null-pointer-is-valid")) {
4417     // The value can be "true" or "false".
4418     bool NullPointerIsValid = false;
4419     for (const auto &I : B.td_attrs())
4420       if (I.first == "null-pointer-is-valid")
4421         NullPointerIsValid = I.second == "true";
4422     B.removeAttribute("null-pointer-is-valid");
4423     if (NullPointerIsValid)
4424       B.addAttribute(Attribute::NullPointerIsValid);
4425   }
4426 }
4427