1 //===-- AutoUpgrade.cpp - Implement auto-upgrade helper functions ---------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements the auto-upgrade helper functions.
11 // This is where deprecated IR intrinsics and other IR features are updated to
12 // current specifications.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/IR/AutoUpgrade.h"
17 #include "llvm/ADT/StringSwitch.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/Instruction.h"
25 #include "llvm/IR/IntrinsicInst.h"
26 #include "llvm/IR/LLVMContext.h"
27 #include "llvm/IR/Module.h"
28 #include "llvm/IR/Verifier.h"
29 #include "llvm/Support/ErrorHandling.h"
30 #include "llvm/Support/Regex.h"
31 #include <cstring>
32 using namespace llvm;
33 
34 static void rename(GlobalValue *GV) { GV->setName(GV->getName() + ".old"); }
35 
36 // Upgrade the declarations of the SSE4.1 ptest intrinsics whose arguments have
37 // changed their type from v4f32 to v2i64.
38 static bool UpgradePTESTIntrinsic(Function* F, Intrinsic::ID IID,
39                                   Function *&NewFn) {
40   // Check whether this is an old version of the function, which received
41   // v4f32 arguments.
42   Type *Arg0Type = F->getFunctionType()->getParamType(0);
43   if (Arg0Type != VectorType::get(Type::getFloatTy(F->getContext()), 4))
44     return false;
45 
46   // Yes, it's old, replace it with new version.
47   rename(F);
48   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
49   return true;
50 }
51 
52 // Upgrade the declarations of intrinsic functions whose 8-bit immediate mask
53 // arguments have changed their type from i32 to i8.
54 static bool UpgradeX86IntrinsicsWith8BitMask(Function *F, Intrinsic::ID IID,
55                                              Function *&NewFn) {
56   // Check that the last argument is an i32.
57   Type *LastArgType = F->getFunctionType()->getParamType(
58      F->getFunctionType()->getNumParams() - 1);
59   if (!LastArgType->isIntegerTy(32))
60     return false;
61 
62   // Move this function aside and map down.
63   rename(F);
64   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
65   return true;
66 }
67 
68 // Upgrade the declaration of fp compare intrinsics that change return type
69 // from scalar to vXi1 mask.
70 static bool UpgradeX86MaskedFPCompare(Function *F, Intrinsic::ID IID,
71                                       Function *&NewFn) {
72   // Check if the return type is a vector.
73   if (F->getReturnType()->isVectorTy())
74     return false;
75 
76   rename(F);
77   NewFn = Intrinsic::getDeclaration(F->getParent(), IID);
78   return true;
79 }
80 
81 static bool ShouldUpgradeX86Intrinsic(Function *F, StringRef Name) {
82   // All of the intrinsics matches below should be marked with which llvm
83   // version started autoupgrading them. At some point in the future we would
84   // like to use this information to remove upgrade code for some older
85   // intrinsics. It is currently undecided how we will determine that future
86   // point.
87   if (Name=="ssse3.pabs.b.128" || // Added in 6.0
88       Name=="ssse3.pabs.w.128" || // Added in 6.0
89       Name=="ssse3.pabs.d.128" || // Added in 6.0
90       Name.startswith("fma.vfmsub.") || // Added in 7.0
91       Name.startswith("fma.vfmsubadd.") || // Added in 7.0
92       Name.startswith("fma.vfnmadd.") || // Added in 7.0
93       Name.startswith("fma.vfnmsub.") || // Added in 7.0
94       Name.startswith("avx512.mask.shuf.i") || // Added in 6.0
95       Name.startswith("avx512.mask.shuf.f") || // Added in 6.0
96       Name.startswith("avx512.kunpck") || //added in 6.0
97       Name.startswith("avx2.pabs.") || // Added in 6.0
98       Name.startswith("avx512.mask.pabs.") || // Added in 6.0
99       Name.startswith("avx512.broadcastm") || // Added in 6.0
100       Name.startswith("avx512.mask.pbroadcast") || // Added in 6.0
101       Name.startswith("sse2.pcmpeq.") || // Added in 3.1
102       Name.startswith("sse2.pcmpgt.") || // Added in 3.1
103       Name.startswith("avx2.pcmpeq.") || // Added in 3.1
104       Name.startswith("avx2.pcmpgt.") || // Added in 3.1
105       Name.startswith("avx512.mask.pcmpeq.") || // Added in 3.9
106       Name.startswith("avx512.mask.pcmpgt.") || // Added in 3.9
107       Name.startswith("avx.vperm2f128.") || // Added in 6.0
108       Name == "avx2.vperm2i128" || // Added in 6.0
109       Name == "sse.add.ss" || // Added in 4.0
110       Name == "sse2.add.sd" || // Added in 4.0
111       Name == "sse.sub.ss" || // Added in 4.0
112       Name == "sse2.sub.sd" || // Added in 4.0
113       Name == "sse.mul.ss" || // Added in 4.0
114       Name == "sse2.mul.sd" || // Added in 4.0
115       Name == "sse.div.ss" || // Added in 4.0
116       Name == "sse2.div.sd" || // Added in 4.0
117       Name == "sse41.pmaxsb" || // Added in 3.9
118       Name == "sse2.pmaxs.w" || // Added in 3.9
119       Name == "sse41.pmaxsd" || // Added in 3.9
120       Name == "sse2.pmaxu.b" || // Added in 3.9
121       Name == "sse41.pmaxuw" || // Added in 3.9
122       Name == "sse41.pmaxud" || // Added in 3.9
123       Name == "sse41.pminsb" || // Added in 3.9
124       Name == "sse2.pmins.w" || // Added in 3.9
125       Name == "sse41.pminsd" || // Added in 3.9
126       Name == "sse2.pminu.b" || // Added in 3.9
127       Name == "sse41.pminuw" || // Added in 3.9
128       Name == "sse41.pminud" || // Added in 3.9
129       Name == "avx512.kand.w" || // Added in 7.0
130       Name == "avx512.kandn.w" || // Added in 7.0
131       Name == "avx512.knot.w" || // Added in 7.0
132       Name == "avx512.kor.w" || // Added in 7.0
133       Name == "avx512.kxor.w" || // Added in 7.0
134       Name == "avx512.kxnor.w" || // Added in 7.0
135       Name == "avx512.kortestc.w" || // Added in 7.0
136       Name == "avx512.kortestz.w" || // Added in 7.0
137       Name.startswith("avx512.mask.pshuf.b.") || // Added in 4.0
138       Name.startswith("avx2.pmax") || // Added in 3.9
139       Name.startswith("avx2.pmin") || // Added in 3.9
140       Name.startswith("avx512.mask.pmax") || // Added in 4.0
141       Name.startswith("avx512.mask.pmin") || // Added in 4.0
142       Name.startswith("avx2.vbroadcast") || // Added in 3.8
143       Name.startswith("avx2.pbroadcast") || // Added in 3.8
144       Name.startswith("avx.vpermil.") || // Added in 3.1
145       Name.startswith("sse2.pshuf") || // Added in 3.9
146       Name.startswith("avx512.pbroadcast") || // Added in 3.9
147       Name.startswith("avx512.mask.broadcast.s") || // Added in 3.9
148       Name.startswith("avx512.mask.movddup") || // Added in 3.9
149       Name.startswith("avx512.mask.movshdup") || // Added in 3.9
150       Name.startswith("avx512.mask.movsldup") || // Added in 3.9
151       Name.startswith("avx512.mask.pshuf.d.") || // Added in 3.9
152       Name.startswith("avx512.mask.pshufl.w.") || // Added in 3.9
153       Name.startswith("avx512.mask.pshufh.w.") || // Added in 3.9
154       Name.startswith("avx512.mask.shuf.p") || // Added in 4.0
155       Name.startswith("avx512.mask.vpermil.p") || // Added in 3.9
156       Name.startswith("avx512.mask.perm.df.") || // Added in 3.9
157       Name.startswith("avx512.mask.perm.di.") || // Added in 3.9
158       Name.startswith("avx512.mask.punpckl") || // Added in 3.9
159       Name.startswith("avx512.mask.punpckh") || // Added in 3.9
160       Name.startswith("avx512.mask.unpckl.") || // Added in 3.9
161       Name.startswith("avx512.mask.unpckh.") || // Added in 3.9
162       Name.startswith("avx512.mask.pand.") || // Added in 3.9
163       Name.startswith("avx512.mask.pandn.") || // Added in 3.9
164       Name.startswith("avx512.mask.por.") || // Added in 3.9
165       Name.startswith("avx512.mask.pxor.") || // Added in 3.9
166       Name.startswith("avx512.mask.and.") || // Added in 3.9
167       Name.startswith("avx512.mask.andn.") || // Added in 3.9
168       Name.startswith("avx512.mask.or.") || // Added in 3.9
169       Name.startswith("avx512.mask.xor.") || // Added in 3.9
170       Name.startswith("avx512.mask.padd.") || // Added in 4.0
171       Name.startswith("avx512.mask.psub.") || // Added in 4.0
172       Name.startswith("avx512.mask.pmull.") || // Added in 4.0
173       Name.startswith("avx512.mask.cvtdq2pd.") || // Added in 4.0
174       Name.startswith("avx512.mask.cvtudq2pd.") || // Added in 4.0
175       Name == "avx512.mask.cvtudq2ps.128" || // Added in 7.0
176       Name == "avx512.mask.cvtudq2ps.256" || // Added in 7.0
177       Name == "avx512.mask.cvtqq2pd.128" || // Added in 7.0
178       Name == "avx512.mask.cvtqq2pd.256" || // Added in 7.0
179       Name == "avx512.mask.cvtuqq2pd.128" || // Added in 7.0
180       Name == "avx512.mask.cvtuqq2pd.256" || // Added in 7.0
181       Name == "avx512.mask.cvtdq2ps.128" || // Added in 7.0
182       Name == "avx512.mask.cvtdq2ps.256" || // Added in 7.0
183       Name == "avx512.mask.cvtpd2dq.256" || // Added in 7.0
184       Name == "avx512.mask.cvtpd2ps.256" || // Added in 7.0
185       Name == "avx512.mask.cvttpd2dq.256" || // Added in 7.0
186       Name == "avx512.mask.cvttps2dq.128" || // Added in 7.0
187       Name == "avx512.mask.cvttps2dq.256" || // Added in 7.0
188       Name == "avx512.mask.cvtps2pd.128" || // Added in 7.0
189       Name == "avx512.mask.cvtps2pd.256" || // Added in 7.0
190       Name == "avx512.cvtusi2sd" || // Added in 7.0
191       Name.startswith("avx512.mask.permvar.") || // Added in 7.0
192       Name.startswith("avx512.mask.permvar.") || // Added in 7.0
193       Name == "sse2.pmulu.dq" || // Added in 7.0
194       Name == "sse41.pmuldq" || // Added in 7.0
195       Name == "avx2.pmulu.dq" || // Added in 7.0
196       Name == "avx2.pmul.dq" || // Added in 7.0
197       Name == "avx512.pmulu.dq.512" || // Added in 7.0
198       Name == "avx512.pmul.dq.512" || // Added in 7.0
199       Name.startswith("avx512.mask.pmul.dq.") || // Added in 4.0
200       Name.startswith("avx512.mask.pmulu.dq.") || // Added in 4.0
201       Name.startswith("avx512.mask.pmul.hr.sw.") || // Added in 7.0
202       Name.startswith("avx512.mask.pmulh.w.") || // Added in 7.0
203       Name.startswith("avx512.mask.pmulhu.w.") || // Added in 7.0
204       Name.startswith("avx512.mask.pmaddw.d.") || // Added in 7.0
205       Name.startswith("avx512.mask.pmaddubs.w.") || // Added in 7.0
206       Name.startswith("avx512.mask.packsswb.") || // Added in 5.0
207       Name.startswith("avx512.mask.packssdw.") || // Added in 5.0
208       Name.startswith("avx512.mask.packuswb.") || // Added in 5.0
209       Name.startswith("avx512.mask.packusdw.") || // Added in 5.0
210       Name.startswith("avx512.mask.cmp.b") || // Added in 5.0
211       Name.startswith("avx512.mask.cmp.d") || // Added in 5.0
212       Name.startswith("avx512.mask.cmp.q") || // Added in 5.0
213       Name.startswith("avx512.mask.cmp.w") || // Added in 5.0
214       Name.startswith("avx512.mask.ucmp.") || // Added in 5.0
215       Name.startswith("avx512.cvtb2mask.") || // Added in 7.0
216       Name.startswith("avx512.cvtw2mask.") || // Added in 7.0
217       Name.startswith("avx512.cvtd2mask.") || // Added in 7.0
218       Name.startswith("avx512.cvtq2mask.") || // Added in 7.0
219       Name == "avx512.mask.add.pd.128" || // Added in 4.0
220       Name == "avx512.mask.add.pd.256" || // Added in 4.0
221       Name == "avx512.mask.add.ps.128" || // Added in 4.0
222       Name == "avx512.mask.add.ps.256" || // Added in 4.0
223       Name == "avx512.mask.div.pd.128" || // Added in 4.0
224       Name == "avx512.mask.div.pd.256" || // Added in 4.0
225       Name == "avx512.mask.div.ps.128" || // Added in 4.0
226       Name == "avx512.mask.div.ps.256" || // Added in 4.0
227       Name == "avx512.mask.mul.pd.128" || // Added in 4.0
228       Name == "avx512.mask.mul.pd.256" || // Added in 4.0
229       Name == "avx512.mask.mul.ps.128" || // Added in 4.0
230       Name == "avx512.mask.mul.ps.256" || // Added in 4.0
231       Name == "avx512.mask.sub.pd.128" || // Added in 4.0
232       Name == "avx512.mask.sub.pd.256" || // Added in 4.0
233       Name == "avx512.mask.sub.ps.128" || // Added in 4.0
234       Name == "avx512.mask.sub.ps.256" || // Added in 4.0
235       Name == "avx512.mask.max.pd.128" || // Added in 5.0
236       Name == "avx512.mask.max.pd.256" || // Added in 5.0
237       Name == "avx512.mask.max.ps.128" || // Added in 5.0
238       Name == "avx512.mask.max.ps.256" || // Added in 5.0
239       Name == "avx512.mask.min.pd.128" || // Added in 5.0
240       Name == "avx512.mask.min.pd.256" || // Added in 5.0
241       Name == "avx512.mask.min.ps.128" || // Added in 5.0
242       Name == "avx512.mask.min.ps.256" || // Added in 5.0
243       Name.startswith("avx512.mask.vpermilvar.") || // Added in 4.0
244       Name.startswith("avx512.mask.psll.d") || // Added in 4.0
245       Name.startswith("avx512.mask.psll.q") || // Added in 4.0
246       Name.startswith("avx512.mask.psll.w") || // Added in 4.0
247       Name.startswith("avx512.mask.psra.d") || // Added in 4.0
248       Name.startswith("avx512.mask.psra.q") || // Added in 4.0
249       Name.startswith("avx512.mask.psra.w") || // Added in 4.0
250       Name.startswith("avx512.mask.psrl.d") || // Added in 4.0
251       Name.startswith("avx512.mask.psrl.q") || // Added in 4.0
252       Name.startswith("avx512.mask.psrl.w") || // Added in 4.0
253       Name.startswith("avx512.mask.pslli") || // Added in 4.0
254       Name.startswith("avx512.mask.psrai") || // Added in 4.0
255       Name.startswith("avx512.mask.psrli") || // Added in 4.0
256       Name.startswith("avx512.mask.psllv") || // Added in 4.0
257       Name.startswith("avx512.mask.psrav") || // Added in 4.0
258       Name.startswith("avx512.mask.psrlv") || // Added in 4.0
259       Name.startswith("sse41.pmovsx") || // Added in 3.8
260       Name.startswith("sse41.pmovzx") || // Added in 3.9
261       Name.startswith("avx2.pmovsx") || // Added in 3.9
262       Name.startswith("avx2.pmovzx") || // Added in 3.9
263       Name.startswith("avx512.mask.pmovsx") || // Added in 4.0
264       Name.startswith("avx512.mask.pmovzx") || // Added in 4.0
265       Name.startswith("avx512.mask.lzcnt.") || // Added in 5.0
266       Name.startswith("avx512.mask.pternlog.") || // Added in 7.0
267       Name.startswith("avx512.maskz.pternlog.") || // Added in 7.0
268       Name.startswith("avx512.mask.vpmadd52") || // Added in 7.0
269       Name.startswith("avx512.maskz.vpmadd52") || // Added in 7.0
270       Name.startswith("avx512.mask.vpermi2var.") || // Added in 7.0
271       Name.startswith("avx512.mask.vpermt2var.") || // Added in 7.0
272       Name.startswith("avx512.maskz.vpermt2var.") || // Added in 7.0
273       Name == "sse.cvtsi2ss" || // Added in 7.0
274       Name == "sse.cvtsi642ss" || // Added in 7.0
275       Name == "sse2.cvtsi2sd" || // Added in 7.0
276       Name == "sse2.cvtsi642sd" || // Added in 7.0
277       Name == "sse2.cvtss2sd" || // Added in 7.0
278       Name == "sse2.cvtdq2pd" || // Added in 3.9
279       Name == "sse2.cvtdq2ps" || // Added in 7.0
280       Name == "sse2.cvtps2pd" || // Added in 3.9
281       Name == "avx.cvtdq2.pd.256" || // Added in 3.9
282       Name == "avx.cvtdq2.ps.256" || // Added in 7.0
283       Name == "avx.cvt.ps2.pd.256" || // Added in 3.9
284       Name.startswith("avx.vinsertf128.") || // Added in 3.7
285       Name == "avx2.vinserti128" || // Added in 3.7
286       Name.startswith("avx512.mask.insert") || // Added in 4.0
287       Name.startswith("avx.vextractf128.") || // Added in 3.7
288       Name == "avx2.vextracti128" || // Added in 3.7
289       Name.startswith("avx512.mask.vextract") || // Added in 4.0
290       Name.startswith("sse4a.movnt.") || // Added in 3.9
291       Name.startswith("avx.movnt.") || // Added in 3.2
292       Name.startswith("avx512.storent.") || // Added in 3.9
293       Name == "sse41.movntdqa" || // Added in 5.0
294       Name == "avx2.movntdqa" || // Added in 5.0
295       Name == "avx512.movntdqa" || // Added in 5.0
296       Name == "sse2.storel.dq" || // Added in 3.9
297       Name.startswith("sse.storeu.") || // Added in 3.9
298       Name.startswith("sse2.storeu.") || // Added in 3.9
299       Name.startswith("avx.storeu.") || // Added in 3.9
300       Name.startswith("avx512.mask.storeu.") || // Added in 3.9
301       Name.startswith("avx512.mask.store.p") || // Added in 3.9
302       Name.startswith("avx512.mask.store.b.") || // Added in 3.9
303       Name.startswith("avx512.mask.store.w.") || // Added in 3.9
304       Name.startswith("avx512.mask.store.d.") || // Added in 3.9
305       Name.startswith("avx512.mask.store.q.") || // Added in 3.9
306       Name == "avx512.mask.store.ss" || // Added in 7.0
307       Name.startswith("avx512.mask.loadu.") || // Added in 3.9
308       Name.startswith("avx512.mask.load.") || // Added in 3.9
309       Name == "sse42.crc32.64.8" || // Added in 3.4
310       Name.startswith("avx.vbroadcast.s") || // Added in 3.5
311       Name.startswith("avx512.vbroadcast.s") || // Added in 7.0
312       Name.startswith("avx512.mask.palignr.") || // Added in 3.9
313       Name.startswith("avx512.mask.valign.") || // Added in 4.0
314       Name.startswith("sse2.psll.dq") || // Added in 3.7
315       Name.startswith("sse2.psrl.dq") || // Added in 3.7
316       Name.startswith("avx2.psll.dq") || // Added in 3.7
317       Name.startswith("avx2.psrl.dq") || // Added in 3.7
318       Name.startswith("avx512.psll.dq") || // Added in 3.9
319       Name.startswith("avx512.psrl.dq") || // Added in 3.9
320       Name == "sse41.pblendw" || // Added in 3.7
321       Name.startswith("sse41.blendp") || // Added in 3.7
322       Name.startswith("avx.blend.p") || // Added in 3.7
323       Name == "avx2.pblendw" || // Added in 3.7
324       Name.startswith("avx2.pblendd.") || // Added in 3.7
325       Name.startswith("avx.vbroadcastf128") || // Added in 4.0
326       Name == "avx2.vbroadcasti128" || // Added in 3.7
327       Name.startswith("avx512.mask.broadcastf") || // Added in 6.0
328       Name.startswith("avx512.mask.broadcasti") || // Added in 6.0
329       Name == "xop.vpcmov" || // Added in 3.8
330       Name == "xop.vpcmov.256" || // Added in 5.0
331       Name.startswith("avx512.mask.move.s") || // Added in 4.0
332       Name.startswith("avx512.cvtmask2") || // Added in 5.0
333       (Name.startswith("xop.vpcom") && // Added in 3.2
334        F->arg_size() == 2) ||
335       Name.startswith("avx512.ptestm") || //Added in 6.0
336       Name.startswith("avx512.ptestnm") || //Added in 6.0
337       Name.startswith("sse2.pavg") || // Added in 6.0
338       Name.startswith("avx2.pavg") || // Added in 6.0
339       Name.startswith("avx512.mask.pavg")) // Added in 6.0
340     return true;
341 
342   return false;
343 }
344 
345 static bool UpgradeX86IntrinsicFunction(Function *F, StringRef Name,
346                                         Function *&NewFn) {
347   // Only handle intrinsics that start with "x86.".
348   if (!Name.startswith("x86."))
349     return false;
350   // Remove "x86." prefix.
351   Name = Name.substr(4);
352 
353   if (ShouldUpgradeX86Intrinsic(F, Name)) {
354     NewFn = nullptr;
355     return true;
356   }
357 
358   // SSE4.1 ptest functions may have an old signature.
359   if (Name.startswith("sse41.ptest")) { // Added in 3.2
360     if (Name.substr(11) == "c")
361       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestc, NewFn);
362     if (Name.substr(11) == "z")
363       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestz, NewFn);
364     if (Name.substr(11) == "nzc")
365       return UpgradePTESTIntrinsic(F, Intrinsic::x86_sse41_ptestnzc, NewFn);
366   }
367   // Several blend and other instructions with masks used the wrong number of
368   // bits.
369   if (Name == "sse41.insertps") // Added in 3.6
370     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_insertps,
371                                             NewFn);
372   if (Name == "sse41.dppd") // Added in 3.6
373     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dppd,
374                                             NewFn);
375   if (Name == "sse41.dpps") // Added in 3.6
376     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_dpps,
377                                             NewFn);
378   if (Name == "sse41.mpsadbw") // Added in 3.6
379     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_sse41_mpsadbw,
380                                             NewFn);
381   if (Name == "avx.dp.ps.256") // Added in 3.6
382     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx_dp_ps_256,
383                                             NewFn);
384   if (Name == "avx2.mpsadbw") // Added in 3.6
385     return UpgradeX86IntrinsicsWith8BitMask(F, Intrinsic::x86_avx2_mpsadbw,
386                                             NewFn);
387   if (Name == "avx512.mask.cmp.pd.128") // Added in 7.0
388     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_128,
389                                      NewFn);
390   if (Name == "avx512.mask.cmp.pd.256") // Added in 7.0
391     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_256,
392                                      NewFn);
393   if (Name == "avx512.mask.cmp.pd.512") // Added in 7.0
394     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_pd_512,
395                                      NewFn);
396   if (Name == "avx512.mask.cmp.ps.128") // Added in 7.0
397     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_128,
398                                      NewFn);
399   if (Name == "avx512.mask.cmp.ps.256") // Added in 7.0
400     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_256,
401                                      NewFn);
402   if (Name == "avx512.mask.cmp.ps.512") // Added in 7.0
403     return UpgradeX86MaskedFPCompare(F, Intrinsic::x86_avx512_mask_cmp_ps_512,
404                                      NewFn);
405 
406   // frcz.ss/sd may need to have an argument dropped. Added in 3.2
407   if (Name.startswith("xop.vfrcz.ss") && F->arg_size() == 2) {
408     rename(F);
409     NewFn = Intrinsic::getDeclaration(F->getParent(),
410                                       Intrinsic::x86_xop_vfrcz_ss);
411     return true;
412   }
413   if (Name.startswith("xop.vfrcz.sd") && F->arg_size() == 2) {
414     rename(F);
415     NewFn = Intrinsic::getDeclaration(F->getParent(),
416                                       Intrinsic::x86_xop_vfrcz_sd);
417     return true;
418   }
419   // Upgrade any XOP PERMIL2 index operand still using a float/double vector.
420   if (Name.startswith("xop.vpermil2")) { // Added in 3.9
421     auto Idx = F->getFunctionType()->getParamType(2);
422     if (Idx->isFPOrFPVectorTy()) {
423       rename(F);
424       unsigned IdxSize = Idx->getPrimitiveSizeInBits();
425       unsigned EltSize = Idx->getScalarSizeInBits();
426       Intrinsic::ID Permil2ID;
427       if (EltSize == 64 && IdxSize == 128)
428         Permil2ID = Intrinsic::x86_xop_vpermil2pd;
429       else if (EltSize == 32 && IdxSize == 128)
430         Permil2ID = Intrinsic::x86_xop_vpermil2ps;
431       else if (EltSize == 64 && IdxSize == 256)
432         Permil2ID = Intrinsic::x86_xop_vpermil2pd_256;
433       else
434         Permil2ID = Intrinsic::x86_xop_vpermil2ps_256;
435       NewFn = Intrinsic::getDeclaration(F->getParent(), Permil2ID);
436       return true;
437     }
438   }
439 
440   return false;
441 }
442 
443 static bool UpgradeIntrinsicFunction1(Function *F, Function *&NewFn) {
444   assert(F && "Illegal to upgrade a non-existent Function.");
445 
446   // Quickly eliminate it, if it's not a candidate.
447   StringRef Name = F->getName();
448   if (Name.size() <= 8 || !Name.startswith("llvm."))
449     return false;
450   Name = Name.substr(5); // Strip off "llvm."
451 
452   switch (Name[0]) {
453   default: break;
454   case 'a': {
455     if (Name.startswith("arm.rbit") || Name.startswith("aarch64.rbit")) {
456       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::bitreverse,
457                                         F->arg_begin()->getType());
458       return true;
459     }
460     if (Name.startswith("arm.neon.vclz")) {
461       Type* args[2] = {
462         F->arg_begin()->getType(),
463         Type::getInt1Ty(F->getContext())
464       };
465       // Can't use Intrinsic::getDeclaration here as it adds a ".i1" to
466       // the end of the name. Change name from llvm.arm.neon.vclz.* to
467       //  llvm.ctlz.*
468       FunctionType* fType = FunctionType::get(F->getReturnType(), args, false);
469       NewFn = Function::Create(fType, F->getLinkage(),
470                                "llvm.ctlz." + Name.substr(14), F->getParent());
471       return true;
472     }
473     if (Name.startswith("arm.neon.vcnt")) {
474       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
475                                         F->arg_begin()->getType());
476       return true;
477     }
478     Regex vldRegex("^arm\\.neon\\.vld([1234]|[234]lane)\\.v[a-z0-9]*$");
479     if (vldRegex.match(Name)) {
480       auto fArgs = F->getFunctionType()->params();
481       SmallVector<Type *, 4> Tys(fArgs.begin(), fArgs.end());
482       // Can't use Intrinsic::getDeclaration here as the return types might
483       // then only be structurally equal.
484       FunctionType* fType = FunctionType::get(F->getReturnType(), Tys, false);
485       NewFn = Function::Create(fType, F->getLinkage(),
486                                "llvm." + Name + ".p0i8", F->getParent());
487       return true;
488     }
489     Regex vstRegex("^arm\\.neon\\.vst([1234]|[234]lane)\\.v[a-z0-9]*$");
490     if (vstRegex.match(Name)) {
491       static const Intrinsic::ID StoreInts[] = {Intrinsic::arm_neon_vst1,
492                                                 Intrinsic::arm_neon_vst2,
493                                                 Intrinsic::arm_neon_vst3,
494                                                 Intrinsic::arm_neon_vst4};
495 
496       static const Intrinsic::ID StoreLaneInts[] = {
497         Intrinsic::arm_neon_vst2lane, Intrinsic::arm_neon_vst3lane,
498         Intrinsic::arm_neon_vst4lane
499       };
500 
501       auto fArgs = F->getFunctionType()->params();
502       Type *Tys[] = {fArgs[0], fArgs[1]};
503       if (Name.find("lane") == StringRef::npos)
504         NewFn = Intrinsic::getDeclaration(F->getParent(),
505                                           StoreInts[fArgs.size() - 3], Tys);
506       else
507         NewFn = Intrinsic::getDeclaration(F->getParent(),
508                                           StoreLaneInts[fArgs.size() - 5], Tys);
509       return true;
510     }
511     if (Name == "aarch64.thread.pointer" || Name == "arm.thread.pointer") {
512       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::thread_pointer);
513       return true;
514     }
515     break;
516   }
517 
518   case 'c': {
519     if (Name.startswith("ctlz.") && F->arg_size() == 1) {
520       rename(F);
521       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
522                                         F->arg_begin()->getType());
523       return true;
524     }
525     if (Name.startswith("cttz.") && F->arg_size() == 1) {
526       rename(F);
527       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::cttz,
528                                         F->arg_begin()->getType());
529       return true;
530     }
531     break;
532   }
533   case 'd': {
534     if (Name == "dbg.value" && F->arg_size() == 4) {
535       rename(F);
536       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::dbg_value);
537       return true;
538     }
539     break;
540   }
541   case 'i':
542   case 'l': {
543     bool IsLifetimeStart = Name.startswith("lifetime.start");
544     if (IsLifetimeStart || Name.startswith("invariant.start")) {
545       Intrinsic::ID ID = IsLifetimeStart ?
546         Intrinsic::lifetime_start : Intrinsic::invariant_start;
547       auto Args = F->getFunctionType()->params();
548       Type* ObjectPtr[1] = {Args[1]};
549       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
550         rename(F);
551         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
552         return true;
553       }
554     }
555 
556     bool IsLifetimeEnd = Name.startswith("lifetime.end");
557     if (IsLifetimeEnd || Name.startswith("invariant.end")) {
558       Intrinsic::ID ID = IsLifetimeEnd ?
559         Intrinsic::lifetime_end : Intrinsic::invariant_end;
560 
561       auto Args = F->getFunctionType()->params();
562       Type* ObjectPtr[1] = {Args[IsLifetimeEnd ? 1 : 2]};
563       if (F->getName() != Intrinsic::getName(ID, ObjectPtr)) {
564         rename(F);
565         NewFn = Intrinsic::getDeclaration(F->getParent(), ID, ObjectPtr);
566         return true;
567       }
568     }
569     if (Name.startswith("invariant.group.barrier")) {
570       // Rename invariant.group.barrier to launder.invariant.group
571       auto Args = F->getFunctionType()->params();
572       Type* ObjectPtr[1] = {Args[0]};
573       rename(F);
574       NewFn = Intrinsic::getDeclaration(F->getParent(),
575           Intrinsic::launder_invariant_group, ObjectPtr);
576       return true;
577 
578     }
579 
580     break;
581   }
582   case 'm': {
583     if (Name.startswith("masked.load.")) {
584       Type *Tys[] = { F->getReturnType(), F->arg_begin()->getType() };
585       if (F->getName() != Intrinsic::getName(Intrinsic::masked_load, Tys)) {
586         rename(F);
587         NewFn = Intrinsic::getDeclaration(F->getParent(),
588                                           Intrinsic::masked_load,
589                                           Tys);
590         return true;
591       }
592     }
593     if (Name.startswith("masked.store.")) {
594       auto Args = F->getFunctionType()->params();
595       Type *Tys[] = { Args[0], Args[1] };
596       if (F->getName() != Intrinsic::getName(Intrinsic::masked_store, Tys)) {
597         rename(F);
598         NewFn = Intrinsic::getDeclaration(F->getParent(),
599                                           Intrinsic::masked_store,
600                                           Tys);
601         return true;
602       }
603     }
604     // Renaming gather/scatter intrinsics with no address space overloading
605     // to the new overload which includes an address space
606     if (Name.startswith("masked.gather.")) {
607       Type *Tys[] = {F->getReturnType(), F->arg_begin()->getType()};
608       if (F->getName() != Intrinsic::getName(Intrinsic::masked_gather, Tys)) {
609         rename(F);
610         NewFn = Intrinsic::getDeclaration(F->getParent(),
611                                           Intrinsic::masked_gather, Tys);
612         return true;
613       }
614     }
615     if (Name.startswith("masked.scatter.")) {
616       auto Args = F->getFunctionType()->params();
617       Type *Tys[] = {Args[0], Args[1]};
618       if (F->getName() != Intrinsic::getName(Intrinsic::masked_scatter, Tys)) {
619         rename(F);
620         NewFn = Intrinsic::getDeclaration(F->getParent(),
621                                           Intrinsic::masked_scatter, Tys);
622         return true;
623       }
624     }
625     // Updating the memory intrinsics (memcpy/memmove/memset) that have an
626     // alignment parameter to embedding the alignment as an attribute of
627     // the pointer args.
628     if (Name.startswith("memcpy.") && F->arg_size() == 5) {
629       rename(F);
630       // Get the types of dest, src, and len
631       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
632       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memcpy,
633                                         ParamTypes);
634       return true;
635     }
636     if (Name.startswith("memmove.") && F->arg_size() == 5) {
637       rename(F);
638       // Get the types of dest, src, and len
639       ArrayRef<Type *> ParamTypes = F->getFunctionType()->params().slice(0, 3);
640       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memmove,
641                                         ParamTypes);
642       return true;
643     }
644     if (Name.startswith("memset.") && F->arg_size() == 5) {
645       rename(F);
646       // Get the types of dest, and len
647       const auto *FT = F->getFunctionType();
648       Type *ParamTypes[2] = {
649           FT->getParamType(0), // Dest
650           FT->getParamType(2)  // len
651       };
652       NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::memset,
653                                         ParamTypes);
654       return true;
655     }
656     break;
657   }
658   case 'n': {
659     if (Name.startswith("nvvm.")) {
660       Name = Name.substr(5);
661 
662       // The following nvvm intrinsics correspond exactly to an LLVM intrinsic.
663       Intrinsic::ID IID = StringSwitch<Intrinsic::ID>(Name)
664                               .Cases("brev32", "brev64", Intrinsic::bitreverse)
665                               .Case("clz.i", Intrinsic::ctlz)
666                               .Case("popc.i", Intrinsic::ctpop)
667                               .Default(Intrinsic::not_intrinsic);
668       if (IID != Intrinsic::not_intrinsic && F->arg_size() == 1) {
669         NewFn = Intrinsic::getDeclaration(F->getParent(), IID,
670                                           {F->getReturnType()});
671         return true;
672       }
673 
674       // The following nvvm intrinsics correspond exactly to an LLVM idiom, but
675       // not to an intrinsic alone.  We expand them in UpgradeIntrinsicCall.
676       //
677       // TODO: We could add lohi.i2d.
678       bool Expand = StringSwitch<bool>(Name)
679                         .Cases("abs.i", "abs.ll", true)
680                         .Cases("clz.ll", "popc.ll", "h2f", true)
681                         .Cases("max.i", "max.ll", "max.ui", "max.ull", true)
682                         .Cases("min.i", "min.ll", "min.ui", "min.ull", true)
683                         .Default(false);
684       if (Expand) {
685         NewFn = nullptr;
686         return true;
687       }
688     }
689     break;
690   }
691   case 'o':
692     // We only need to change the name to match the mangling including the
693     // address space.
694     if (Name.startswith("objectsize.")) {
695       Type *Tys[2] = { F->getReturnType(), F->arg_begin()->getType() };
696       if (F->arg_size() == 2 ||
697           F->getName() != Intrinsic::getName(Intrinsic::objectsize, Tys)) {
698         rename(F);
699         NewFn = Intrinsic::getDeclaration(F->getParent(), Intrinsic::objectsize,
700                                           Tys);
701         return true;
702       }
703     }
704     break;
705 
706   case 's':
707     if (Name == "stackprotectorcheck") {
708       NewFn = nullptr;
709       return true;
710     }
711     break;
712 
713   case 'x':
714     if (UpgradeX86IntrinsicFunction(F, Name, NewFn))
715       return true;
716   }
717   // Remangle our intrinsic since we upgrade the mangling
718   auto Result = llvm::Intrinsic::remangleIntrinsicFunction(F);
719   if (Result != None) {
720     NewFn = Result.getValue();
721     return true;
722   }
723 
724   //  This may not belong here. This function is effectively being overloaded
725   //  to both detect an intrinsic which needs upgrading, and to provide the
726   //  upgraded form of the intrinsic. We should perhaps have two separate
727   //  functions for this.
728   return false;
729 }
730 
731 bool llvm::UpgradeIntrinsicFunction(Function *F, Function *&NewFn) {
732   NewFn = nullptr;
733   bool Upgraded = UpgradeIntrinsicFunction1(F, NewFn);
734   assert(F != NewFn && "Intrinsic function upgraded to the same function");
735 
736   // Upgrade intrinsic attributes.  This does not change the function.
737   if (NewFn)
738     F = NewFn;
739   if (Intrinsic::ID id = F->getIntrinsicID())
740     F->setAttributes(Intrinsic::getAttributes(F->getContext(), id));
741   return Upgraded;
742 }
743 
744 bool llvm::UpgradeGlobalVariable(GlobalVariable *GV) {
745   // Nothing to do yet.
746   return false;
747 }
748 
749 // Handles upgrading SSE2/AVX2/AVX512BW PSLLDQ intrinsics by converting them
750 // to byte shuffles.
751 static Value *UpgradeX86PSLLDQIntrinsics(IRBuilder<> &Builder,
752                                          Value *Op, unsigned Shift) {
753   Type *ResultTy = Op->getType();
754   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
755 
756   // Bitcast from a 64-bit element type to a byte element type.
757   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
758   Op = Builder.CreateBitCast(Op, VecTy, "cast");
759 
760   // We'll be shuffling in zeroes.
761   Value *Res = Constant::getNullValue(VecTy);
762 
763   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
764   // we'll just return the zero vector.
765   if (Shift < 16) {
766     uint32_t Idxs[64];
767     // 256/512-bit version is split into 2/4 16-byte lanes.
768     for (unsigned l = 0; l != NumElts; l += 16)
769       for (unsigned i = 0; i != 16; ++i) {
770         unsigned Idx = NumElts + i - Shift;
771         if (Idx < NumElts)
772           Idx -= NumElts - 16; // end of lane, switch operand.
773         Idxs[l + i] = Idx + l;
774       }
775 
776     Res = Builder.CreateShuffleVector(Res, Op, makeArrayRef(Idxs, NumElts));
777   }
778 
779   // Bitcast back to a 64-bit element type.
780   return Builder.CreateBitCast(Res, ResultTy, "cast");
781 }
782 
783 // Handles upgrading SSE2/AVX2/AVX512BW PSRLDQ intrinsics by converting them
784 // to byte shuffles.
785 static Value *UpgradeX86PSRLDQIntrinsics(IRBuilder<> &Builder, Value *Op,
786                                          unsigned Shift) {
787   Type *ResultTy = Op->getType();
788   unsigned NumElts = ResultTy->getVectorNumElements() * 8;
789 
790   // Bitcast from a 64-bit element type to a byte element type.
791   Type *VecTy = VectorType::get(Builder.getInt8Ty(), NumElts);
792   Op = Builder.CreateBitCast(Op, VecTy, "cast");
793 
794   // We'll be shuffling in zeroes.
795   Value *Res = Constant::getNullValue(VecTy);
796 
797   // If shift is less than 16, emit a shuffle to move the bytes. Otherwise,
798   // we'll just return the zero vector.
799   if (Shift < 16) {
800     uint32_t Idxs[64];
801     // 256/512-bit version is split into 2/4 16-byte lanes.
802     for (unsigned l = 0; l != NumElts; l += 16)
803       for (unsigned i = 0; i != 16; ++i) {
804         unsigned Idx = i + Shift;
805         if (Idx >= 16)
806           Idx += NumElts - 16; // end of lane, switch operand.
807         Idxs[l + i] = Idx + l;
808       }
809 
810     Res = Builder.CreateShuffleVector(Op, Res, makeArrayRef(Idxs, NumElts));
811   }
812 
813   // Bitcast back to a 64-bit element type.
814   return Builder.CreateBitCast(Res, ResultTy, "cast");
815 }
816 
817 static Value *getX86MaskVec(IRBuilder<> &Builder, Value *Mask,
818                             unsigned NumElts) {
819   llvm::VectorType *MaskTy = llvm::VectorType::get(Builder.getInt1Ty(),
820                              cast<IntegerType>(Mask->getType())->getBitWidth());
821   Mask = Builder.CreateBitCast(Mask, MaskTy);
822 
823   // If we have less than 8 elements, then the starting mask was an i8 and
824   // we need to extract down to the right number of elements.
825   if (NumElts < 8) {
826     uint32_t Indices[4];
827     for (unsigned i = 0; i != NumElts; ++i)
828       Indices[i] = i;
829     Mask = Builder.CreateShuffleVector(Mask, Mask,
830                                        makeArrayRef(Indices, NumElts),
831                                        "extract");
832   }
833 
834   return Mask;
835 }
836 
837 static Value *EmitX86Select(IRBuilder<> &Builder, Value *Mask,
838                             Value *Op0, Value *Op1) {
839   // If the mask is all ones just emit the align operation.
840   if (const auto *C = dyn_cast<Constant>(Mask))
841     if (C->isAllOnesValue())
842       return Op0;
843 
844   Mask = getX86MaskVec(Builder, Mask, Op0->getType()->getVectorNumElements());
845   return Builder.CreateSelect(Mask, Op0, Op1);
846 }
847 
848 // Handle autoupgrade for masked PALIGNR and VALIGND/Q intrinsics.
849 // PALIGNR handles large immediates by shifting while VALIGN masks the immediate
850 // so we need to handle both cases. VALIGN also doesn't have 128-bit lanes.
851 static Value *UpgradeX86ALIGNIntrinsics(IRBuilder<> &Builder, Value *Op0,
852                                         Value *Op1, Value *Shift,
853                                         Value *Passthru, Value *Mask,
854                                         bool IsVALIGN) {
855   unsigned ShiftVal = cast<llvm::ConstantInt>(Shift)->getZExtValue();
856 
857   unsigned NumElts = Op0->getType()->getVectorNumElements();
858   assert((IsVALIGN || NumElts % 16 == 0) && "Illegal NumElts for PALIGNR!");
859   assert((!IsVALIGN || NumElts <= 16) && "NumElts too large for VALIGN!");
860   assert(isPowerOf2_32(NumElts) && "NumElts not a power of 2!");
861 
862   // Mask the immediate for VALIGN.
863   if (IsVALIGN)
864     ShiftVal &= (NumElts - 1);
865 
866   // If palignr is shifting the pair of vectors more than the size of two
867   // lanes, emit zero.
868   if (ShiftVal >= 32)
869     return llvm::Constant::getNullValue(Op0->getType());
870 
871   // If palignr is shifting the pair of input vectors more than one lane,
872   // but less than two lanes, convert to shifting in zeroes.
873   if (ShiftVal > 16) {
874     ShiftVal -= 16;
875     Op1 = Op0;
876     Op0 = llvm::Constant::getNullValue(Op0->getType());
877   }
878 
879   uint32_t Indices[64];
880   // 256-bit palignr operates on 128-bit lanes so we need to handle that
881   for (unsigned l = 0; l < NumElts; l += 16) {
882     for (unsigned i = 0; i != 16; ++i) {
883       unsigned Idx = ShiftVal + i;
884       if (!IsVALIGN && Idx >= 16) // Disable wrap for VALIGN.
885         Idx += NumElts - 16; // End of lane, switch operand.
886       Indices[l + i] = Idx + l;
887     }
888   }
889 
890   Value *Align = Builder.CreateShuffleVector(Op1, Op0,
891                                              makeArrayRef(Indices, NumElts),
892                                              "palignr");
893 
894   return EmitX86Select(Builder, Mask, Align, Passthru);
895 }
896 
897 static Value *UpgradeMaskedStore(IRBuilder<> &Builder,
898                                  Value *Ptr, Value *Data, Value *Mask,
899                                  bool Aligned) {
900   // Cast the pointer to the right type.
901   Ptr = Builder.CreateBitCast(Ptr,
902                               llvm::PointerType::getUnqual(Data->getType()));
903   unsigned Align =
904     Aligned ? cast<VectorType>(Data->getType())->getBitWidth() / 8 : 1;
905 
906   // If the mask is all ones just emit a regular store.
907   if (const auto *C = dyn_cast<Constant>(Mask))
908     if (C->isAllOnesValue())
909       return Builder.CreateAlignedStore(Data, Ptr, Align);
910 
911   // Convert the mask from an integer type to a vector of i1.
912   unsigned NumElts = Data->getType()->getVectorNumElements();
913   Mask = getX86MaskVec(Builder, Mask, NumElts);
914   return Builder.CreateMaskedStore(Data, Ptr, Align, Mask);
915 }
916 
917 static Value *UpgradeMaskedLoad(IRBuilder<> &Builder,
918                                 Value *Ptr, Value *Passthru, Value *Mask,
919                                 bool Aligned) {
920   // Cast the pointer to the right type.
921   Ptr = Builder.CreateBitCast(Ptr,
922                              llvm::PointerType::getUnqual(Passthru->getType()));
923   unsigned Align =
924     Aligned ? cast<VectorType>(Passthru->getType())->getBitWidth() / 8 : 1;
925 
926   // If the mask is all ones just emit a regular store.
927   if (const auto *C = dyn_cast<Constant>(Mask))
928     if (C->isAllOnesValue())
929       return Builder.CreateAlignedLoad(Ptr, Align);
930 
931   // Convert the mask from an integer type to a vector of i1.
932   unsigned NumElts = Passthru->getType()->getVectorNumElements();
933   Mask = getX86MaskVec(Builder, Mask, NumElts);
934   return Builder.CreateMaskedLoad(Ptr, Align, Mask, Passthru);
935 }
936 
937 static Value *upgradeAbs(IRBuilder<> &Builder, CallInst &CI) {
938   Value *Op0 = CI.getArgOperand(0);
939   llvm::Type *Ty = Op0->getType();
940   Value *Zero = llvm::Constant::getNullValue(Ty);
941   Value *Cmp = Builder.CreateICmp(ICmpInst::ICMP_SGT, Op0, Zero);
942   Value *Neg = Builder.CreateNeg(Op0);
943   Value *Res = Builder.CreateSelect(Cmp, Op0, Neg);
944 
945   if (CI.getNumArgOperands() == 3)
946     Res = EmitX86Select(Builder,CI.getArgOperand(2), Res, CI.getArgOperand(1));
947 
948   return Res;
949 }
950 
951 static Value *upgradeIntMinMax(IRBuilder<> &Builder, CallInst &CI,
952                                ICmpInst::Predicate Pred) {
953   Value *Op0 = CI.getArgOperand(0);
954   Value *Op1 = CI.getArgOperand(1);
955   Value *Cmp = Builder.CreateICmp(Pred, Op0, Op1);
956   Value *Res = Builder.CreateSelect(Cmp, Op0, Op1);
957 
958   if (CI.getNumArgOperands() == 4)
959     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
960 
961   return Res;
962 }
963 
964 static Value *upgradePMULDQ(IRBuilder<> &Builder, CallInst &CI, bool IsSigned) {
965   Type *Ty = CI.getType();
966 
967   // Arguments have a vXi32 type so cast to vXi64.
968   Value *LHS = Builder.CreateBitCast(CI.getArgOperand(0), Ty);
969   Value *RHS = Builder.CreateBitCast(CI.getArgOperand(1), Ty);
970 
971   if (IsSigned) {
972     // Shift left then arithmetic shift right.
973     Constant *ShiftAmt = ConstantInt::get(Ty, 32);
974     LHS = Builder.CreateShl(LHS, ShiftAmt);
975     LHS = Builder.CreateAShr(LHS, ShiftAmt);
976     RHS = Builder.CreateShl(RHS, ShiftAmt);
977     RHS = Builder.CreateAShr(RHS, ShiftAmt);
978   } else {
979     // Clear the upper bits.
980     Constant *Mask = ConstantInt::get(Ty, 0xffffffff);
981     LHS = Builder.CreateAnd(LHS, Mask);
982     RHS = Builder.CreateAnd(RHS, Mask);
983   }
984 
985   Value *Res = Builder.CreateMul(LHS, RHS);
986 
987   if (CI.getNumArgOperands() == 4)
988     Res = EmitX86Select(Builder, CI.getArgOperand(3), Res, CI.getArgOperand(2));
989 
990   return Res;
991 }
992 
993 // Applying mask on vector of i1's and make sure result is at least 8 bits wide.
994 static Value *ApplyX86MaskOn1BitsVec(IRBuilder<> &Builder,Value *Vec, Value *Mask,
995                                      unsigned NumElts) {
996   if (Mask) {
997     const auto *C = dyn_cast<Constant>(Mask);
998     if (!C || !C->isAllOnesValue())
999       Vec = Builder.CreateAnd(Vec, getX86MaskVec(Builder, Mask, NumElts));
1000   }
1001 
1002   if (NumElts < 8) {
1003     uint32_t Indices[8];
1004     for (unsigned i = 0; i != NumElts; ++i)
1005       Indices[i] = i;
1006     for (unsigned i = NumElts; i != 8; ++i)
1007       Indices[i] = NumElts + i % NumElts;
1008     Vec = Builder.CreateShuffleVector(Vec,
1009                                       Constant::getNullValue(Vec->getType()),
1010                                       Indices);
1011   }
1012   return Builder.CreateBitCast(Vec, Builder.getIntNTy(std::max(NumElts, 8U)));
1013 }
1014 
1015 static Value *upgradeMaskedCompare(IRBuilder<> &Builder, CallInst &CI,
1016                                    unsigned CC, bool Signed) {
1017   Value *Op0 = CI.getArgOperand(0);
1018   unsigned NumElts = Op0->getType()->getVectorNumElements();
1019 
1020   Value *Cmp;
1021   if (CC == 3) {
1022     Cmp = Constant::getNullValue(llvm::VectorType::get(Builder.getInt1Ty(), NumElts));
1023   } else if (CC == 7) {
1024     Cmp = Constant::getAllOnesValue(llvm::VectorType::get(Builder.getInt1Ty(), NumElts));
1025   } else {
1026     ICmpInst::Predicate Pred;
1027     switch (CC) {
1028     default: llvm_unreachable("Unknown condition code");
1029     case 0: Pred = ICmpInst::ICMP_EQ;  break;
1030     case 1: Pred = Signed ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT; break;
1031     case 2: Pred = Signed ? ICmpInst::ICMP_SLE : ICmpInst::ICMP_ULE; break;
1032     case 4: Pred = ICmpInst::ICMP_NE;  break;
1033     case 5: Pred = Signed ? ICmpInst::ICMP_SGE : ICmpInst::ICMP_UGE; break;
1034     case 6: Pred = Signed ? ICmpInst::ICMP_SGT : ICmpInst::ICMP_UGT; break;
1035     }
1036     Cmp = Builder.CreateICmp(Pred, Op0, CI.getArgOperand(1));
1037   }
1038 
1039   Value *Mask = CI.getArgOperand(CI.getNumArgOperands() - 1);
1040 
1041   return ApplyX86MaskOn1BitsVec(Builder, Cmp, Mask, NumElts);
1042 }
1043 
1044 // Replace a masked intrinsic with an older unmasked intrinsic.
1045 static Value *UpgradeX86MaskedShift(IRBuilder<> &Builder, CallInst &CI,
1046                                     Intrinsic::ID IID) {
1047   Function *Intrin = Intrinsic::getDeclaration(CI.getModule(), IID);
1048   Value *Rep = Builder.CreateCall(Intrin,
1049                                  { CI.getArgOperand(0), CI.getArgOperand(1) });
1050   return EmitX86Select(Builder, CI.getArgOperand(3), Rep, CI.getArgOperand(2));
1051 }
1052 
1053 static Value* upgradeMaskedMove(IRBuilder<> &Builder, CallInst &CI) {
1054   Value* A = CI.getArgOperand(0);
1055   Value* B = CI.getArgOperand(1);
1056   Value* Src = CI.getArgOperand(2);
1057   Value* Mask = CI.getArgOperand(3);
1058 
1059   Value* AndNode = Builder.CreateAnd(Mask, APInt(8, 1));
1060   Value* Cmp = Builder.CreateIsNotNull(AndNode);
1061   Value* Extract1 = Builder.CreateExtractElement(B, (uint64_t)0);
1062   Value* Extract2 = Builder.CreateExtractElement(Src, (uint64_t)0);
1063   Value* Select = Builder.CreateSelect(Cmp, Extract1, Extract2);
1064   return Builder.CreateInsertElement(A, Select, (uint64_t)0);
1065 }
1066 
1067 
1068 static Value* UpgradeMaskToInt(IRBuilder<> &Builder, CallInst &CI) {
1069   Value* Op = CI.getArgOperand(0);
1070   Type* ReturnOp = CI.getType();
1071   unsigned NumElts = CI.getType()->getVectorNumElements();
1072   Value *Mask = getX86MaskVec(Builder, Op, NumElts);
1073   return Builder.CreateSExt(Mask, ReturnOp, "vpmovm2");
1074 }
1075 
1076 // Replace intrinsic with unmasked version and a select.
1077 static bool upgradeAVX512MaskToSelect(StringRef Name, IRBuilder<> &Builder,
1078                                       CallInst &CI, Value *&Rep) {
1079   Name = Name.substr(12); // Remove avx512.mask.
1080 
1081   unsigned VecWidth = CI.getType()->getPrimitiveSizeInBits();
1082   unsigned EltWidth = CI.getType()->getScalarSizeInBits();
1083   Intrinsic::ID IID;
1084   if (Name.startswith("max.p")) {
1085     if (VecWidth == 128 && EltWidth == 32)
1086       IID = Intrinsic::x86_sse_max_ps;
1087     else if (VecWidth == 128 && EltWidth == 64)
1088       IID = Intrinsic::x86_sse2_max_pd;
1089     else if (VecWidth == 256 && EltWidth == 32)
1090       IID = Intrinsic::x86_avx_max_ps_256;
1091     else if (VecWidth == 256 && EltWidth == 64)
1092       IID = Intrinsic::x86_avx_max_pd_256;
1093     else
1094       llvm_unreachable("Unexpected intrinsic");
1095   } else if (Name.startswith("min.p")) {
1096     if (VecWidth == 128 && EltWidth == 32)
1097       IID = Intrinsic::x86_sse_min_ps;
1098     else if (VecWidth == 128 && EltWidth == 64)
1099       IID = Intrinsic::x86_sse2_min_pd;
1100     else if (VecWidth == 256 && EltWidth == 32)
1101       IID = Intrinsic::x86_avx_min_ps_256;
1102     else if (VecWidth == 256 && EltWidth == 64)
1103       IID = Intrinsic::x86_avx_min_pd_256;
1104     else
1105       llvm_unreachable("Unexpected intrinsic");
1106   } else if (Name.startswith("pshuf.b.")) {
1107     if (VecWidth == 128)
1108       IID = Intrinsic::x86_ssse3_pshuf_b_128;
1109     else if (VecWidth == 256)
1110       IID = Intrinsic::x86_avx2_pshuf_b;
1111     else if (VecWidth == 512)
1112       IID = Intrinsic::x86_avx512_pshuf_b_512;
1113     else
1114       llvm_unreachable("Unexpected intrinsic");
1115   } else if (Name.startswith("pmul.hr.sw.")) {
1116     if (VecWidth == 128)
1117       IID = Intrinsic::x86_ssse3_pmul_hr_sw_128;
1118     else if (VecWidth == 256)
1119       IID = Intrinsic::x86_avx2_pmul_hr_sw;
1120     else if (VecWidth == 512)
1121       IID = Intrinsic::x86_avx512_pmul_hr_sw_512;
1122     else
1123       llvm_unreachable("Unexpected intrinsic");
1124   } else if (Name.startswith("pmulh.w.")) {
1125     if (VecWidth == 128)
1126       IID = Intrinsic::x86_sse2_pmulh_w;
1127     else if (VecWidth == 256)
1128       IID = Intrinsic::x86_avx2_pmulh_w;
1129     else if (VecWidth == 512)
1130       IID = Intrinsic::x86_avx512_pmulh_w_512;
1131     else
1132       llvm_unreachable("Unexpected intrinsic");
1133   } else if (Name.startswith("pmulhu.w.")) {
1134     if (VecWidth == 128)
1135       IID = Intrinsic::x86_sse2_pmulhu_w;
1136     else if (VecWidth == 256)
1137       IID = Intrinsic::x86_avx2_pmulhu_w;
1138     else if (VecWidth == 512)
1139       IID = Intrinsic::x86_avx512_pmulhu_w_512;
1140     else
1141       llvm_unreachable("Unexpected intrinsic");
1142   } else if (Name.startswith("pmaddw.d.")) {
1143     if (VecWidth == 128)
1144       IID = Intrinsic::x86_sse2_pmadd_wd;
1145     else if (VecWidth == 256)
1146       IID = Intrinsic::x86_avx2_pmadd_wd;
1147     else if (VecWidth == 512)
1148       IID = Intrinsic::x86_avx512_pmaddw_d_512;
1149     else
1150       llvm_unreachable("Unexpected intrinsic");
1151   } else if (Name.startswith("pmaddubs.w.")) {
1152     if (VecWidth == 128)
1153       IID = Intrinsic::x86_ssse3_pmadd_ub_sw_128;
1154     else if (VecWidth == 256)
1155       IID = Intrinsic::x86_avx2_pmadd_ub_sw;
1156     else if (VecWidth == 512)
1157       IID = Intrinsic::x86_avx512_pmaddubs_w_512;
1158     else
1159       llvm_unreachable("Unexpected intrinsic");
1160   } else if (Name.startswith("packsswb.")) {
1161     if (VecWidth == 128)
1162       IID = Intrinsic::x86_sse2_packsswb_128;
1163     else if (VecWidth == 256)
1164       IID = Intrinsic::x86_avx2_packsswb;
1165     else if (VecWidth == 512)
1166       IID = Intrinsic::x86_avx512_packsswb_512;
1167     else
1168       llvm_unreachable("Unexpected intrinsic");
1169   } else if (Name.startswith("packssdw.")) {
1170     if (VecWidth == 128)
1171       IID = Intrinsic::x86_sse2_packssdw_128;
1172     else if (VecWidth == 256)
1173       IID = Intrinsic::x86_avx2_packssdw;
1174     else if (VecWidth == 512)
1175       IID = Intrinsic::x86_avx512_packssdw_512;
1176     else
1177       llvm_unreachable("Unexpected intrinsic");
1178   } else if (Name.startswith("packuswb.")) {
1179     if (VecWidth == 128)
1180       IID = Intrinsic::x86_sse2_packuswb_128;
1181     else if (VecWidth == 256)
1182       IID = Intrinsic::x86_avx2_packuswb;
1183     else if (VecWidth == 512)
1184       IID = Intrinsic::x86_avx512_packuswb_512;
1185     else
1186       llvm_unreachable("Unexpected intrinsic");
1187   } else if (Name.startswith("packusdw.")) {
1188     if (VecWidth == 128)
1189       IID = Intrinsic::x86_sse41_packusdw;
1190     else if (VecWidth == 256)
1191       IID = Intrinsic::x86_avx2_packusdw;
1192     else if (VecWidth == 512)
1193       IID = Intrinsic::x86_avx512_packusdw_512;
1194     else
1195       llvm_unreachable("Unexpected intrinsic");
1196   } else if (Name.startswith("vpermilvar.")) {
1197     if (VecWidth == 128 && EltWidth == 32)
1198       IID = Intrinsic::x86_avx_vpermilvar_ps;
1199     else if (VecWidth == 128 && EltWidth == 64)
1200       IID = Intrinsic::x86_avx_vpermilvar_pd;
1201     else if (VecWidth == 256 && EltWidth == 32)
1202       IID = Intrinsic::x86_avx_vpermilvar_ps_256;
1203     else if (VecWidth == 256 && EltWidth == 64)
1204       IID = Intrinsic::x86_avx_vpermilvar_pd_256;
1205     else if (VecWidth == 512 && EltWidth == 32)
1206       IID = Intrinsic::x86_avx512_vpermilvar_ps_512;
1207     else if (VecWidth == 512 && EltWidth == 64)
1208       IID = Intrinsic::x86_avx512_vpermilvar_pd_512;
1209     else
1210       llvm_unreachable("Unexpected intrinsic");
1211   } else if (Name == "cvtpd2dq.256") {
1212     IID = Intrinsic::x86_avx_cvt_pd2dq_256;
1213   } else if (Name == "cvtpd2ps.256") {
1214     IID = Intrinsic::x86_avx_cvt_pd2_ps_256;
1215   } else if (Name == "cvttpd2dq.256") {
1216     IID = Intrinsic::x86_avx_cvtt_pd2dq_256;
1217   } else if (Name == "cvttps2dq.128") {
1218     IID = Intrinsic::x86_sse2_cvttps2dq;
1219   } else if (Name == "cvttps2dq.256") {
1220     IID = Intrinsic::x86_avx_cvtt_ps2dq_256;
1221   } else if (Name.startswith("permvar.")) {
1222     bool IsFloat = CI.getType()->isFPOrFPVectorTy();
1223     if (VecWidth == 256 && EltWidth == 32 && IsFloat)
1224       IID = Intrinsic::x86_avx2_permps;
1225     else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
1226       IID = Intrinsic::x86_avx2_permd;
1227     else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
1228       IID = Intrinsic::x86_avx512_permvar_df_256;
1229     else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
1230       IID = Intrinsic::x86_avx512_permvar_di_256;
1231     else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
1232       IID = Intrinsic::x86_avx512_permvar_sf_512;
1233     else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
1234       IID = Intrinsic::x86_avx512_permvar_si_512;
1235     else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
1236       IID = Intrinsic::x86_avx512_permvar_df_512;
1237     else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
1238       IID = Intrinsic::x86_avx512_permvar_di_512;
1239     else if (VecWidth == 128 && EltWidth == 16)
1240       IID = Intrinsic::x86_avx512_permvar_hi_128;
1241     else if (VecWidth == 256 && EltWidth == 16)
1242       IID = Intrinsic::x86_avx512_permvar_hi_256;
1243     else if (VecWidth == 512 && EltWidth == 16)
1244       IID = Intrinsic::x86_avx512_permvar_hi_512;
1245     else if (VecWidth == 128 && EltWidth == 8)
1246       IID = Intrinsic::x86_avx512_permvar_qi_128;
1247     else if (VecWidth == 256 && EltWidth == 8)
1248       IID = Intrinsic::x86_avx512_permvar_qi_256;
1249     else if (VecWidth == 512 && EltWidth == 8)
1250       IID = Intrinsic::x86_avx512_permvar_qi_512;
1251     else
1252       llvm_unreachable("Unexpected intrinsic");
1253   } else
1254     return false;
1255 
1256   SmallVector<Value *, 4> Args(CI.arg_operands().begin(),
1257                                CI.arg_operands().end());
1258   Args.pop_back();
1259   Args.pop_back();
1260   Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI.getModule(), IID),
1261                            Args);
1262   unsigned NumArgs = CI.getNumArgOperands();
1263   Rep = EmitX86Select(Builder, CI.getArgOperand(NumArgs - 1), Rep,
1264                       CI.getArgOperand(NumArgs - 2));
1265   return true;
1266 }
1267 
1268 /// Upgrade comment in call to inline asm that represents an objc retain release
1269 /// marker.
1270 void llvm::UpgradeInlineAsmString(std::string *AsmStr) {
1271   size_t Pos;
1272   if (AsmStr->find("mov\tfp") == 0 &&
1273       AsmStr->find("objc_retainAutoreleaseReturnValue") != std::string::npos &&
1274       (Pos = AsmStr->find("# marker")) != std::string::npos) {
1275     AsmStr->replace(Pos, 1, ";");
1276   }
1277   return;
1278 }
1279 
1280 /// Upgrade a call to an old intrinsic. All argument and return casting must be
1281 /// provided to seamlessly integrate with existing context.
1282 void llvm::UpgradeIntrinsicCall(CallInst *CI, Function *NewFn) {
1283   Function *F = CI->getCalledFunction();
1284   LLVMContext &C = CI->getContext();
1285   IRBuilder<> Builder(C);
1286   Builder.SetInsertPoint(CI->getParent(), CI->getIterator());
1287 
1288   assert(F && "Intrinsic call is not direct?");
1289 
1290   if (!NewFn) {
1291     // Get the Function's name.
1292     StringRef Name = F->getName();
1293 
1294     assert(Name.startswith("llvm.") && "Intrinsic doesn't start with 'llvm.'");
1295     Name = Name.substr(5);
1296 
1297     bool IsX86 = Name.startswith("x86.");
1298     if (IsX86)
1299       Name = Name.substr(4);
1300     bool IsNVVM = Name.startswith("nvvm.");
1301     if (IsNVVM)
1302       Name = Name.substr(5);
1303 
1304     if (IsX86 && Name.startswith("sse4a.movnt.")) {
1305       Module *M = F->getParent();
1306       SmallVector<Metadata *, 1> Elts;
1307       Elts.push_back(
1308           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1309       MDNode *Node = MDNode::get(C, Elts);
1310 
1311       Value *Arg0 = CI->getArgOperand(0);
1312       Value *Arg1 = CI->getArgOperand(1);
1313 
1314       // Nontemporal (unaligned) store of the 0'th element of the float/double
1315       // vector.
1316       Type *SrcEltTy = cast<VectorType>(Arg1->getType())->getElementType();
1317       PointerType *EltPtrTy = PointerType::getUnqual(SrcEltTy);
1318       Value *Addr = Builder.CreateBitCast(Arg0, EltPtrTy, "cast");
1319       Value *Extract =
1320           Builder.CreateExtractElement(Arg1, (uint64_t)0, "extractelement");
1321 
1322       StoreInst *SI = Builder.CreateAlignedStore(Extract, Addr, 1);
1323       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1324 
1325       // Remove intrinsic.
1326       CI->eraseFromParent();
1327       return;
1328     }
1329 
1330     if (IsX86 && (Name.startswith("avx.movnt.") ||
1331                   Name.startswith("avx512.storent."))) {
1332       Module *M = F->getParent();
1333       SmallVector<Metadata *, 1> Elts;
1334       Elts.push_back(
1335           ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
1336       MDNode *Node = MDNode::get(C, Elts);
1337 
1338       Value *Arg0 = CI->getArgOperand(0);
1339       Value *Arg1 = CI->getArgOperand(1);
1340 
1341       // Convert the type of the pointer to a pointer to the stored type.
1342       Value *BC = Builder.CreateBitCast(Arg0,
1343                                         PointerType::getUnqual(Arg1->getType()),
1344                                         "cast");
1345       VectorType *VTy = cast<VectorType>(Arg1->getType());
1346       StoreInst *SI = Builder.CreateAlignedStore(Arg1, BC,
1347                                                  VTy->getBitWidth() / 8);
1348       SI->setMetadata(M->getMDKindID("nontemporal"), Node);
1349 
1350       // Remove intrinsic.
1351       CI->eraseFromParent();
1352       return;
1353     }
1354 
1355     if (IsX86 && Name == "sse2.storel.dq") {
1356       Value *Arg0 = CI->getArgOperand(0);
1357       Value *Arg1 = CI->getArgOperand(1);
1358 
1359       Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
1360       Value *BC0 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
1361       Value *Elt = Builder.CreateExtractElement(BC0, (uint64_t)0);
1362       Value *BC = Builder.CreateBitCast(Arg0,
1363                                         PointerType::getUnqual(Elt->getType()),
1364                                         "cast");
1365       Builder.CreateAlignedStore(Elt, BC, 1);
1366 
1367       // Remove intrinsic.
1368       CI->eraseFromParent();
1369       return;
1370     }
1371 
1372     if (IsX86 && (Name.startswith("sse.storeu.") ||
1373                   Name.startswith("sse2.storeu.") ||
1374                   Name.startswith("avx.storeu."))) {
1375       Value *Arg0 = CI->getArgOperand(0);
1376       Value *Arg1 = CI->getArgOperand(1);
1377 
1378       Arg0 = Builder.CreateBitCast(Arg0,
1379                                    PointerType::getUnqual(Arg1->getType()),
1380                                    "cast");
1381       Builder.CreateAlignedStore(Arg1, Arg0, 1);
1382 
1383       // Remove intrinsic.
1384       CI->eraseFromParent();
1385       return;
1386     }
1387 
1388     if (IsX86 && Name == "avx512.mask.store.ss") {
1389       Value *Mask = Builder.CreateAnd(CI->getArgOperand(2), Builder.getInt8(1));
1390       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1391                          Mask, false);
1392 
1393       // Remove intrinsic.
1394       CI->eraseFromParent();
1395       return;
1396     }
1397 
1398     if (IsX86 && (Name.startswith("avx512.mask.store"))) {
1399       // "avx512.mask.storeu." or "avx512.mask.store."
1400       bool Aligned = Name[17] != 'u'; // "avx512.mask.storeu".
1401       UpgradeMaskedStore(Builder, CI->getArgOperand(0), CI->getArgOperand(1),
1402                          CI->getArgOperand(2), Aligned);
1403 
1404       // Remove intrinsic.
1405       CI->eraseFromParent();
1406       return;
1407     }
1408 
1409     Value *Rep;
1410     // Upgrade packed integer vector compare intrinsics to compare instructions.
1411     if (IsX86 && (Name.startswith("sse2.pcmp") ||
1412                   Name.startswith("avx2.pcmp"))) {
1413       // "sse2.pcpmpeq." "sse2.pcmpgt." "avx2.pcmpeq." or "avx2.pcmpgt."
1414       bool CmpEq = Name[9] == 'e';
1415       Rep = Builder.CreateICmp(CmpEq ? ICmpInst::ICMP_EQ : ICmpInst::ICMP_SGT,
1416                                CI->getArgOperand(0), CI->getArgOperand(1));
1417       Rep = Builder.CreateSExt(Rep, CI->getType(), "");
1418     } else if (IsX86 && (Name.startswith("avx512.broadcastm"))) {
1419       Type *ExtTy = Type::getInt32Ty(C);
1420       if (CI->getOperand(0)->getType()->isIntegerTy(8))
1421         ExtTy = Type::getInt64Ty(C);
1422       unsigned NumElts = CI->getType()->getPrimitiveSizeInBits() /
1423                          ExtTy->getPrimitiveSizeInBits();
1424       Rep = Builder.CreateZExt(CI->getArgOperand(0), ExtTy);
1425       Rep = Builder.CreateVectorSplat(NumElts, Rep);
1426     } else if (IsX86 && (Name.startswith("avx512.ptestm") ||
1427                          Name.startswith("avx512.ptestnm"))) {
1428       Value *Op0 = CI->getArgOperand(0);
1429       Value *Op1 = CI->getArgOperand(1);
1430       Value *Mask = CI->getArgOperand(2);
1431       Rep = Builder.CreateAnd(Op0, Op1);
1432       llvm::Type *Ty = Op0->getType();
1433       Value *Zero = llvm::Constant::getNullValue(Ty);
1434       ICmpInst::Predicate Pred =
1435         Name.startswith("avx512.ptestm") ? ICmpInst::ICMP_NE : ICmpInst::ICMP_EQ;
1436       Rep = Builder.CreateICmp(Pred, Rep, Zero);
1437       unsigned NumElts = Op0->getType()->getVectorNumElements();
1438       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, Mask, NumElts);
1439     } else if (IsX86 && (Name.startswith("avx512.mask.pbroadcast"))){
1440       unsigned NumElts =
1441           CI->getArgOperand(1)->getType()->getVectorNumElements();
1442       Rep = Builder.CreateVectorSplat(NumElts, CI->getArgOperand(0));
1443       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1444                           CI->getArgOperand(1));
1445     } else if (IsX86 && (Name.startswith("avx512.kunpck"))) {
1446       unsigned NumElts = CI->getType()->getScalarSizeInBits();
1447       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), NumElts);
1448       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), NumElts);
1449       uint32_t Indices[64];
1450       for (unsigned i = 0; i != NumElts; ++i)
1451         Indices[i] = i;
1452 
1453       // First extract half of each vector. This gives better codegen than
1454       // doing it in a single shuffle.
1455       LHS = Builder.CreateShuffleVector(LHS, LHS,
1456                                         makeArrayRef(Indices, NumElts / 2));
1457       RHS = Builder.CreateShuffleVector(RHS, RHS,
1458                                         makeArrayRef(Indices, NumElts / 2));
1459       // Concat the vectors.
1460       // NOTE: Operands have to be swapped to match intrinsic definition.
1461       Rep = Builder.CreateShuffleVector(RHS, LHS,
1462                                         makeArrayRef(Indices, NumElts));
1463       Rep = Builder.CreateBitCast(Rep, CI->getType());
1464     } else if (IsX86 && Name == "avx512.kand.w") {
1465       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1466       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1467       Rep = Builder.CreateAnd(LHS, RHS);
1468       Rep = Builder.CreateBitCast(Rep, CI->getType());
1469     } else if (IsX86 && Name == "avx512.kandn.w") {
1470       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1471       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1472       LHS = Builder.CreateNot(LHS);
1473       Rep = Builder.CreateAnd(LHS, RHS);
1474       Rep = Builder.CreateBitCast(Rep, CI->getType());
1475     } else if (IsX86 && Name == "avx512.kor.w") {
1476       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1477       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1478       Rep = Builder.CreateOr(LHS, RHS);
1479       Rep = Builder.CreateBitCast(Rep, CI->getType());
1480     } else if (IsX86 && Name == "avx512.kxor.w") {
1481       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1482       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1483       Rep = Builder.CreateXor(LHS, RHS);
1484       Rep = Builder.CreateBitCast(Rep, CI->getType());
1485     } else if (IsX86 && Name == "avx512.kxnor.w") {
1486       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1487       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1488       LHS = Builder.CreateNot(LHS);
1489       Rep = Builder.CreateXor(LHS, RHS);
1490       Rep = Builder.CreateBitCast(Rep, CI->getType());
1491     } else if (IsX86 && Name == "avx512.knot.w") {
1492       Rep = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1493       Rep = Builder.CreateNot(Rep);
1494       Rep = Builder.CreateBitCast(Rep, CI->getType());
1495     } else if (IsX86 &&
1496                (Name == "avx512.kortestz.w" || Name == "avx512.kortestc.w")) {
1497       Value *LHS = getX86MaskVec(Builder, CI->getArgOperand(0), 16);
1498       Value *RHS = getX86MaskVec(Builder, CI->getArgOperand(1), 16);
1499       Rep = Builder.CreateOr(LHS, RHS);
1500       Rep = Builder.CreateBitCast(Rep, Builder.getInt16Ty());
1501       Value *C;
1502       if (Name[14] == 'c')
1503         C = ConstantInt::getAllOnesValue(Builder.getInt16Ty());
1504       else
1505         C = ConstantInt::getNullValue(Builder.getInt16Ty());
1506       Rep = Builder.CreateICmpEQ(Rep, C);
1507       Rep = Builder.CreateZExt(Rep, Builder.getInt32Ty());
1508     } else if (IsX86 && (Name == "sse.add.ss" || Name == "sse2.add.sd")) {
1509       Type *I32Ty = Type::getInt32Ty(C);
1510       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1511                                                  ConstantInt::get(I32Ty, 0));
1512       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1513                                                  ConstantInt::get(I32Ty, 0));
1514       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1515                                         Builder.CreateFAdd(Elt0, Elt1),
1516                                         ConstantInt::get(I32Ty, 0));
1517     } else if (IsX86 && (Name == "sse.sub.ss" || Name == "sse2.sub.sd")) {
1518       Type *I32Ty = Type::getInt32Ty(C);
1519       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1520                                                  ConstantInt::get(I32Ty, 0));
1521       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1522                                                  ConstantInt::get(I32Ty, 0));
1523       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1524                                         Builder.CreateFSub(Elt0, Elt1),
1525                                         ConstantInt::get(I32Ty, 0));
1526     } else if (IsX86 && (Name == "sse.mul.ss" || Name == "sse2.mul.sd")) {
1527       Type *I32Ty = Type::getInt32Ty(C);
1528       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1529                                                  ConstantInt::get(I32Ty, 0));
1530       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1531                                                  ConstantInt::get(I32Ty, 0));
1532       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1533                                         Builder.CreateFMul(Elt0, Elt1),
1534                                         ConstantInt::get(I32Ty, 0));
1535     } else if (IsX86 && (Name == "sse.div.ss" || Name == "sse2.div.sd")) {
1536       Type *I32Ty = Type::getInt32Ty(C);
1537       Value *Elt0 = Builder.CreateExtractElement(CI->getArgOperand(0),
1538                                                  ConstantInt::get(I32Ty, 0));
1539       Value *Elt1 = Builder.CreateExtractElement(CI->getArgOperand(1),
1540                                                  ConstantInt::get(I32Ty, 0));
1541       Rep = Builder.CreateInsertElement(CI->getArgOperand(0),
1542                                         Builder.CreateFDiv(Elt0, Elt1),
1543                                         ConstantInt::get(I32Ty, 0));
1544     } else if (IsX86 && Name.startswith("avx512.mask.pcmp")) {
1545       // "avx512.mask.pcmpeq." or "avx512.mask.pcmpgt."
1546       bool CmpEq = Name[16] == 'e';
1547       Rep = upgradeMaskedCompare(Builder, *CI, CmpEq ? 0 : 6, true);
1548     } else if (IsX86 && Name.startswith("avx512.mask.cmp")) {
1549       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1550       Rep = upgradeMaskedCompare(Builder, *CI, Imm, true);
1551     } else if (IsX86 && Name.startswith("avx512.mask.ucmp")) {
1552       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1553       Rep = upgradeMaskedCompare(Builder, *CI, Imm, false);
1554     } else if (IsX86 && (Name.startswith("avx512.cvtb2mask.") ||
1555                          Name.startswith("avx512.cvtw2mask.") ||
1556                          Name.startswith("avx512.cvtd2mask.") ||
1557                          Name.startswith("avx512.cvtq2mask."))) {
1558       Value *Op = CI->getArgOperand(0);
1559       Value *Zero = llvm::Constant::getNullValue(Op->getType());
1560       Rep = Builder.CreateICmp(ICmpInst::ICMP_SLT, Op, Zero);
1561       Rep = ApplyX86MaskOn1BitsVec(Builder, Rep, nullptr,
1562                                    Op->getType()->getVectorNumElements());
1563     } else if(IsX86 && (Name == "ssse3.pabs.b.128" ||
1564                         Name == "ssse3.pabs.w.128" ||
1565                         Name == "ssse3.pabs.d.128" ||
1566                         Name.startswith("avx2.pabs") ||
1567                         Name.startswith("avx512.mask.pabs"))) {
1568       Rep = upgradeAbs(Builder, *CI);
1569     } else if (IsX86 && (Name == "sse41.pmaxsb" ||
1570                          Name == "sse2.pmaxs.w" ||
1571                          Name == "sse41.pmaxsd" ||
1572                          Name.startswith("avx2.pmaxs") ||
1573                          Name.startswith("avx512.mask.pmaxs"))) {
1574       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SGT);
1575     } else if (IsX86 && (Name == "sse2.pmaxu.b" ||
1576                          Name == "sse41.pmaxuw" ||
1577                          Name == "sse41.pmaxud" ||
1578                          Name.startswith("avx2.pmaxu") ||
1579                          Name.startswith("avx512.mask.pmaxu"))) {
1580       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_UGT);
1581     } else if (IsX86 && (Name == "sse41.pminsb" ||
1582                          Name == "sse2.pmins.w" ||
1583                          Name == "sse41.pminsd" ||
1584                          Name.startswith("avx2.pmins") ||
1585                          Name.startswith("avx512.mask.pmins"))) {
1586       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_SLT);
1587     } else if (IsX86 && (Name == "sse2.pminu.b" ||
1588                          Name == "sse41.pminuw" ||
1589                          Name == "sse41.pminud" ||
1590                          Name.startswith("avx2.pminu") ||
1591                          Name.startswith("avx512.mask.pminu"))) {
1592       Rep = upgradeIntMinMax(Builder, *CI, ICmpInst::ICMP_ULT);
1593     } else if (IsX86 && (Name == "sse2.pmulu.dq" ||
1594                          Name == "avx2.pmulu.dq" ||
1595                          Name == "avx512.pmulu.dq.512" ||
1596                          Name.startswith("avx512.mask.pmulu.dq."))) {
1597       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/false);
1598     } else if (IsX86 && (Name == "sse41.pmuldq" ||
1599                          Name == "avx2.pmul.dq" ||
1600                          Name == "avx512.pmul.dq.512" ||
1601                          Name.startswith("avx512.mask.pmul.dq."))) {
1602       Rep = upgradePMULDQ(Builder, *CI, /*Signed*/true);
1603     } else if (IsX86 && (Name == "sse.cvtsi2ss" ||
1604                          Name == "sse2.cvtsi2sd" ||
1605                          Name == "sse.cvtsi642ss" ||
1606                          Name == "sse2.cvtsi642sd")) {
1607       Rep = Builder.CreateSIToFP(CI->getArgOperand(1),
1608                                  CI->getType()->getVectorElementType());
1609       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
1610     } else if (IsX86 && Name == "avx512.cvtusi2sd") {
1611       Rep = Builder.CreateUIToFP(CI->getArgOperand(1),
1612                                  CI->getType()->getVectorElementType());
1613       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
1614     } else if (IsX86 && Name == "sse2.cvtss2sd") {
1615       Rep = Builder.CreateExtractElement(CI->getArgOperand(1), (uint64_t)0);
1616       Rep = Builder.CreateFPExt(Rep, CI->getType()->getVectorElementType());
1617       Rep = Builder.CreateInsertElement(CI->getArgOperand(0), Rep, (uint64_t)0);
1618     } else if (IsX86 && (Name == "sse2.cvtdq2pd" ||
1619                          Name == "sse2.cvtdq2ps" ||
1620                          Name == "avx.cvtdq2.pd.256" ||
1621                          Name == "avx.cvtdq2.ps.256" ||
1622                          Name.startswith("avx512.mask.cvtdq2pd.") ||
1623                          Name.startswith("avx512.mask.cvtudq2pd.") ||
1624                          Name == "avx512.mask.cvtdq2ps.128" ||
1625                          Name == "avx512.mask.cvtdq2ps.256" ||
1626                          Name == "avx512.mask.cvtudq2ps.128" ||
1627                          Name == "avx512.mask.cvtudq2ps.256" ||
1628                          Name == "avx512.mask.cvtqq2pd.128" ||
1629                          Name == "avx512.mask.cvtqq2pd.256" ||
1630                          Name == "avx512.mask.cvtuqq2pd.128" ||
1631                          Name == "avx512.mask.cvtuqq2pd.256" ||
1632                          Name == "sse2.cvtps2pd" ||
1633                          Name == "avx.cvt.ps2.pd.256" ||
1634                          Name == "avx512.mask.cvtps2pd.128" ||
1635                          Name == "avx512.mask.cvtps2pd.256")) {
1636       Type *DstTy = CI->getType();
1637       Rep = CI->getArgOperand(0);
1638 
1639       unsigned NumDstElts = DstTy->getVectorNumElements();
1640       if (NumDstElts < Rep->getType()->getVectorNumElements()) {
1641         assert(NumDstElts == 2 && "Unexpected vector size");
1642         uint32_t ShuffleMask[2] = { 0, 1 };
1643         Rep = Builder.CreateShuffleVector(Rep, Rep, ShuffleMask);
1644       }
1645 
1646       bool IsPS2PD = (StringRef::npos != Name.find("ps2"));
1647       bool IsUnsigned = (StringRef::npos != Name.find("cvtu"));
1648       if (IsPS2PD)
1649         Rep = Builder.CreateFPExt(Rep, DstTy, "cvtps2pd");
1650       else if (IsUnsigned)
1651         Rep = Builder.CreateUIToFP(Rep, DstTy, "cvt");
1652       else
1653         Rep = Builder.CreateSIToFP(Rep, DstTy, "cvt");
1654 
1655       if (CI->getNumArgOperands() == 3)
1656         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1657                             CI->getArgOperand(1));
1658     } else if (IsX86 && (Name.startswith("avx512.mask.loadu."))) {
1659       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
1660                               CI->getArgOperand(1), CI->getArgOperand(2),
1661                               /*Aligned*/false);
1662     } else if (IsX86 && (Name.startswith("avx512.mask.load."))) {
1663       Rep = UpgradeMaskedLoad(Builder, CI->getArgOperand(0),
1664                               CI->getArgOperand(1),CI->getArgOperand(2),
1665                               /*Aligned*/true);
1666     } else if (IsX86 && Name.startswith("xop.vpcom")) {
1667       Intrinsic::ID intID;
1668       if (Name.endswith("ub"))
1669         intID = Intrinsic::x86_xop_vpcomub;
1670       else if (Name.endswith("uw"))
1671         intID = Intrinsic::x86_xop_vpcomuw;
1672       else if (Name.endswith("ud"))
1673         intID = Intrinsic::x86_xop_vpcomud;
1674       else if (Name.endswith("uq"))
1675         intID = Intrinsic::x86_xop_vpcomuq;
1676       else if (Name.endswith("b"))
1677         intID = Intrinsic::x86_xop_vpcomb;
1678       else if (Name.endswith("w"))
1679         intID = Intrinsic::x86_xop_vpcomw;
1680       else if (Name.endswith("d"))
1681         intID = Intrinsic::x86_xop_vpcomd;
1682       else if (Name.endswith("q"))
1683         intID = Intrinsic::x86_xop_vpcomq;
1684       else
1685         llvm_unreachable("Unknown suffix");
1686 
1687       Name = Name.substr(9); // strip off "xop.vpcom"
1688       unsigned Imm;
1689       if (Name.startswith("lt"))
1690         Imm = 0;
1691       else if (Name.startswith("le"))
1692         Imm = 1;
1693       else if (Name.startswith("gt"))
1694         Imm = 2;
1695       else if (Name.startswith("ge"))
1696         Imm = 3;
1697       else if (Name.startswith("eq"))
1698         Imm = 4;
1699       else if (Name.startswith("ne"))
1700         Imm = 5;
1701       else if (Name.startswith("false"))
1702         Imm = 6;
1703       else if (Name.startswith("true"))
1704         Imm = 7;
1705       else
1706         llvm_unreachable("Unknown condition");
1707 
1708       Function *VPCOM = Intrinsic::getDeclaration(F->getParent(), intID);
1709       Rep =
1710           Builder.CreateCall(VPCOM, {CI->getArgOperand(0), CI->getArgOperand(1),
1711                                      Builder.getInt8(Imm)});
1712     } else if (IsX86 && Name.startswith("xop.vpcmov")) {
1713       Value *Sel = CI->getArgOperand(2);
1714       Value *NotSel = Builder.CreateNot(Sel);
1715       Value *Sel0 = Builder.CreateAnd(CI->getArgOperand(0), Sel);
1716       Value *Sel1 = Builder.CreateAnd(CI->getArgOperand(1), NotSel);
1717       Rep = Builder.CreateOr(Sel0, Sel1);
1718     } else if (IsX86 && Name == "sse42.crc32.64.8") {
1719       Function *CRC32 = Intrinsic::getDeclaration(F->getParent(),
1720                                                Intrinsic::x86_sse42_crc32_32_8);
1721       Value *Trunc0 = Builder.CreateTrunc(CI->getArgOperand(0), Type::getInt32Ty(C));
1722       Rep = Builder.CreateCall(CRC32, {Trunc0, CI->getArgOperand(1)});
1723       Rep = Builder.CreateZExt(Rep, CI->getType(), "");
1724     } else if (IsX86 && (Name.startswith("avx.vbroadcast.s") ||
1725                          Name.startswith("avx512.vbroadcast.s"))) {
1726       // Replace broadcasts with a series of insertelements.
1727       Type *VecTy = CI->getType();
1728       Type *EltTy = VecTy->getVectorElementType();
1729       unsigned EltNum = VecTy->getVectorNumElements();
1730       Value *Cast = Builder.CreateBitCast(CI->getArgOperand(0),
1731                                           EltTy->getPointerTo());
1732       Value *Load = Builder.CreateLoad(EltTy, Cast);
1733       Type *I32Ty = Type::getInt32Ty(C);
1734       Rep = UndefValue::get(VecTy);
1735       for (unsigned I = 0; I < EltNum; ++I)
1736         Rep = Builder.CreateInsertElement(Rep, Load,
1737                                           ConstantInt::get(I32Ty, I));
1738     } else if (IsX86 && (Name.startswith("sse41.pmovsx") ||
1739                          Name.startswith("sse41.pmovzx") ||
1740                          Name.startswith("avx2.pmovsx") ||
1741                          Name.startswith("avx2.pmovzx") ||
1742                          Name.startswith("avx512.mask.pmovsx") ||
1743                          Name.startswith("avx512.mask.pmovzx"))) {
1744       VectorType *SrcTy = cast<VectorType>(CI->getArgOperand(0)->getType());
1745       VectorType *DstTy = cast<VectorType>(CI->getType());
1746       unsigned NumDstElts = DstTy->getNumElements();
1747 
1748       // Extract a subvector of the first NumDstElts lanes and sign/zero extend.
1749       SmallVector<uint32_t, 8> ShuffleMask(NumDstElts);
1750       for (unsigned i = 0; i != NumDstElts; ++i)
1751         ShuffleMask[i] = i;
1752 
1753       Value *SV = Builder.CreateShuffleVector(
1754           CI->getArgOperand(0), UndefValue::get(SrcTy), ShuffleMask);
1755 
1756       bool DoSext = (StringRef::npos != Name.find("pmovsx"));
1757       Rep = DoSext ? Builder.CreateSExt(SV, DstTy)
1758                    : Builder.CreateZExt(SV, DstTy);
1759       // If there are 3 arguments, it's a masked intrinsic so we need a select.
1760       if (CI->getNumArgOperands() == 3)
1761         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1762                             CI->getArgOperand(1));
1763     } else if (IsX86 && (Name.startswith("avx.vbroadcastf128") ||
1764                          Name == "avx2.vbroadcasti128")) {
1765       // Replace vbroadcastf128/vbroadcasti128 with a vector load+shuffle.
1766       Type *EltTy = CI->getType()->getVectorElementType();
1767       unsigned NumSrcElts = 128 / EltTy->getPrimitiveSizeInBits();
1768       Type *VT = VectorType::get(EltTy, NumSrcElts);
1769       Value *Op = Builder.CreatePointerCast(CI->getArgOperand(0),
1770                                             PointerType::getUnqual(VT));
1771       Value *Load = Builder.CreateAlignedLoad(Op, 1);
1772       if (NumSrcElts == 2)
1773         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
1774                                           { 0, 1, 0, 1 });
1775       else
1776         Rep = Builder.CreateShuffleVector(Load, UndefValue::get(Load->getType()),
1777                                           { 0, 1, 2, 3, 0, 1, 2, 3 });
1778     } else if (IsX86 && (Name.startswith("avx512.mask.shuf.i") ||
1779                          Name.startswith("avx512.mask.shuf.f"))) {
1780       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1781       Type *VT = CI->getType();
1782       unsigned NumLanes = VT->getPrimitiveSizeInBits() / 128;
1783       unsigned NumElementsInLane = 128 / VT->getScalarSizeInBits();
1784       unsigned ControlBitsMask = NumLanes - 1;
1785       unsigned NumControlBits = NumLanes / 2;
1786       SmallVector<uint32_t, 8> ShuffleMask(0);
1787 
1788       for (unsigned l = 0; l != NumLanes; ++l) {
1789         unsigned LaneMask = (Imm >> (l * NumControlBits)) & ControlBitsMask;
1790         // We actually need the other source.
1791         if (l >= NumLanes / 2)
1792           LaneMask += NumLanes;
1793         for (unsigned i = 0; i != NumElementsInLane; ++i)
1794           ShuffleMask.push_back(LaneMask * NumElementsInLane + i);
1795       }
1796       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
1797                                         CI->getArgOperand(1), ShuffleMask);
1798       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
1799                           CI->getArgOperand(3));
1800     }else if (IsX86 && (Name.startswith("avx512.mask.broadcastf") ||
1801                          Name.startswith("avx512.mask.broadcasti"))) {
1802       unsigned NumSrcElts =
1803                         CI->getArgOperand(0)->getType()->getVectorNumElements();
1804       unsigned NumDstElts = CI->getType()->getVectorNumElements();
1805 
1806       SmallVector<uint32_t, 8> ShuffleMask(NumDstElts);
1807       for (unsigned i = 0; i != NumDstElts; ++i)
1808         ShuffleMask[i] = i % NumSrcElts;
1809 
1810       Rep = Builder.CreateShuffleVector(CI->getArgOperand(0),
1811                                         CI->getArgOperand(0),
1812                                         ShuffleMask);
1813       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1814                           CI->getArgOperand(1));
1815     } else if (IsX86 && (Name.startswith("avx2.pbroadcast") ||
1816                          Name.startswith("avx2.vbroadcast") ||
1817                          Name.startswith("avx512.pbroadcast") ||
1818                          Name.startswith("avx512.mask.broadcast.s"))) {
1819       // Replace vp?broadcasts with a vector shuffle.
1820       Value *Op = CI->getArgOperand(0);
1821       unsigned NumElts = CI->getType()->getVectorNumElements();
1822       Type *MaskTy = VectorType::get(Type::getInt32Ty(C), NumElts);
1823       Rep = Builder.CreateShuffleVector(Op, UndefValue::get(Op->getType()),
1824                                         Constant::getNullValue(MaskTy));
1825 
1826       if (CI->getNumArgOperands() == 3)
1827         Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
1828                             CI->getArgOperand(1));
1829     } else if (IsX86 && Name.startswith("avx512.mask.palignr.")) {
1830       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
1831                                       CI->getArgOperand(1),
1832                                       CI->getArgOperand(2),
1833                                       CI->getArgOperand(3),
1834                                       CI->getArgOperand(4),
1835                                       false);
1836     } else if (IsX86 && Name.startswith("avx512.mask.valign.")) {
1837       Rep = UpgradeX86ALIGNIntrinsics(Builder, CI->getArgOperand(0),
1838                                       CI->getArgOperand(1),
1839                                       CI->getArgOperand(2),
1840                                       CI->getArgOperand(3),
1841                                       CI->getArgOperand(4),
1842                                       true);
1843     } else if (IsX86 && (Name == "sse2.psll.dq" ||
1844                          Name == "avx2.psll.dq")) {
1845       // 128/256-bit shift left specified in bits.
1846       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1847       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0),
1848                                        Shift / 8); // Shift is in bits.
1849     } else if (IsX86 && (Name == "sse2.psrl.dq" ||
1850                          Name == "avx2.psrl.dq")) {
1851       // 128/256-bit shift right specified in bits.
1852       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1853       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0),
1854                                        Shift / 8); // Shift is in bits.
1855     } else if (IsX86 && (Name == "sse2.psll.dq.bs" ||
1856                          Name == "avx2.psll.dq.bs" ||
1857                          Name == "avx512.psll.dq.512")) {
1858       // 128/256/512-bit shift left specified in bytes.
1859       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1860       Rep = UpgradeX86PSLLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
1861     } else if (IsX86 && (Name == "sse2.psrl.dq.bs" ||
1862                          Name == "avx2.psrl.dq.bs" ||
1863                          Name == "avx512.psrl.dq.512")) {
1864       // 128/256/512-bit shift right specified in bytes.
1865       unsigned Shift = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1866       Rep = UpgradeX86PSRLDQIntrinsics(Builder, CI->getArgOperand(0), Shift);
1867     } else if (IsX86 && (Name == "sse41.pblendw" ||
1868                          Name.startswith("sse41.blendp") ||
1869                          Name.startswith("avx.blend.p") ||
1870                          Name == "avx2.pblendw" ||
1871                          Name.startswith("avx2.pblendd."))) {
1872       Value *Op0 = CI->getArgOperand(0);
1873       Value *Op1 = CI->getArgOperand(1);
1874       unsigned Imm = cast <ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1875       VectorType *VecTy = cast<VectorType>(CI->getType());
1876       unsigned NumElts = VecTy->getNumElements();
1877 
1878       SmallVector<uint32_t, 16> Idxs(NumElts);
1879       for (unsigned i = 0; i != NumElts; ++i)
1880         Idxs[i] = ((Imm >> (i%8)) & 1) ? i + NumElts : i;
1881 
1882       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
1883     } else if (IsX86 && (Name.startswith("avx.vinsertf128.") ||
1884                          Name == "avx2.vinserti128" ||
1885                          Name.startswith("avx512.mask.insert"))) {
1886       Value *Op0 = CI->getArgOperand(0);
1887       Value *Op1 = CI->getArgOperand(1);
1888       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1889       unsigned DstNumElts = CI->getType()->getVectorNumElements();
1890       unsigned SrcNumElts = Op1->getType()->getVectorNumElements();
1891       unsigned Scale = DstNumElts / SrcNumElts;
1892 
1893       // Mask off the high bits of the immediate value; hardware ignores those.
1894       Imm = Imm % Scale;
1895 
1896       // Extend the second operand into a vector the size of the destination.
1897       Value *UndefV = UndefValue::get(Op1->getType());
1898       SmallVector<uint32_t, 8> Idxs(DstNumElts);
1899       for (unsigned i = 0; i != SrcNumElts; ++i)
1900         Idxs[i] = i;
1901       for (unsigned i = SrcNumElts; i != DstNumElts; ++i)
1902         Idxs[i] = SrcNumElts;
1903       Rep = Builder.CreateShuffleVector(Op1, UndefV, Idxs);
1904 
1905       // Insert the second operand into the first operand.
1906 
1907       // Note that there is no guarantee that instruction lowering will actually
1908       // produce a vinsertf128 instruction for the created shuffles. In
1909       // particular, the 0 immediate case involves no lane changes, so it can
1910       // be handled as a blend.
1911 
1912       // Example of shuffle mask for 32-bit elements:
1913       // Imm = 1  <i32 0, i32 1, i32 2,  i32 3,  i32 8, i32 9, i32 10, i32 11>
1914       // Imm = 0  <i32 8, i32 9, i32 10, i32 11, i32 4, i32 5, i32 6,  i32 7 >
1915 
1916       // First fill with identify mask.
1917       for (unsigned i = 0; i != DstNumElts; ++i)
1918         Idxs[i] = i;
1919       // Then replace the elements where we need to insert.
1920       for (unsigned i = 0; i != SrcNumElts; ++i)
1921         Idxs[i + Imm * SrcNumElts] = i + DstNumElts;
1922       Rep = Builder.CreateShuffleVector(Op0, Rep, Idxs);
1923 
1924       // If the intrinsic has a mask operand, handle that.
1925       if (CI->getNumArgOperands() == 5)
1926         Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
1927                             CI->getArgOperand(3));
1928     } else if (IsX86 && (Name.startswith("avx.vextractf128.") ||
1929                          Name == "avx2.vextracti128" ||
1930                          Name.startswith("avx512.mask.vextract"))) {
1931       Value *Op0 = CI->getArgOperand(0);
1932       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1933       unsigned DstNumElts = CI->getType()->getVectorNumElements();
1934       unsigned SrcNumElts = Op0->getType()->getVectorNumElements();
1935       unsigned Scale = SrcNumElts / DstNumElts;
1936 
1937       // Mask off the high bits of the immediate value; hardware ignores those.
1938       Imm = Imm % Scale;
1939 
1940       // Get indexes for the subvector of the input vector.
1941       SmallVector<uint32_t, 8> Idxs(DstNumElts);
1942       for (unsigned i = 0; i != DstNumElts; ++i) {
1943         Idxs[i] = i + (Imm * DstNumElts);
1944       }
1945       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1946 
1947       // If the intrinsic has a mask operand, handle that.
1948       if (CI->getNumArgOperands() == 4)
1949         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1950                             CI->getArgOperand(2));
1951     } else if (!IsX86 && Name == "stackprotectorcheck") {
1952       Rep = nullptr;
1953     } else if (IsX86 && (Name.startswith("avx512.mask.perm.df.") ||
1954                          Name.startswith("avx512.mask.perm.di."))) {
1955       Value *Op0 = CI->getArgOperand(0);
1956       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
1957       VectorType *VecTy = cast<VectorType>(CI->getType());
1958       unsigned NumElts = VecTy->getNumElements();
1959 
1960       SmallVector<uint32_t, 8> Idxs(NumElts);
1961       for (unsigned i = 0; i != NumElts; ++i)
1962         Idxs[i] = (i & ~0x3) + ((Imm >> (2 * (i & 0x3))) & 3);
1963 
1964       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
1965 
1966       if (CI->getNumArgOperands() == 4)
1967         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
1968                             CI->getArgOperand(2));
1969     } else if (IsX86 && (Name.startswith("avx.vperm2f128.") ||
1970                          Name == "avx2.vperm2i128")) {
1971       // The immediate permute control byte looks like this:
1972       //    [1:0] - select 128 bits from sources for low half of destination
1973       //    [2]   - ignore
1974       //    [3]   - zero low half of destination
1975       //    [5:4] - select 128 bits from sources for high half of destination
1976       //    [6]   - ignore
1977       //    [7]   - zero high half of destination
1978 
1979       uint8_t Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
1980 
1981       unsigned NumElts = CI->getType()->getVectorNumElements();
1982       unsigned HalfSize = NumElts / 2;
1983       SmallVector<uint32_t, 8> ShuffleMask(NumElts);
1984 
1985       // Determine which operand(s) are actually in use for this instruction.
1986       Value *V0 = (Imm & 0x02) ? CI->getArgOperand(1) : CI->getArgOperand(0);
1987       Value *V1 = (Imm & 0x20) ? CI->getArgOperand(1) : CI->getArgOperand(0);
1988 
1989       // If needed, replace operands based on zero mask.
1990       V0 = (Imm & 0x08) ? ConstantAggregateZero::get(CI->getType()) : V0;
1991       V1 = (Imm & 0x80) ? ConstantAggregateZero::get(CI->getType()) : V1;
1992 
1993       // Permute low half of result.
1994       unsigned StartIndex = (Imm & 0x01) ? HalfSize : 0;
1995       for (unsigned i = 0; i < HalfSize; ++i)
1996         ShuffleMask[i] = StartIndex + i;
1997 
1998       // Permute high half of result.
1999       StartIndex = (Imm & 0x10) ? HalfSize : 0;
2000       for (unsigned i = 0; i < HalfSize; ++i)
2001         ShuffleMask[i + HalfSize] = NumElts + StartIndex + i;
2002 
2003       Rep = Builder.CreateShuffleVector(V0, V1, ShuffleMask);
2004 
2005     } else if (IsX86 && (Name.startswith("avx.vpermil.") ||
2006                          Name == "sse2.pshuf.d" ||
2007                          Name.startswith("avx512.mask.vpermil.p") ||
2008                          Name.startswith("avx512.mask.pshuf.d."))) {
2009       Value *Op0 = CI->getArgOperand(0);
2010       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2011       VectorType *VecTy = cast<VectorType>(CI->getType());
2012       unsigned NumElts = VecTy->getNumElements();
2013       // Calculate the size of each index in the immediate.
2014       unsigned IdxSize = 64 / VecTy->getScalarSizeInBits();
2015       unsigned IdxMask = ((1 << IdxSize) - 1);
2016 
2017       SmallVector<uint32_t, 8> Idxs(NumElts);
2018       // Lookup the bits for this element, wrapping around the immediate every
2019       // 8-bits. Elements are grouped into sets of 2 or 4 elements so we need
2020       // to offset by the first index of each group.
2021       for (unsigned i = 0; i != NumElts; ++i)
2022         Idxs[i] = ((Imm >> ((i * IdxSize) % 8)) & IdxMask) | (i & ~IdxMask);
2023 
2024       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2025 
2026       if (CI->getNumArgOperands() == 4)
2027         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2028                             CI->getArgOperand(2));
2029     } else if (IsX86 && (Name == "sse2.pshufl.w" ||
2030                          Name.startswith("avx512.mask.pshufl.w."))) {
2031       Value *Op0 = CI->getArgOperand(0);
2032       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2033       unsigned NumElts = CI->getType()->getVectorNumElements();
2034 
2035       SmallVector<uint32_t, 16> Idxs(NumElts);
2036       for (unsigned l = 0; l != NumElts; l += 8) {
2037         for (unsigned i = 0; i != 4; ++i)
2038           Idxs[i + l] = ((Imm >> (2 * i)) & 0x3) + l;
2039         for (unsigned i = 4; i != 8; ++i)
2040           Idxs[i + l] = i + l;
2041       }
2042 
2043       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2044 
2045       if (CI->getNumArgOperands() == 4)
2046         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2047                             CI->getArgOperand(2));
2048     } else if (IsX86 && (Name == "sse2.pshufh.w" ||
2049                          Name.startswith("avx512.mask.pshufh.w."))) {
2050       Value *Op0 = CI->getArgOperand(0);
2051       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(1))->getZExtValue();
2052       unsigned NumElts = CI->getType()->getVectorNumElements();
2053 
2054       SmallVector<uint32_t, 16> Idxs(NumElts);
2055       for (unsigned l = 0; l != NumElts; l += 8) {
2056         for (unsigned i = 0; i != 4; ++i)
2057           Idxs[i + l] = i + l;
2058         for (unsigned i = 0; i != 4; ++i)
2059           Idxs[i + l + 4] = ((Imm >> (2 * i)) & 0x3) + 4 + l;
2060       }
2061 
2062       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2063 
2064       if (CI->getNumArgOperands() == 4)
2065         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2066                             CI->getArgOperand(2));
2067     } else if (IsX86 && Name.startswith("avx512.mask.shuf.p")) {
2068       Value *Op0 = CI->getArgOperand(0);
2069       Value *Op1 = CI->getArgOperand(1);
2070       unsigned Imm = cast<ConstantInt>(CI->getArgOperand(2))->getZExtValue();
2071       unsigned NumElts = CI->getType()->getVectorNumElements();
2072 
2073       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2074       unsigned HalfLaneElts = NumLaneElts / 2;
2075 
2076       SmallVector<uint32_t, 16> Idxs(NumElts);
2077       for (unsigned i = 0; i != NumElts; ++i) {
2078         // Base index is the starting element of the lane.
2079         Idxs[i] = i - (i % NumLaneElts);
2080         // If we are half way through the lane switch to the other source.
2081         if ((i % NumLaneElts) >= HalfLaneElts)
2082           Idxs[i] += NumElts;
2083         // Now select the specific element. By adding HalfLaneElts bits from
2084         // the immediate. Wrapping around the immediate every 8-bits.
2085         Idxs[i] += (Imm >> ((i * HalfLaneElts) % 8)) & ((1 << HalfLaneElts) - 1);
2086       }
2087 
2088       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2089 
2090       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep,
2091                           CI->getArgOperand(3));
2092     } else if (IsX86 && (Name.startswith("avx512.mask.movddup") ||
2093                          Name.startswith("avx512.mask.movshdup") ||
2094                          Name.startswith("avx512.mask.movsldup"))) {
2095       Value *Op0 = CI->getArgOperand(0);
2096       unsigned NumElts = CI->getType()->getVectorNumElements();
2097       unsigned NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2098 
2099       unsigned Offset = 0;
2100       if (Name.startswith("avx512.mask.movshdup."))
2101         Offset = 1;
2102 
2103       SmallVector<uint32_t, 16> Idxs(NumElts);
2104       for (unsigned l = 0; l != NumElts; l += NumLaneElts)
2105         for (unsigned i = 0; i != NumLaneElts; i += 2) {
2106           Idxs[i + l + 0] = i + l + Offset;
2107           Idxs[i + l + 1] = i + l + Offset;
2108         }
2109 
2110       Rep = Builder.CreateShuffleVector(Op0, Op0, Idxs);
2111 
2112       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2113                           CI->getArgOperand(1));
2114     } else if (IsX86 && (Name.startswith("avx512.mask.punpckl") ||
2115                          Name.startswith("avx512.mask.unpckl."))) {
2116       Value *Op0 = CI->getArgOperand(0);
2117       Value *Op1 = CI->getArgOperand(1);
2118       int NumElts = CI->getType()->getVectorNumElements();
2119       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2120 
2121       SmallVector<uint32_t, 64> Idxs(NumElts);
2122       for (int l = 0; l != NumElts; l += NumLaneElts)
2123         for (int i = 0; i != NumLaneElts; ++i)
2124           Idxs[i + l] = l + (i / 2) + NumElts * (i % 2);
2125 
2126       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2127 
2128       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2129                           CI->getArgOperand(2));
2130     } else if (IsX86 && (Name.startswith("avx512.mask.punpckh") ||
2131                          Name.startswith("avx512.mask.unpckh."))) {
2132       Value *Op0 = CI->getArgOperand(0);
2133       Value *Op1 = CI->getArgOperand(1);
2134       int NumElts = CI->getType()->getVectorNumElements();
2135       int NumLaneElts = 128/CI->getType()->getScalarSizeInBits();
2136 
2137       SmallVector<uint32_t, 64> Idxs(NumElts);
2138       for (int l = 0; l != NumElts; l += NumLaneElts)
2139         for (int i = 0; i != NumLaneElts; ++i)
2140           Idxs[i + l] = (NumLaneElts / 2) + l + (i / 2) + NumElts * (i % 2);
2141 
2142       Rep = Builder.CreateShuffleVector(Op0, Op1, Idxs);
2143 
2144       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2145                           CI->getArgOperand(2));
2146     } else if (IsX86 && Name.startswith("avx512.mask.pand.")) {
2147       Rep = Builder.CreateAnd(CI->getArgOperand(0), CI->getArgOperand(1));
2148       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2149                           CI->getArgOperand(2));
2150     } else if (IsX86 && Name.startswith("avx512.mask.pandn.")) {
2151       Rep = Builder.CreateAnd(Builder.CreateNot(CI->getArgOperand(0)),
2152                               CI->getArgOperand(1));
2153       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2154                           CI->getArgOperand(2));
2155     } else if (IsX86 && Name.startswith("avx512.mask.por.")) {
2156       Rep = Builder.CreateOr(CI->getArgOperand(0), CI->getArgOperand(1));
2157       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2158                           CI->getArgOperand(2));
2159     } else if (IsX86 && Name.startswith("avx512.mask.pxor.")) {
2160       Rep = Builder.CreateXor(CI->getArgOperand(0), CI->getArgOperand(1));
2161       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2162                           CI->getArgOperand(2));
2163     } else if (IsX86 && Name.startswith("avx512.mask.and.")) {
2164       VectorType *FTy = cast<VectorType>(CI->getType());
2165       VectorType *ITy = VectorType::getInteger(FTy);
2166       Rep = Builder.CreateAnd(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2167                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2168       Rep = Builder.CreateBitCast(Rep, FTy);
2169       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2170                           CI->getArgOperand(2));
2171     } else if (IsX86 && Name.startswith("avx512.mask.andn.")) {
2172       VectorType *FTy = cast<VectorType>(CI->getType());
2173       VectorType *ITy = VectorType::getInteger(FTy);
2174       Rep = Builder.CreateNot(Builder.CreateBitCast(CI->getArgOperand(0), ITy));
2175       Rep = Builder.CreateAnd(Rep,
2176                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2177       Rep = Builder.CreateBitCast(Rep, FTy);
2178       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2179                           CI->getArgOperand(2));
2180     } else if (IsX86 && Name.startswith("avx512.mask.or.")) {
2181       VectorType *FTy = cast<VectorType>(CI->getType());
2182       VectorType *ITy = VectorType::getInteger(FTy);
2183       Rep = Builder.CreateOr(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2184                              Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2185       Rep = Builder.CreateBitCast(Rep, FTy);
2186       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2187                           CI->getArgOperand(2));
2188     } else if (IsX86 && Name.startswith("avx512.mask.xor.")) {
2189       VectorType *FTy = cast<VectorType>(CI->getType());
2190       VectorType *ITy = VectorType::getInteger(FTy);
2191       Rep = Builder.CreateXor(Builder.CreateBitCast(CI->getArgOperand(0), ITy),
2192                               Builder.CreateBitCast(CI->getArgOperand(1), ITy));
2193       Rep = Builder.CreateBitCast(Rep, FTy);
2194       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2195                           CI->getArgOperand(2));
2196     } else if (IsX86 && Name.startswith("avx512.mask.padd.")) {
2197       Rep = Builder.CreateAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2198       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2199                           CI->getArgOperand(2));
2200     } else if (IsX86 && Name.startswith("avx512.mask.psub.")) {
2201       Rep = Builder.CreateSub(CI->getArgOperand(0), CI->getArgOperand(1));
2202       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2203                           CI->getArgOperand(2));
2204     } else if (IsX86 && Name.startswith("avx512.mask.pmull.")) {
2205       Rep = Builder.CreateMul(CI->getArgOperand(0), CI->getArgOperand(1));
2206       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2207                           CI->getArgOperand(2));
2208     } else if (IsX86 && (Name.startswith("avx512.mask.add.p"))) {
2209       Rep = Builder.CreateFAdd(CI->getArgOperand(0), CI->getArgOperand(1));
2210       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2211                           CI->getArgOperand(2));
2212     } else if (IsX86 && Name.startswith("avx512.mask.div.p")) {
2213       Rep = Builder.CreateFDiv(CI->getArgOperand(0), CI->getArgOperand(1));
2214       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2215                           CI->getArgOperand(2));
2216     } else if (IsX86 && Name.startswith("avx512.mask.mul.p")) {
2217       Rep = Builder.CreateFMul(CI->getArgOperand(0), CI->getArgOperand(1));
2218       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2219                           CI->getArgOperand(2));
2220     } else if (IsX86 && Name.startswith("avx512.mask.sub.p")) {
2221       Rep = Builder.CreateFSub(CI->getArgOperand(0), CI->getArgOperand(1));
2222       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2223                           CI->getArgOperand(2));
2224     } else if (IsX86 && Name.startswith("avx512.mask.lzcnt.")) {
2225       Rep = Builder.CreateCall(Intrinsic::getDeclaration(F->getParent(),
2226                                                          Intrinsic::ctlz,
2227                                                          CI->getType()),
2228                                { CI->getArgOperand(0), Builder.getInt1(false) });
2229       Rep = EmitX86Select(Builder, CI->getArgOperand(2), Rep,
2230                           CI->getArgOperand(1));
2231     } else if (IsX86 && Name.startswith("avx512.mask.psll")) {
2232       bool IsImmediate = Name[16] == 'i' ||
2233                          (Name.size() > 18 && Name[18] == 'i');
2234       bool IsVariable = Name[16] == 'v';
2235       char Size = Name[16] == '.' ? Name[17] :
2236                   Name[17] == '.' ? Name[18] :
2237                   Name[18] == '.' ? Name[19] :
2238                                     Name[20];
2239 
2240       Intrinsic::ID IID;
2241       if (IsVariable && Name[17] != '.') {
2242         if (Size == 'd' && Name[17] == '2') // avx512.mask.psllv2.di
2243           IID = Intrinsic::x86_avx2_psllv_q;
2244         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psllv4.di
2245           IID = Intrinsic::x86_avx2_psllv_q_256;
2246         else if (Size == 's' && Name[17] == '4') // avx512.mask.psllv4.si
2247           IID = Intrinsic::x86_avx2_psllv_d;
2248         else if (Size == 's' && Name[17] == '8') // avx512.mask.psllv8.si
2249           IID = Intrinsic::x86_avx2_psllv_d_256;
2250         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psllv8.hi
2251           IID = Intrinsic::x86_avx512_psllv_w_128;
2252         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psllv16.hi
2253           IID = Intrinsic::x86_avx512_psllv_w_256;
2254         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psllv32hi
2255           IID = Intrinsic::x86_avx512_psllv_w_512;
2256         else
2257           llvm_unreachable("Unexpected size");
2258       } else if (Name.endswith(".128")) {
2259         if (Size == 'd') // avx512.mask.psll.d.128, avx512.mask.psll.di.128
2260           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_d
2261                             : Intrinsic::x86_sse2_psll_d;
2262         else if (Size == 'q') // avx512.mask.psll.q.128, avx512.mask.psll.qi.128
2263           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_q
2264                             : Intrinsic::x86_sse2_psll_q;
2265         else if (Size == 'w') // avx512.mask.psll.w.128, avx512.mask.psll.wi.128
2266           IID = IsImmediate ? Intrinsic::x86_sse2_pslli_w
2267                             : Intrinsic::x86_sse2_psll_w;
2268         else
2269           llvm_unreachable("Unexpected size");
2270       } else if (Name.endswith(".256")) {
2271         if (Size == 'd') // avx512.mask.psll.d.256, avx512.mask.psll.di.256
2272           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_d
2273                             : Intrinsic::x86_avx2_psll_d;
2274         else if (Size == 'q') // avx512.mask.psll.q.256, avx512.mask.psll.qi.256
2275           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_q
2276                             : Intrinsic::x86_avx2_psll_q;
2277         else if (Size == 'w') // avx512.mask.psll.w.256, avx512.mask.psll.wi.256
2278           IID = IsImmediate ? Intrinsic::x86_avx2_pslli_w
2279                             : Intrinsic::x86_avx2_psll_w;
2280         else
2281           llvm_unreachable("Unexpected size");
2282       } else {
2283         if (Size == 'd') // psll.di.512, pslli.d, psll.d, psllv.d.512
2284           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_d_512 :
2285                 IsVariable  ? Intrinsic::x86_avx512_psllv_d_512 :
2286                               Intrinsic::x86_avx512_psll_d_512;
2287         else if (Size == 'q') // psll.qi.512, pslli.q, psll.q, psllv.q.512
2288           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_q_512 :
2289                 IsVariable  ? Intrinsic::x86_avx512_psllv_q_512 :
2290                               Intrinsic::x86_avx512_psll_q_512;
2291         else if (Size == 'w') // psll.wi.512, pslli.w, psll.w
2292           IID = IsImmediate ? Intrinsic::x86_avx512_pslli_w_512
2293                             : Intrinsic::x86_avx512_psll_w_512;
2294         else
2295           llvm_unreachable("Unexpected size");
2296       }
2297 
2298       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2299     } else if (IsX86 && Name.startswith("avx512.mask.psrl")) {
2300       bool IsImmediate = Name[16] == 'i' ||
2301                          (Name.size() > 18 && Name[18] == 'i');
2302       bool IsVariable = Name[16] == 'v';
2303       char Size = Name[16] == '.' ? Name[17] :
2304                   Name[17] == '.' ? Name[18] :
2305                   Name[18] == '.' ? Name[19] :
2306                                     Name[20];
2307 
2308       Intrinsic::ID IID;
2309       if (IsVariable && Name[17] != '.') {
2310         if (Size == 'd' && Name[17] == '2') // avx512.mask.psrlv2.di
2311           IID = Intrinsic::x86_avx2_psrlv_q;
2312         else if (Size == 'd' && Name[17] == '4') // avx512.mask.psrlv4.di
2313           IID = Intrinsic::x86_avx2_psrlv_q_256;
2314         else if (Size == 's' && Name[17] == '4') // avx512.mask.psrlv4.si
2315           IID = Intrinsic::x86_avx2_psrlv_d;
2316         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrlv8.si
2317           IID = Intrinsic::x86_avx2_psrlv_d_256;
2318         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrlv8.hi
2319           IID = Intrinsic::x86_avx512_psrlv_w_128;
2320         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrlv16.hi
2321           IID = Intrinsic::x86_avx512_psrlv_w_256;
2322         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrlv32hi
2323           IID = Intrinsic::x86_avx512_psrlv_w_512;
2324         else
2325           llvm_unreachable("Unexpected size");
2326       } else if (Name.endswith(".128")) {
2327         if (Size == 'd') // avx512.mask.psrl.d.128, avx512.mask.psrl.di.128
2328           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_d
2329                             : Intrinsic::x86_sse2_psrl_d;
2330         else if (Size == 'q') // avx512.mask.psrl.q.128, avx512.mask.psrl.qi.128
2331           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_q
2332                             : Intrinsic::x86_sse2_psrl_q;
2333         else if (Size == 'w') // avx512.mask.psrl.w.128, avx512.mask.psrl.wi.128
2334           IID = IsImmediate ? Intrinsic::x86_sse2_psrli_w
2335                             : Intrinsic::x86_sse2_psrl_w;
2336         else
2337           llvm_unreachable("Unexpected size");
2338       } else if (Name.endswith(".256")) {
2339         if (Size == 'd') // avx512.mask.psrl.d.256, avx512.mask.psrl.di.256
2340           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_d
2341                             : Intrinsic::x86_avx2_psrl_d;
2342         else if (Size == 'q') // avx512.mask.psrl.q.256, avx512.mask.psrl.qi.256
2343           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_q
2344                             : Intrinsic::x86_avx2_psrl_q;
2345         else if (Size == 'w') // avx512.mask.psrl.w.256, avx512.mask.psrl.wi.256
2346           IID = IsImmediate ? Intrinsic::x86_avx2_psrli_w
2347                             : Intrinsic::x86_avx2_psrl_w;
2348         else
2349           llvm_unreachable("Unexpected size");
2350       } else {
2351         if (Size == 'd') // psrl.di.512, psrli.d, psrl.d, psrl.d.512
2352           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_d_512 :
2353                 IsVariable  ? Intrinsic::x86_avx512_psrlv_d_512 :
2354                               Intrinsic::x86_avx512_psrl_d_512;
2355         else if (Size == 'q') // psrl.qi.512, psrli.q, psrl.q, psrl.q.512
2356           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_q_512 :
2357                 IsVariable  ? Intrinsic::x86_avx512_psrlv_q_512 :
2358                               Intrinsic::x86_avx512_psrl_q_512;
2359         else if (Size == 'w') // psrl.wi.512, psrli.w, psrl.w)
2360           IID = IsImmediate ? Intrinsic::x86_avx512_psrli_w_512
2361                             : Intrinsic::x86_avx512_psrl_w_512;
2362         else
2363           llvm_unreachable("Unexpected size");
2364       }
2365 
2366       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2367     } else if (IsX86 && Name.startswith("avx512.mask.psra")) {
2368       bool IsImmediate = Name[16] == 'i' ||
2369                          (Name.size() > 18 && Name[18] == 'i');
2370       bool IsVariable = Name[16] == 'v';
2371       char Size = Name[16] == '.' ? Name[17] :
2372                   Name[17] == '.' ? Name[18] :
2373                   Name[18] == '.' ? Name[19] :
2374                                     Name[20];
2375 
2376       Intrinsic::ID IID;
2377       if (IsVariable && Name[17] != '.') {
2378         if (Size == 's' && Name[17] == '4') // avx512.mask.psrav4.si
2379           IID = Intrinsic::x86_avx2_psrav_d;
2380         else if (Size == 's' && Name[17] == '8') // avx512.mask.psrav8.si
2381           IID = Intrinsic::x86_avx2_psrav_d_256;
2382         else if (Size == 'h' && Name[17] == '8') // avx512.mask.psrav8.hi
2383           IID = Intrinsic::x86_avx512_psrav_w_128;
2384         else if (Size == 'h' && Name[17] == '1') // avx512.mask.psrav16.hi
2385           IID = Intrinsic::x86_avx512_psrav_w_256;
2386         else if (Name[17] == '3' && Name[18] == '2') // avx512.mask.psrav32hi
2387           IID = Intrinsic::x86_avx512_psrav_w_512;
2388         else
2389           llvm_unreachable("Unexpected size");
2390       } else if (Name.endswith(".128")) {
2391         if (Size == 'd') // avx512.mask.psra.d.128, avx512.mask.psra.di.128
2392           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_d
2393                             : Intrinsic::x86_sse2_psra_d;
2394         else if (Size == 'q') // avx512.mask.psra.q.128, avx512.mask.psra.qi.128
2395           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_128 :
2396                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_128 :
2397                               Intrinsic::x86_avx512_psra_q_128;
2398         else if (Size == 'w') // avx512.mask.psra.w.128, avx512.mask.psra.wi.128
2399           IID = IsImmediate ? Intrinsic::x86_sse2_psrai_w
2400                             : Intrinsic::x86_sse2_psra_w;
2401         else
2402           llvm_unreachable("Unexpected size");
2403       } else if (Name.endswith(".256")) {
2404         if (Size == 'd') // avx512.mask.psra.d.256, avx512.mask.psra.di.256
2405           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_d
2406                             : Intrinsic::x86_avx2_psra_d;
2407         else if (Size == 'q') // avx512.mask.psra.q.256, avx512.mask.psra.qi.256
2408           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_256 :
2409                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_256 :
2410                               Intrinsic::x86_avx512_psra_q_256;
2411         else if (Size == 'w') // avx512.mask.psra.w.256, avx512.mask.psra.wi.256
2412           IID = IsImmediate ? Intrinsic::x86_avx2_psrai_w
2413                             : Intrinsic::x86_avx2_psra_w;
2414         else
2415           llvm_unreachable("Unexpected size");
2416       } else {
2417         if (Size == 'd') // psra.di.512, psrai.d, psra.d, psrav.d.512
2418           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_d_512 :
2419                 IsVariable  ? Intrinsic::x86_avx512_psrav_d_512 :
2420                               Intrinsic::x86_avx512_psra_d_512;
2421         else if (Size == 'q') // psra.qi.512, psrai.q, psra.q
2422           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_q_512 :
2423                 IsVariable  ? Intrinsic::x86_avx512_psrav_q_512 :
2424                               Intrinsic::x86_avx512_psra_q_512;
2425         else if (Size == 'w') // psra.wi.512, psrai.w, psra.w
2426           IID = IsImmediate ? Intrinsic::x86_avx512_psrai_w_512
2427                             : Intrinsic::x86_avx512_psra_w_512;
2428         else
2429           llvm_unreachable("Unexpected size");
2430       }
2431 
2432       Rep = UpgradeX86MaskedShift(Builder, *CI, IID);
2433     } else if (IsX86 && Name.startswith("avx512.mask.move.s")) {
2434       Rep = upgradeMaskedMove(Builder, *CI);
2435     } else if (IsX86 && Name.startswith("avx512.cvtmask2")) {
2436       Rep = UpgradeMaskToInt(Builder, *CI);
2437     } else if (IsX86 && Name.endswith(".movntdqa")) {
2438       Module *M = F->getParent();
2439       MDNode *Node = MDNode::get(
2440           C, ConstantAsMetadata::get(ConstantInt::get(Type::getInt32Ty(C), 1)));
2441 
2442       Value *Ptr = CI->getArgOperand(0);
2443       VectorType *VTy = cast<VectorType>(CI->getType());
2444 
2445       // Convert the type of the pointer to a pointer to the stored type.
2446       Value *BC =
2447           Builder.CreateBitCast(Ptr, PointerType::getUnqual(VTy), "cast");
2448       LoadInst *LI = Builder.CreateAlignedLoad(BC, VTy->getBitWidth() / 8);
2449       LI->setMetadata(M->getMDKindID("nontemporal"), Node);
2450       Rep = LI;
2451     } else if (IsX86 &&
2452                (Name.startswith("sse2.pavg") || Name.startswith("avx2.pavg") ||
2453                 Name.startswith("avx512.mask.pavg"))) {
2454       // llvm.x86.sse2.pavg.b/w, llvm.x86.avx2.pavg.b/w,
2455       // llvm.x86.avx512.mask.pavg.b/w
2456       Value *A = CI->getArgOperand(0);
2457       Value *B = CI->getArgOperand(1);
2458       VectorType *ZextType = VectorType::getExtendedElementVectorType(
2459           cast<VectorType>(A->getType()));
2460       Value *ExtendedA = Builder.CreateZExt(A, ZextType);
2461       Value *ExtendedB = Builder.CreateZExt(B, ZextType);
2462       Value *Sum = Builder.CreateAdd(ExtendedA, ExtendedB);
2463       Value *AddOne = Builder.CreateAdd(Sum, ConstantInt::get(ZextType, 1));
2464       Value *ShiftR = Builder.CreateLShr(AddOne, ConstantInt::get(ZextType, 1));
2465       Rep = Builder.CreateTrunc(ShiftR, A->getType());
2466       if (CI->getNumArgOperands() > 2) {
2467         Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep,
2468                             CI->getArgOperand(2));
2469       }
2470     } else if (IsX86 && Name.startswith("fma.vfmsub")) {
2471       // Handle FMSUB and FSUBADD.
2472       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
2473       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
2474       Intrinsic::ID IID;
2475       if (Name[10] == '.' && Name[11] == 'p') {
2476         // Packed FMSUB
2477         if (VecWidth == 128 && EltWidth == 32)
2478           IID = Intrinsic::x86_fma_vfmadd_ps;
2479         else if (VecWidth == 128 && EltWidth == 64)
2480           IID = Intrinsic::x86_fma_vfmadd_pd;
2481         else if (VecWidth == 256 && EltWidth == 32)
2482           IID = Intrinsic::x86_fma_vfmadd_ps_256;
2483         else if (VecWidth == 256 && EltWidth == 64)
2484           IID = Intrinsic::x86_fma_vfmadd_pd_256;
2485         else
2486           llvm_unreachable("Unexpected intrinsic");
2487       } else if (Name[10] == '.' && Name[11] == 's') {
2488         // Scalar FMSUB
2489         if (EltWidth == 32)
2490           IID = Intrinsic::x86_fma_vfmadd_ss;
2491         else if (EltWidth == 64)
2492           IID = Intrinsic::x86_fma_vfmadd_sd;
2493         else
2494           llvm_unreachable("Unexpected intrinsic");
2495       } else {
2496         // FMSUBADD
2497         if (VecWidth == 128 && EltWidth == 32)
2498           IID = Intrinsic::x86_fma_vfmaddsub_ps;
2499         else if (VecWidth == 128 && EltWidth == 64)
2500           IID = Intrinsic::x86_fma_vfmaddsub_pd;
2501         else if (VecWidth == 256 && EltWidth == 32)
2502           IID = Intrinsic::x86_fma_vfmaddsub_ps_256;
2503         else if (VecWidth == 256 && EltWidth == 64)
2504           IID = Intrinsic::x86_fma_vfmaddsub_pd_256;
2505         else
2506           llvm_unreachable("Unexpected intrinsic");
2507       }
2508       Value *Arg2 = Builder.CreateFNeg(CI->getArgOperand(2));
2509       Value *Ops[] = { CI->getArgOperand(0), CI->getArgOperand(1), Arg2 };
2510       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
2511                                                          Ops);
2512     } else if (IsX86 && (Name.startswith("fma.vfnmadd.") ||
2513                          Name.startswith("fma.vfnmsub."))) {
2514       Value *Arg0 = CI->getArgOperand(0);
2515       Value *Arg1 = CI->getArgOperand(1);
2516       Value *Arg2 = CI->getArgOperand(2);
2517       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
2518       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
2519       Intrinsic::ID IID;
2520       if (Name[12] == 'p') {
2521         // Packed FNMADD/FNSUB
2522         Arg0 = Builder.CreateFNeg(Arg0);
2523         if (VecWidth == 128 && EltWidth == 32)
2524           IID = Intrinsic::x86_fma_vfmadd_ps;
2525         else if (VecWidth == 128 && EltWidth == 64)
2526           IID = Intrinsic::x86_fma_vfmadd_pd;
2527         else if (VecWidth == 256 && EltWidth == 32)
2528           IID = Intrinsic::x86_fma_vfmadd_ps_256;
2529         else if (VecWidth == 256 && EltWidth == 64)
2530           IID = Intrinsic::x86_fma_vfmadd_pd_256;
2531         else
2532           llvm_unreachable("Unexpected intrinsic");
2533       } else {
2534         // Scalar FNMADD/FNMSUB
2535         Arg1 = Builder.CreateFNeg(Arg1); // Arg0 is passthru so invert Arg1.
2536         if (EltWidth == 32)
2537           IID = Intrinsic::x86_fma_vfmadd_ss;
2538         else if (EltWidth == 64)
2539           IID = Intrinsic::x86_fma_vfmadd_sd;
2540         else
2541           llvm_unreachable("Unexpected intrinsic");
2542       }
2543       // Invert for FNMSUB.
2544       if (Name[8] == 's')
2545         Arg2 = Builder.CreateFNeg(Arg2);
2546       Value *Ops[] = { Arg0, Arg1, Arg2 };
2547       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
2548                                                          Ops);
2549     } else if (IsX86 && (Name.startswith("avx512.mask.pternlog.") ||
2550                          Name.startswith("avx512.maskz.pternlog."))) {
2551       bool ZeroMask = Name[11] == 'z';
2552       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
2553       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
2554       Intrinsic::ID IID;
2555       if (VecWidth == 128 && EltWidth == 32)
2556         IID = Intrinsic::x86_avx512_pternlog_d_128;
2557       else if (VecWidth == 256 && EltWidth == 32)
2558         IID = Intrinsic::x86_avx512_pternlog_d_256;
2559       else if (VecWidth == 512 && EltWidth == 32)
2560         IID = Intrinsic::x86_avx512_pternlog_d_512;
2561       else if (VecWidth == 128 && EltWidth == 64)
2562         IID = Intrinsic::x86_avx512_pternlog_q_128;
2563       else if (VecWidth == 256 && EltWidth == 64)
2564         IID = Intrinsic::x86_avx512_pternlog_q_256;
2565       else if (VecWidth == 512 && EltWidth == 64)
2566         IID = Intrinsic::x86_avx512_pternlog_q_512;
2567       else
2568         llvm_unreachable("Unexpected intrinsic");
2569 
2570       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
2571                         CI->getArgOperand(2), CI->getArgOperand(3) };
2572       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
2573                                Args);
2574       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
2575                                  : CI->getArgOperand(0);
2576       Rep = EmitX86Select(Builder, CI->getArgOperand(4), Rep, PassThru);
2577     } else if (IsX86 && (Name.startswith("avx512.mask.vpmadd52") ||
2578                          Name.startswith("avx512.maskz.vpmadd52"))) {
2579       bool ZeroMask = Name[11] == 'z';
2580       bool High = Name[20] == 'h' || Name[21] == 'h';
2581       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
2582       Intrinsic::ID IID;
2583       if (VecWidth == 128 && !High)
2584         IID = Intrinsic::x86_avx512_vpmadd52l_uq_128;
2585       else if (VecWidth == 256 && !High)
2586         IID = Intrinsic::x86_avx512_vpmadd52l_uq_256;
2587       else if (VecWidth == 512 && !High)
2588         IID = Intrinsic::x86_avx512_vpmadd52l_uq_512;
2589       else if (VecWidth == 128 && High)
2590         IID = Intrinsic::x86_avx512_vpmadd52h_uq_128;
2591       else if (VecWidth == 256 && High)
2592         IID = Intrinsic::x86_avx512_vpmadd52h_uq_256;
2593       else if (VecWidth == 512 && High)
2594         IID = Intrinsic::x86_avx512_vpmadd52h_uq_512;
2595       else
2596         llvm_unreachable("Unexpected intrinsic");
2597 
2598       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
2599                         CI->getArgOperand(2) };
2600       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
2601                                Args);
2602       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
2603                                  : CI->getArgOperand(0);
2604       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
2605     } else if (IsX86 && (Name.startswith("avx512.mask.vpermi2var.") ||
2606                          Name.startswith("avx512.mask.vpermt2var.") ||
2607                          Name.startswith("avx512.maskz.vpermt2var."))) {
2608       bool ZeroMask = Name[11] == 'z';
2609       bool IndexForm = Name[17] == 'i';
2610       unsigned VecWidth = CI->getType()->getPrimitiveSizeInBits();
2611       unsigned EltWidth = CI->getType()->getScalarSizeInBits();
2612       bool IsFloat = CI->getType()->isFPOrFPVectorTy();
2613       Intrinsic::ID IID;
2614       if (VecWidth == 128 && EltWidth == 32 && IsFloat)
2615         IID = Intrinsic::x86_avx512_vpermi2var_ps_128;
2616       else if (VecWidth == 128 && EltWidth == 32 && !IsFloat)
2617         IID = Intrinsic::x86_avx512_vpermi2var_d_128;
2618       else if (VecWidth == 128 && EltWidth == 64 && IsFloat)
2619         IID = Intrinsic::x86_avx512_vpermi2var_pd_128;
2620       else if (VecWidth == 128 && EltWidth == 64 && !IsFloat)
2621         IID = Intrinsic::x86_avx512_vpermi2var_q_128;
2622       else if (VecWidth == 256 && EltWidth == 32 && IsFloat)
2623         IID = Intrinsic::x86_avx512_vpermi2var_ps_256;
2624       else if (VecWidth == 256 && EltWidth == 32 && !IsFloat)
2625         IID = Intrinsic::x86_avx512_vpermi2var_d_256;
2626       else if (VecWidth == 256 && EltWidth == 64 && IsFloat)
2627         IID = Intrinsic::x86_avx512_vpermi2var_pd_256;
2628       else if (VecWidth == 256 && EltWidth == 64 && !IsFloat)
2629         IID = Intrinsic::x86_avx512_vpermi2var_q_256;
2630       else if (VecWidth == 512 && EltWidth == 32 && IsFloat)
2631         IID = Intrinsic::x86_avx512_vpermi2var_ps_512;
2632       else if (VecWidth == 512 && EltWidth == 32 && !IsFloat)
2633         IID = Intrinsic::x86_avx512_vpermi2var_d_512;
2634       else if (VecWidth == 512 && EltWidth == 64 && IsFloat)
2635         IID = Intrinsic::x86_avx512_vpermi2var_pd_512;
2636       else if (VecWidth == 512 && EltWidth == 64 && !IsFloat)
2637         IID = Intrinsic::x86_avx512_vpermi2var_q_512;
2638       else if (VecWidth == 128 && EltWidth == 16)
2639         IID = Intrinsic::x86_avx512_vpermi2var_hi_128;
2640       else if (VecWidth == 256 && EltWidth == 16)
2641         IID = Intrinsic::x86_avx512_vpermi2var_hi_256;
2642       else if (VecWidth == 512 && EltWidth == 16)
2643         IID = Intrinsic::x86_avx512_vpermi2var_hi_512;
2644       else if (VecWidth == 128 && EltWidth == 8)
2645         IID = Intrinsic::x86_avx512_vpermi2var_qi_128;
2646       else if (VecWidth == 256 && EltWidth == 8)
2647         IID = Intrinsic::x86_avx512_vpermi2var_qi_256;
2648       else if (VecWidth == 512 && EltWidth == 8)
2649         IID = Intrinsic::x86_avx512_vpermi2var_qi_512;
2650       else
2651         llvm_unreachable("Unexpected intrinsic");
2652 
2653       Value *Args[] = { CI->getArgOperand(0) , CI->getArgOperand(1),
2654                         CI->getArgOperand(2) };
2655 
2656       // If this isn't index form we need to swap operand 0 and 1.
2657       if (!IndexForm)
2658         std::swap(Args[0], Args[1]);
2659 
2660       Rep = Builder.CreateCall(Intrinsic::getDeclaration(CI->getModule(), IID),
2661                                Args);
2662       Value *PassThru = ZeroMask ? ConstantAggregateZero::get(CI->getType())
2663                                  : Builder.CreateBitCast(CI->getArgOperand(1),
2664                                                          CI->getType());
2665       Rep = EmitX86Select(Builder, CI->getArgOperand(3), Rep, PassThru);
2666     } else if (IsX86 && Name.startswith("avx512.mask.") &&
2667                upgradeAVX512MaskToSelect(Name, Builder, *CI, Rep)) {
2668       // Rep will be updated by the call in the condition.
2669     } else if (IsNVVM && (Name == "abs.i" || Name == "abs.ll")) {
2670       Value *Arg = CI->getArgOperand(0);
2671       Value *Neg = Builder.CreateNeg(Arg, "neg");
2672       Value *Cmp = Builder.CreateICmpSGE(
2673           Arg, llvm::Constant::getNullValue(Arg->getType()), "abs.cond");
2674       Rep = Builder.CreateSelect(Cmp, Arg, Neg, "abs");
2675     } else if (IsNVVM && (Name == "max.i" || Name == "max.ll" ||
2676                           Name == "max.ui" || Name == "max.ull")) {
2677       Value *Arg0 = CI->getArgOperand(0);
2678       Value *Arg1 = CI->getArgOperand(1);
2679       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
2680                        ? Builder.CreateICmpUGE(Arg0, Arg1, "max.cond")
2681                        : Builder.CreateICmpSGE(Arg0, Arg1, "max.cond");
2682       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "max");
2683     } else if (IsNVVM && (Name == "min.i" || Name == "min.ll" ||
2684                           Name == "min.ui" || Name == "min.ull")) {
2685       Value *Arg0 = CI->getArgOperand(0);
2686       Value *Arg1 = CI->getArgOperand(1);
2687       Value *Cmp = Name.endswith(".ui") || Name.endswith(".ull")
2688                        ? Builder.CreateICmpULE(Arg0, Arg1, "min.cond")
2689                        : Builder.CreateICmpSLE(Arg0, Arg1, "min.cond");
2690       Rep = Builder.CreateSelect(Cmp, Arg0, Arg1, "min");
2691     } else if (IsNVVM && Name == "clz.ll") {
2692       // llvm.nvvm.clz.ll returns an i32, but llvm.ctlz.i64 and returns an i64.
2693       Value *Arg = CI->getArgOperand(0);
2694       Value *Ctlz = Builder.CreateCall(
2695           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctlz,
2696                                     {Arg->getType()}),
2697           {Arg, Builder.getFalse()}, "ctlz");
2698       Rep = Builder.CreateTrunc(Ctlz, Builder.getInt32Ty(), "ctlz.trunc");
2699     } else if (IsNVVM && Name == "popc.ll") {
2700       // llvm.nvvm.popc.ll returns an i32, but llvm.ctpop.i64 and returns an
2701       // i64.
2702       Value *Arg = CI->getArgOperand(0);
2703       Value *Popc = Builder.CreateCall(
2704           Intrinsic::getDeclaration(F->getParent(), Intrinsic::ctpop,
2705                                     {Arg->getType()}),
2706           Arg, "ctpop");
2707       Rep = Builder.CreateTrunc(Popc, Builder.getInt32Ty(), "ctpop.trunc");
2708     } else if (IsNVVM && Name == "h2f") {
2709       Rep = Builder.CreateCall(Intrinsic::getDeclaration(
2710                                    F->getParent(), Intrinsic::convert_from_fp16,
2711                                    {Builder.getFloatTy()}),
2712                                CI->getArgOperand(0), "h2f");
2713     } else {
2714       llvm_unreachable("Unknown function for CallInst upgrade.");
2715     }
2716 
2717     if (Rep)
2718       CI->replaceAllUsesWith(Rep);
2719     CI->eraseFromParent();
2720     return;
2721   }
2722 
2723   const auto &DefaultCase = [&NewFn, &CI]() -> void {
2724     // Handle generic mangling change, but nothing else
2725     assert(
2726         (CI->getCalledFunction()->getName() != NewFn->getName()) &&
2727         "Unknown function for CallInst upgrade and isn't just a name change");
2728     CI->setCalledFunction(NewFn);
2729   };
2730   CallInst *NewCall = nullptr;
2731   switch (NewFn->getIntrinsicID()) {
2732   default: {
2733     DefaultCase();
2734     return;
2735   }
2736 
2737   case Intrinsic::arm_neon_vld1:
2738   case Intrinsic::arm_neon_vld2:
2739   case Intrinsic::arm_neon_vld3:
2740   case Intrinsic::arm_neon_vld4:
2741   case Intrinsic::arm_neon_vld2lane:
2742   case Intrinsic::arm_neon_vld3lane:
2743   case Intrinsic::arm_neon_vld4lane:
2744   case Intrinsic::arm_neon_vst1:
2745   case Intrinsic::arm_neon_vst2:
2746   case Intrinsic::arm_neon_vst3:
2747   case Intrinsic::arm_neon_vst4:
2748   case Intrinsic::arm_neon_vst2lane:
2749   case Intrinsic::arm_neon_vst3lane:
2750   case Intrinsic::arm_neon_vst4lane: {
2751     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2752                                  CI->arg_operands().end());
2753     NewCall = Builder.CreateCall(NewFn, Args);
2754     break;
2755   }
2756 
2757   case Intrinsic::bitreverse:
2758     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
2759     break;
2760 
2761   case Intrinsic::ctlz:
2762   case Intrinsic::cttz:
2763     assert(CI->getNumArgOperands() == 1 &&
2764            "Mismatch between function args and call args");
2765     NewCall =
2766         Builder.CreateCall(NewFn, {CI->getArgOperand(0), Builder.getFalse()});
2767     break;
2768 
2769   case Intrinsic::objectsize: {
2770     Value *NullIsUnknownSize = CI->getNumArgOperands() == 2
2771                                    ? Builder.getFalse()
2772                                    : CI->getArgOperand(2);
2773     NewCall = Builder.CreateCall(
2774         NewFn, {CI->getArgOperand(0), CI->getArgOperand(1), NullIsUnknownSize});
2775     break;
2776   }
2777 
2778   case Intrinsic::ctpop:
2779     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
2780     break;
2781 
2782   case Intrinsic::convert_from_fp16:
2783     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(0)});
2784     break;
2785 
2786   case Intrinsic::dbg_value:
2787     // Upgrade from the old version that had an extra offset argument.
2788     assert(CI->getNumArgOperands() == 4);
2789     // Drop nonzero offsets instead of attempting to upgrade them.
2790     if (auto *Offset = dyn_cast_or_null<Constant>(CI->getArgOperand(1)))
2791       if (Offset->isZeroValue()) {
2792         NewCall = Builder.CreateCall(
2793             NewFn,
2794             {CI->getArgOperand(0), CI->getArgOperand(2), CI->getArgOperand(3)});
2795         break;
2796       }
2797     CI->eraseFromParent();
2798     return;
2799 
2800   case Intrinsic::x86_xop_vfrcz_ss:
2801   case Intrinsic::x86_xop_vfrcz_sd:
2802     NewCall = Builder.CreateCall(NewFn, {CI->getArgOperand(1)});
2803     break;
2804 
2805   case Intrinsic::x86_xop_vpermil2pd:
2806   case Intrinsic::x86_xop_vpermil2ps:
2807   case Intrinsic::x86_xop_vpermil2pd_256:
2808   case Intrinsic::x86_xop_vpermil2ps_256: {
2809     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2810                                  CI->arg_operands().end());
2811     VectorType *FltIdxTy = cast<VectorType>(Args[2]->getType());
2812     VectorType *IntIdxTy = VectorType::getInteger(FltIdxTy);
2813     Args[2] = Builder.CreateBitCast(Args[2], IntIdxTy);
2814     NewCall = Builder.CreateCall(NewFn, Args);
2815     break;
2816   }
2817 
2818   case Intrinsic::x86_sse41_ptestc:
2819   case Intrinsic::x86_sse41_ptestz:
2820   case Intrinsic::x86_sse41_ptestnzc: {
2821     // The arguments for these intrinsics used to be v4f32, and changed
2822     // to v2i64. This is purely a nop, since those are bitwise intrinsics.
2823     // So, the only thing required is a bitcast for both arguments.
2824     // First, check the arguments have the old type.
2825     Value *Arg0 = CI->getArgOperand(0);
2826     if (Arg0->getType() != VectorType::get(Type::getFloatTy(C), 4))
2827       return;
2828 
2829     // Old intrinsic, add bitcasts
2830     Value *Arg1 = CI->getArgOperand(1);
2831 
2832     Type *NewVecTy = VectorType::get(Type::getInt64Ty(C), 2);
2833 
2834     Value *BC0 = Builder.CreateBitCast(Arg0, NewVecTy, "cast");
2835     Value *BC1 = Builder.CreateBitCast(Arg1, NewVecTy, "cast");
2836 
2837     NewCall = Builder.CreateCall(NewFn, {BC0, BC1});
2838     break;
2839   }
2840 
2841   case Intrinsic::x86_sse41_insertps:
2842   case Intrinsic::x86_sse41_dppd:
2843   case Intrinsic::x86_sse41_dpps:
2844   case Intrinsic::x86_sse41_mpsadbw:
2845   case Intrinsic::x86_avx_dp_ps_256:
2846   case Intrinsic::x86_avx2_mpsadbw: {
2847     // Need to truncate the last argument from i32 to i8 -- this argument models
2848     // an inherently 8-bit immediate operand to these x86 instructions.
2849     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2850                                  CI->arg_operands().end());
2851 
2852     // Replace the last argument with a trunc.
2853     Args.back() = Builder.CreateTrunc(Args.back(), Type::getInt8Ty(C), "trunc");
2854     NewCall = Builder.CreateCall(NewFn, Args);
2855     break;
2856   }
2857 
2858   case Intrinsic::x86_avx512_mask_cmp_pd_128:
2859   case Intrinsic::x86_avx512_mask_cmp_pd_256:
2860   case Intrinsic::x86_avx512_mask_cmp_pd_512:
2861   case Intrinsic::x86_avx512_mask_cmp_ps_128:
2862   case Intrinsic::x86_avx512_mask_cmp_ps_256:
2863   case Intrinsic::x86_avx512_mask_cmp_ps_512: {
2864     SmallVector<Value *, 4> Args;
2865     Args.push_back(CI->getArgOperand(0));
2866     Args.push_back(CI->getArgOperand(1));
2867     Args.push_back(CI->getArgOperand(2));
2868     if (CI->getNumArgOperands() == 5)
2869       Args.push_back(CI->getArgOperand(4));
2870 
2871     NewCall = Builder.CreateCall(NewFn, Args);
2872     unsigned NumElts = Args[0]->getType()->getVectorNumElements();
2873     Value *Res = ApplyX86MaskOn1BitsVec(Builder, NewCall, CI->getArgOperand(3),
2874                                         NumElts);
2875 
2876     std::string Name = CI->getName();
2877     if (!Name.empty()) {
2878       CI->setName(Name + ".old");
2879       NewCall->setName(Name);
2880     }
2881     CI->replaceAllUsesWith(Res);
2882     CI->eraseFromParent();
2883     return;
2884   }
2885 
2886   case Intrinsic::thread_pointer: {
2887     NewCall = Builder.CreateCall(NewFn, {});
2888     break;
2889   }
2890 
2891   case Intrinsic::invariant_start:
2892   case Intrinsic::invariant_end:
2893   case Intrinsic::masked_load:
2894   case Intrinsic::masked_store:
2895   case Intrinsic::masked_gather:
2896   case Intrinsic::masked_scatter: {
2897     SmallVector<Value *, 4> Args(CI->arg_operands().begin(),
2898                                  CI->arg_operands().end());
2899     NewCall = Builder.CreateCall(NewFn, Args);
2900     break;
2901   }
2902 
2903   case Intrinsic::memcpy:
2904   case Intrinsic::memmove:
2905   case Intrinsic::memset: {
2906     // We have to make sure that the call signature is what we're expecting.
2907     // We only want to change the old signatures by removing the alignment arg:
2908     //  @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i32, i1)
2909     //    -> @llvm.mem[cpy|move]...(i8*, i8*, i[32|i64], i1)
2910     //  @llvm.memset...(i8*, i8, i[32|64], i32, i1)
2911     //    -> @llvm.memset...(i8*, i8, i[32|64], i1)
2912     // Note: i8*'s in the above can be any pointer type
2913     if (CI->getNumArgOperands() != 5) {
2914       DefaultCase();
2915       return;
2916     }
2917     // Remove alignment argument (3), and add alignment attributes to the
2918     // dest/src pointers.
2919     Value *Args[4] = {CI->getArgOperand(0), CI->getArgOperand(1),
2920                       CI->getArgOperand(2), CI->getArgOperand(4)};
2921     NewCall = Builder.CreateCall(NewFn, Args);
2922     auto *MemCI = cast<MemIntrinsic>(NewCall);
2923     // All mem intrinsics support dest alignment.
2924     const ConstantInt *Align = cast<ConstantInt>(CI->getArgOperand(3));
2925     MemCI->setDestAlignment(Align->getZExtValue());
2926     // Memcpy/Memmove also support source alignment.
2927     if (auto *MTI = dyn_cast<MemTransferInst>(MemCI))
2928       MTI->setSourceAlignment(Align->getZExtValue());
2929     break;
2930   }
2931   }
2932   assert(NewCall && "Should have either set this variable or returned through "
2933                     "the default case");
2934   std::string Name = CI->getName();
2935   if (!Name.empty()) {
2936     CI->setName(Name + ".old");
2937     NewCall->setName(Name);
2938   }
2939   CI->replaceAllUsesWith(NewCall);
2940   CI->eraseFromParent();
2941 }
2942 
2943 void llvm::UpgradeCallsToIntrinsic(Function *F) {
2944   assert(F && "Illegal attempt to upgrade a non-existent intrinsic.");
2945 
2946   // Check if this function should be upgraded and get the replacement function
2947   // if there is one.
2948   Function *NewFn;
2949   if (UpgradeIntrinsicFunction(F, NewFn)) {
2950     // Replace all users of the old function with the new function or new
2951     // instructions. This is not a range loop because the call is deleted.
2952     for (auto UI = F->user_begin(), UE = F->user_end(); UI != UE; )
2953       if (CallInst *CI = dyn_cast<CallInst>(*UI++))
2954         UpgradeIntrinsicCall(CI, NewFn);
2955 
2956     // Remove old function, no longer used, from the module.
2957     F->eraseFromParent();
2958   }
2959 }
2960 
2961 MDNode *llvm::UpgradeTBAANode(MDNode &MD) {
2962   // Check if the tag uses struct-path aware TBAA format.
2963   if (isa<MDNode>(MD.getOperand(0)) && MD.getNumOperands() >= 3)
2964     return &MD;
2965 
2966   auto &Context = MD.getContext();
2967   if (MD.getNumOperands() == 3) {
2968     Metadata *Elts[] = {MD.getOperand(0), MD.getOperand(1)};
2969     MDNode *ScalarType = MDNode::get(Context, Elts);
2970     // Create a MDNode <ScalarType, ScalarType, offset 0, const>
2971     Metadata *Elts2[] = {ScalarType, ScalarType,
2972                          ConstantAsMetadata::get(
2973                              Constant::getNullValue(Type::getInt64Ty(Context))),
2974                          MD.getOperand(2)};
2975     return MDNode::get(Context, Elts2);
2976   }
2977   // Create a MDNode <MD, MD, offset 0>
2978   Metadata *Elts[] = {&MD, &MD, ConstantAsMetadata::get(Constant::getNullValue(
2979                                     Type::getInt64Ty(Context)))};
2980   return MDNode::get(Context, Elts);
2981 }
2982 
2983 Instruction *llvm::UpgradeBitCastInst(unsigned Opc, Value *V, Type *DestTy,
2984                                       Instruction *&Temp) {
2985   if (Opc != Instruction::BitCast)
2986     return nullptr;
2987 
2988   Temp = nullptr;
2989   Type *SrcTy = V->getType();
2990   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
2991       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
2992     LLVMContext &Context = V->getContext();
2993 
2994     // We have no information about target data layout, so we assume that
2995     // the maximum pointer size is 64bit.
2996     Type *MidTy = Type::getInt64Ty(Context);
2997     Temp = CastInst::Create(Instruction::PtrToInt, V, MidTy);
2998 
2999     return CastInst::Create(Instruction::IntToPtr, Temp, DestTy);
3000   }
3001 
3002   return nullptr;
3003 }
3004 
3005 Value *llvm::UpgradeBitCastExpr(unsigned Opc, Constant *C, Type *DestTy) {
3006   if (Opc != Instruction::BitCast)
3007     return nullptr;
3008 
3009   Type *SrcTy = C->getType();
3010   if (SrcTy->isPtrOrPtrVectorTy() && DestTy->isPtrOrPtrVectorTy() &&
3011       SrcTy->getPointerAddressSpace() != DestTy->getPointerAddressSpace()) {
3012     LLVMContext &Context = C->getContext();
3013 
3014     // We have no information about target data layout, so we assume that
3015     // the maximum pointer size is 64bit.
3016     Type *MidTy = Type::getInt64Ty(Context);
3017 
3018     return ConstantExpr::getIntToPtr(ConstantExpr::getPtrToInt(C, MidTy),
3019                                      DestTy);
3020   }
3021 
3022   return nullptr;
3023 }
3024 
3025 /// Check the debug info version number, if it is out-dated, drop the debug
3026 /// info. Return true if module is modified.
3027 bool llvm::UpgradeDebugInfo(Module &M) {
3028   unsigned Version = getDebugMetadataVersionFromModule(M);
3029   if (Version == DEBUG_METADATA_VERSION) {
3030     bool BrokenDebugInfo = false;
3031     if (verifyModule(M, &llvm::errs(), &BrokenDebugInfo))
3032       report_fatal_error("Broken module found, compilation aborted!");
3033     if (!BrokenDebugInfo)
3034       // Everything is ok.
3035       return false;
3036     else {
3037       // Diagnose malformed debug info.
3038       DiagnosticInfoIgnoringInvalidDebugMetadata Diag(M);
3039       M.getContext().diagnose(Diag);
3040     }
3041   }
3042   bool Modified = StripDebugInfo(M);
3043   if (Modified && Version != DEBUG_METADATA_VERSION) {
3044     // Diagnose a version mismatch.
3045     DiagnosticInfoDebugMetadataVersion DiagVersion(M, Version);
3046     M.getContext().diagnose(DiagVersion);
3047   }
3048   return Modified;
3049 }
3050 
3051 bool llvm::UpgradeRetainReleaseMarker(Module &M) {
3052   bool Changed = false;
3053   NamedMDNode *ModRetainReleaseMarker =
3054       M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker");
3055   if (ModRetainReleaseMarker) {
3056     MDNode *Op = ModRetainReleaseMarker->getOperand(0);
3057     if (Op) {
3058       MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(0));
3059       if (ID) {
3060         SmallVector<StringRef, 4> ValueComp;
3061         ID->getString().split(ValueComp, "#");
3062         if (ValueComp.size() == 2) {
3063           std::string NewValue = ValueComp[0].str() + ";" + ValueComp[1].str();
3064           Metadata *Ops[1] = {MDString::get(M.getContext(), NewValue)};
3065           ModRetainReleaseMarker->setOperand(0,
3066                                              MDNode::get(M.getContext(), Ops));
3067           Changed = true;
3068         }
3069       }
3070     }
3071   }
3072   return Changed;
3073 }
3074 
3075 bool llvm::UpgradeModuleFlags(Module &M) {
3076   NamedMDNode *ModFlags = M.getModuleFlagsMetadata();
3077   if (!ModFlags)
3078     return false;
3079 
3080   bool HasObjCFlag = false, HasClassProperties = false, Changed = false;
3081   for (unsigned I = 0, E = ModFlags->getNumOperands(); I != E; ++I) {
3082     MDNode *Op = ModFlags->getOperand(I);
3083     if (Op->getNumOperands() != 3)
3084       continue;
3085     MDString *ID = dyn_cast_or_null<MDString>(Op->getOperand(1));
3086     if (!ID)
3087       continue;
3088     if (ID->getString() == "Objective-C Image Info Version")
3089       HasObjCFlag = true;
3090     if (ID->getString() == "Objective-C Class Properties")
3091       HasClassProperties = true;
3092     // Upgrade PIC/PIE Module Flags. The module flag behavior for these two
3093     // field was Error and now they are Max.
3094     if (ID->getString() == "PIC Level" || ID->getString() == "PIE Level") {
3095       if (auto *Behavior =
3096               mdconst::dyn_extract_or_null<ConstantInt>(Op->getOperand(0))) {
3097         if (Behavior->getLimitedValue() == Module::Error) {
3098           Type *Int32Ty = Type::getInt32Ty(M.getContext());
3099           Metadata *Ops[3] = {
3100               ConstantAsMetadata::get(ConstantInt::get(Int32Ty, Module::Max)),
3101               MDString::get(M.getContext(), ID->getString()),
3102               Op->getOperand(2)};
3103           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
3104           Changed = true;
3105         }
3106       }
3107     }
3108     // Upgrade Objective-C Image Info Section. Removed the whitespce in the
3109     // section name so that llvm-lto will not complain about mismatching
3110     // module flags that is functionally the same.
3111     if (ID->getString() == "Objective-C Image Info Section") {
3112       if (auto *Value = dyn_cast_or_null<MDString>(Op->getOperand(2))) {
3113         SmallVector<StringRef, 4> ValueComp;
3114         Value->getString().split(ValueComp, " ");
3115         if (ValueComp.size() != 1) {
3116           std::string NewValue;
3117           for (auto &S : ValueComp)
3118             NewValue += S.str();
3119           Metadata *Ops[3] = {Op->getOperand(0), Op->getOperand(1),
3120                               MDString::get(M.getContext(), NewValue)};
3121           ModFlags->setOperand(I, MDNode::get(M.getContext(), Ops));
3122           Changed = true;
3123         }
3124       }
3125     }
3126   }
3127 
3128   // "Objective-C Class Properties" is recently added for Objective-C. We
3129   // upgrade ObjC bitcodes to contain a "Objective-C Class Properties" module
3130   // flag of value 0, so we can correclty downgrade this flag when trying to
3131   // link an ObjC bitcode without this module flag with an ObjC bitcode with
3132   // this module flag.
3133   if (HasObjCFlag && !HasClassProperties) {
3134     M.addModuleFlag(llvm::Module::Override, "Objective-C Class Properties",
3135                     (uint32_t)0);
3136     Changed = true;
3137   }
3138 
3139   return Changed;
3140 }
3141 
3142 void llvm::UpgradeSectionAttributes(Module &M) {
3143   auto TrimSpaces = [](StringRef Section) -> std::string {
3144     SmallVector<StringRef, 5> Components;
3145     Section.split(Components, ',');
3146 
3147     SmallString<32> Buffer;
3148     raw_svector_ostream OS(Buffer);
3149 
3150     for (auto Component : Components)
3151       OS << ',' << Component.trim();
3152 
3153     return OS.str().substr(1);
3154   };
3155 
3156   for (auto &GV : M.globals()) {
3157     if (!GV.hasSection())
3158       continue;
3159 
3160     StringRef Section = GV.getSection();
3161 
3162     if (!Section.startswith("__DATA, __objc_catlist"))
3163       continue;
3164 
3165     // __DATA, __objc_catlist, regular, no_dead_strip
3166     // __DATA,__objc_catlist,regular,no_dead_strip
3167     GV.setSection(TrimSpaces(Section));
3168   }
3169 }
3170 
3171 static bool isOldLoopArgument(Metadata *MD) {
3172   auto *T = dyn_cast_or_null<MDTuple>(MD);
3173   if (!T)
3174     return false;
3175   if (T->getNumOperands() < 1)
3176     return false;
3177   auto *S = dyn_cast_or_null<MDString>(T->getOperand(0));
3178   if (!S)
3179     return false;
3180   return S->getString().startswith("llvm.vectorizer.");
3181 }
3182 
3183 static MDString *upgradeLoopTag(LLVMContext &C, StringRef OldTag) {
3184   StringRef OldPrefix = "llvm.vectorizer.";
3185   assert(OldTag.startswith(OldPrefix) && "Expected old prefix");
3186 
3187   if (OldTag == "llvm.vectorizer.unroll")
3188     return MDString::get(C, "llvm.loop.interleave.count");
3189 
3190   return MDString::get(
3191       C, (Twine("llvm.loop.vectorize.") + OldTag.drop_front(OldPrefix.size()))
3192              .str());
3193 }
3194 
3195 static Metadata *upgradeLoopArgument(Metadata *MD) {
3196   auto *T = dyn_cast_or_null<MDTuple>(MD);
3197   if (!T)
3198     return MD;
3199   if (T->getNumOperands() < 1)
3200     return MD;
3201   auto *OldTag = dyn_cast_or_null<MDString>(T->getOperand(0));
3202   if (!OldTag)
3203     return MD;
3204   if (!OldTag->getString().startswith("llvm.vectorizer."))
3205     return MD;
3206 
3207   // This has an old tag.  Upgrade it.
3208   SmallVector<Metadata *, 8> Ops;
3209   Ops.reserve(T->getNumOperands());
3210   Ops.push_back(upgradeLoopTag(T->getContext(), OldTag->getString()));
3211   for (unsigned I = 1, E = T->getNumOperands(); I != E; ++I)
3212     Ops.push_back(T->getOperand(I));
3213 
3214   return MDTuple::get(T->getContext(), Ops);
3215 }
3216 
3217 MDNode *llvm::upgradeInstructionLoopAttachment(MDNode &N) {
3218   auto *T = dyn_cast<MDTuple>(&N);
3219   if (!T)
3220     return &N;
3221 
3222   if (none_of(T->operands(), isOldLoopArgument))
3223     return &N;
3224 
3225   SmallVector<Metadata *, 8> Ops;
3226   Ops.reserve(T->getNumOperands());
3227   for (Metadata *MD : T->operands())
3228     Ops.push_back(upgradeLoopArgument(MD));
3229 
3230   return MDTuple::get(T->getContext(), Ops);
3231 }
3232