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