<html><head><meta http-equiv="Content-Type" content="text/html charset=utf-8"></head><body style="word-wrap: break-word; -webkit-nbsp-mode: space; -webkit-line-break: after-white-space;" class="">Hi all,<div class=""><br class=""><div class=""><blockquote type="cite" class=""><div class="">On 2 Oct 2019, at 14:34, Sanjay Patel <<a href="mailto:spatel@rotateright.com" class="">spatel@rotateright.com</a>> wrote</div><div class=""><div dir="ltr" class=""><div dir="ltr" class=""><div class="">Providing target options/overrides to code that is supposed to be target-independent sounds self-defeating to me. I doubt that proposal would gain much support.</div><div class="">Of course, if you're customizing LLVM for your own out-of-trunk backend, you can do anything you'd like if you're willing to maintain the custom patches.<br class=""></div><div class="">I suggest that you file a bug report showing an exact problem caused by 1 of the icmp/select transforms. <br class=""></div><div class="">If it can be done using an in-trunk backend like AVR or MSP430, then we'll have a real example showing the harm and hopefully better ideas about how to solve the bug.</div></div></div></div></blockquote></div><div class=""><div class=""><br class=""></div><div class="">I fully understand your statement about target-independent code. This has no possible discussion in a general way. However one of my points is that at least some of this code is not really that “target independent” because in fact it depends on cheap features available on ALL targets, which is not the case. That’s why I think that some flexibility must be given. I’m not advocating for “target options/overrides”, but general ones that can be optionally chosen by particular targets. I think that at the end of the day it’s just a matter of language, not a matter of fact.</div><div class=""><br class=""></div><div class="">If we look at the problem from some distance, we find that there are already options to alter IR code generation. For example the -phi-node-folding-threshold option is one of them. Ok, no target seems to use that particular one, but it’s there already, and it modifies LLVM-IR generation by telling how aggressively LLVM turns branches into selects. I found that this option produces better  LLVM-IR input for the target I’m working on, as well as both the MSP430 and AVR targets. </div><div class=""><br class=""></div><div class="">I can of course try to apply my custom patches and maintain them, but although I was able to implement a backend, the complexity and extend of the whole thing is beyond my abilities and resources. Furthermore, I regard this as a LLVM wide problem, and that’s why I try to raise some awareness.</div><div class=""><br class=""></div><div class="">Following your suggestion, I just filed a bug with a very simple example that to make things easier is not attributable to the InstCombine pass in this case but to transformations happening during LLVM codegen. </div><div class=""><a href="https://bugs.llvm.org/show_bug.cgi?id=43542" class="">https://bugs.llvm.org/show_bug.cgi?id=43542</a></div><div class=""><br class=""></div><div class="">John</div><div class=""><br class=""><div><blockquote type="cite" class=""><div class="">On 2 Oct 2019, at 14:34, Sanjay Patel <<a href="mailto:spatel@rotateright.com" class="">spatel@rotateright.com</a>> wrote:</div><br class="Apple-interchange-newline"><div class=""><div dir="ltr" class=""><div dir="ltr" class=""><div dir="ltr" class="gmail_attr">On Tue, Oct 1, 2019 at 5:51 PM Joan Lluch <<a href="mailto:joan.lluch@icloud.com" class="">joan.lluch@icloud.com</a>> wrote:<br class=""></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div style="overflow-wrap: break-word;" class="">In 
order to give better support to current and future implementations of 
small processor targets, I wonder if instead of attempting to implement a
 general solution, we could implement a set of compiler flags (or code 
hooks) that targets could use to optionally disable undesired IR 
optimiser actions, however not affecting anything of the current 
behaviour as long as these flags are not used. If we had that, nothing 
would need to be done on the existing targets, particularly the major 
ones, and yet, new backend developments and small processor (AVR, 
MSP430) could potentially benefit from that. My opinion is that the 
availability of such options will not defeat the “almost entirely 
target-independent” nature of the IR optimiser, as the transformations 
would still be target-agnostic, except that targets would be able to 
decide which ones are more convenient for them, or disable the non 
desirable ones. Does this sound ok or feasible?.</div></blockquote><div class=""><br class=""></div><div class="">Providing target options/overrides to code that is supposed to be target-independent sounds self-defeating to me. I doubt that proposal would gain much support.</div><div class="">Of course, if you're customizing LLVM for your own out-of-trunk backend, you can do anything you'd like if you're willing to maintain the custom patches.<br class=""></div><div class="">I suggest that you file a bug report showing an exact problem caused by 1 of the icmp/select transforms. <br class=""></div><div class="">If it can be done using an in-trunk backend like AVR or MSP430, then we'll have a real example showing the harm and hopefully better ideas about how to solve the bug.<br class=""></div><div class=""> </div></div><br class=""><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Tue, Oct 1, 2019 at 5:51 PM Joan Lluch <<a href="mailto:joan.lluch@icloud.com" class="">joan.lluch@icloud.com</a>> wrote:<br class=""></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div style="overflow-wrap: break-word;" class=""><div class="">Hi Sanjay,</div><div class=""><br class=""></div><div class="">Thanks for your reply.</div><div class=""><br class=""></div><div class=""><blockquote type="cite" class=""><div dir="ltr" class=""><div class="">So yes, the IR optimizer (instcombine is the specific pass) sometimes turns icmp (and select) sequences into ALU ops. Instcombine is almost entirely *target-independent* and should remain that way. The (sometimes unfortunate) decision to create shifts were made based on popular targets of the time (PowerPC and/or x86), and other targets may have suffered because of that.</div></div></blockquote><br class=""></div><div class="">Yes, that’s what I actually found that I didn’t anticipate.</div><div class=""><br class=""></div><div class=""><blockquote type="cite" class=""><div dir="ltr" class=""><div class="">We've been trying to reverse those canonicalizations in IR over the past few years when the choice is clearly not always optimal, but it's not easy. To avoid perf regressions, you first have to make the backend/codegen aware of the alternate pattern that includes icmp/select and transform that to math/logic (translate instcombine code to DAGCombiner). Then, you have to remove the transform from instcombine and replace it with the reverse transform. This can uncover infinite loops and other problems within instcombine.</div></div></blockquote><br class=""></div><div class="">I understand that. In any case, I am glad that at least this is acknowledged as some kind of flaw of the LLVM system, particularly for the optimal implementation of small processor backends. As these targets generally have cheap branches and do not generally have selects or multi-bit shifts, they hardly benefit from transformations involving shifts or aggressively attempting to replace jumps.</div><div class=""><br class=""></div><div class=""><blockquote type="cite" class=""><div dir="ltr" class=""><div class="">So to finally answer the question: If you can transform the shift into an alternate sequence with a "setcc" DAG node in your target's "ISelLowering" code, that's the easiest way forward. Otherwise, you have to weigh the impact of each target-independent transform on every target.</div></div></blockquote><br class=""></div><div class="">Yes, that’s what I have been doing all the time. My backend contains a lot of code only to reverse undesired LLVM transformations, and yet the resulting final assembly is not as good as it could be, because it is often hard or impossible to identify all sources of improvement. It’s ironical that some older, less sophisticated compilers (and GCC) produce /much/ better code than LLVM for simple architectures.</div><div class=""><br class=""></div><div class="">In order to give better support to current and future implementations of small processor targets, I wonder if instead of attempting to implement a general solution, we could implement a set of compiler flags (or code hooks) that targets could use to optionally disable undesired IR optimiser actions, however not affecting anything of the current behaviour as long as these flags are not used. If we had that, nothing would need to be done on the existing targets, particularly the major ones, and yet, new backend developments and small processor (AVR, MSP430) could potentially benefit from that. My opinion is that the availability of such options will not defeat the “almost entirely target-independent” nature of the IR optimiser, as the transformations would still be target-agnostic, except that targets would be able to decide which ones are more convenient for them, or disable the non desirable ones. Does this sound ok or feasible?.</div><div class=""><br class=""></div><div class="">John</div><div class=""><br class=""></div><div class=""><br class=""></div><br class=""><div class=""><blockquote type="cite" class=""><div class="">On 1 Oct 2019, at 17:20, Sanjay Patel <<a href="mailto:spatel@rotateright.com" target="_blank" class="">spatel@rotateright.com</a>> wrote:</div><br class=""><div class=""><div dir="ltr" class=""><div class="">First, let's agree on terminology:</div><div class="">1. We're in LLVM. Clang has little or nothing to do with these questions from the perspective of LLVM developers.</div><div class="">2. The IR optimizer (also known as the middle-end and invoked via 'opt') is what takes LLVM IR from a front-end (clang is just 1 example) and transforms it to different LLVM IR for easier target-specific optimization.</div><div class="">3. The back-end (invoked using 'llc') is what takes LLVM IR and turns it into assembly for your target. Codegen is 1 part of the backend.<br class=""></div><div class=""><br class=""></div><div class="">So yes, the IR optimizer (instcombine is the specific pass) sometimes turns icmp (and select) sequences into ALU ops. Instcombine is almost entirely *target-independent* and should remain that way. The (sometimes unfortunate) decision to create shifts were made based on popular targets of the time (PowerPC and/or x86), and other targets may have suffered because of that.<br class=""></div><div class=""><br class=""></div><div class="">We've been trying to reverse those canonicalizations in IR over the past few years when the choice is clearly not always optimal, but it's not easy. To avoid perf regressions, you first have to make the backend/codegen aware of the alternate pattern that includes icmp/select and transform that to math/logic (translate instcombine code to DAGCombiner). Then, you have to remove the transform from instcombine and replace it with the reverse transform. This can uncover infinite loops and other problems within instcombine.</div><div class=""><br class=""></div><div class="">It's often not clear which form of IR will lead to better optimizations within the IR optimizer itself. We favor the shortest IR sequence in most cases. But if there's a tie, we have to make a judgement about what is easier to analyze/transform when viewed within a longer sequence of IR.<br class=""></div><div class=""><br class=""></div><div class="">So to finally answer the question: If you can transform the shift into an alternate sequence with a "setcc" DAG node in your target's "ISelLowering" code, that's the easiest way forward. Otherwise, you have to weigh the impact of each target-independent transform on every target.<br class=""></div><div class=""><br class=""></div></div><br class=""><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Mon, Sep 30, 2019 at 5:31 PM Craig Topper <<a href="mailto:craig.topper@gmail.com" target="_blank" class="">craig.topper@gmail.com</a>> wrote:<br class=""></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div dir="ltr" class=""><div class="">For the MSP430 example, I'm guess its InstCombiner::transformSExtICmp or InstCombiner::transformZExtICmp</div><br clear="all" class=""><div class=""><div dir="ltr" class="">~Craig</div></div><br class=""></div><br class=""><div class="gmail_quote"><div dir="ltr" class="gmail_attr">On Mon, Sep 30, 2019 at 2:21 PM Support IMAP <<a href="mailto:support@sweetwilliamsl.com" target="_blank" class="">support@sweetwilliamsl.com</a>> wrote:<br class=""></div><blockquote class="gmail_quote" style="margin:0px 0px 0px 0.8ex;border-left:1px solid rgb(204,204,204);padding-left:1ex"><div class=""><div class="">Hi all,</div><div class=""><br class=""></div><div class="">Ok, I just found a much simpler example of the same issue.</div><div class=""><br class=""></div><div class="">Consider the following code</div><div class=""><br class=""></div><div class=""><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco;background-color:rgb(255,255,255)" class=""><span style="color:rgb(186,45,162)" class="">int</span> cmpge32_0(<span style="color:rgb(186,45,162)" class="">long</span> a) {</div><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco;background-color:rgb(255,255,255)" class="">  <span style="color:rgb(186,45,162)" class="">return</span> a>=<span style="color:rgb(39,42,216)" class="">0</span>;</div><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco;background-color:rgb(255,255,255)" class="">}</div><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco;background-color:rgb(255,255,255)" class=""><br class=""></div><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco;background-color:rgb(255,255,255)" class=""><span style="font-family:Helvetica;font-size:12px" class="">Compiled for the MSP430 with -O1 or -Os results in the following:</span></div><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco;background-color:rgb(255,255,255)" class=""><span style="font-family:Helvetica;font-size:12px" class=""><br class=""></span></div><div style="margin:0px;line-height:normal;background-color:rgb(255,255,255)" class=""><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">; Function Attrs: norecurse nounwind readnone</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">define dso_local i16 @cmpge32_0(i32 %a) local_unnamed_addr #0 {</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">entry:</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">  %a.lobit = lshr i32 %a, 31</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">  %0 = trunc i32 %a.lobit to i16</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">  %.not = xor i16 %0, 1</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">  ret i16 %.not</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class="">}</div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class=""><span style="font-family:Helvetica;font-size:12px" class=""><br class=""></span></div><div style="margin:0px;line-height:normal" class=""><font face="Monaco" class=""><span style="font-size:11px" class="">T</span></font><span style="font-family:Helvetica;font-size:12px" class="">he backend then turns this into the following totally suboptimal code:</span></div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class=""><span style="font-family:Helvetica;font-size:12px" class=""><br class=""></span></div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class=""><div style="margin:0px;line-height:normal" class="">cmpge32_<span style="color:rgb(39,42,216)" class="">0</span>:</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">     </span>mov<span style="white-space:pre-wrap" class="">  </span>r13, r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">   </span>inv<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>swpb<span style="white-space:pre-wrap" class=""> </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>mov.b<span style="white-space:pre-wrap" class="">        </span>r12, r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">   </span>clrc</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">       </span>rrc<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>rra<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>rra<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>rra<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>rra<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>rra<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>rra<span style="white-space:pre-wrap" class="">  </span>r12</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">        </span>ret</div><div style="margin:0px;line-height:normal" class="">.Lfunc_end0:</div><div style="margin:0px;line-height:normal" class=""><span style="white-space:pre-wrap" class="">  </span>.size<span style="white-space:pre-wrap" class="">        </span>cmpge32_<span style="color:rgb(39,42,216)" class="">0</span>, .Lfunc_end0-cmpge32_<span style="color:rgb(39,42,216)" class="">0</span></div></div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class=""><br class=""></div><div style="font-family:Monaco;font-size:11px;margin:0px;line-height:normal" class=""><span style="font-family:Helvetica;font-size:12px" class=""><br class=""></span></div><div style="margin:0px;line-height:normal" class="">The cause of this anomaly is again the presence of the Shift instruction (<span style="font-family:Monaco;font-size:11px" class="">%a.lobit = lshr i32 %a, 31) </span>at the IR level, which is hard to handle by the backend.</div><div style="margin:0px;line-height:normal" class=""><br class=""></div><div style="margin:0px;line-height:normal" class="">The same C code compiled with -O0 creates the following IR code excerpt instead of the lshr-trunc code sequence</div><div style="margin:0px;line-height:normal" class=""><br class=""></div><div style="margin:0px;line-height:normal" class=""><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco" class="">  %cmp = icmp sge i32 %0, 0</div><div style="margin:0px;font-size:11px;line-height:normal;font-family:Monaco" class="">  %conv = zext i1 %cmp to i16</div></div><div style="margin:0px;line-height:normal" class=""><br class=""></div><div style="margin:0px;line-height:normal" class="">This compiles into MUCH better code for the MSP430 architecture (and virtually any 16 bit architecture not supporting multiple shifts). </div><div style="margin:0px;line-height:normal" class="">It would be desirable that LLVM would just leave the comparison as is, also for  -O1 and above. </div><div style="margin:0px;line-height:normal" class=""><br class=""></div><div style="margin:0px;line-height:normal" class=""><br class=""></div><div style="margin:0px;line-height:normal" class="">So Please, can somebody point me to the LLVM class or function that performs the transformation of the comparison above into the undesired shift, so I can investigate what’s going on, or whether there’s something I can do?</div><div style="margin:0px;line-height:normal" class=""><br class=""></div><div style="margin:0px;line-height:normal" class="">That would be really appreciated.</div><div style="margin:0px;line-height:normal" class=""><br class=""></div><div style="margin:0px;line-height:normal" class="">John</div></div></div><div class=""><br class=""></div><div class=""><br class="">Hi Roman<br class=""><br class=""><blockquote type="cite" class="">Not exactly, this is IR after optimizations, this is not what clang produces.<br class="">To see what clang produces you want to pass -O0.<br class="">All optimizations beyond that are done by LLVM.<br class=""></blockquote><br class=""><br class="">Ok, I understand such naming convention, but it is still something that happens at the IR code generation steps, and therefore the backend has little to do about. <br class=""><br class="">So, what are actually the hooks that I can implement or investigate to modify the undesired behaviour?<br class=""><br class="">John<br class=""><br class=""><br class=""><blockquote type="cite" class="">On 30 Sep 2019, at 13:35, Roman Lebedev <<a href="mailto:lebedev.ri@gmail.com" target="_blank" class="">lebedev.ri@gmail.com</a>> wrote:<br class=""><br class="">On Mon, Sep 30, 2019 at 11:52 AM Joan Lluch <<a href="mailto:joan.lluch@icloud.com" target="_blank" class="">joan.lluch@icloud.com</a>> wrote:<br class=""><blockquote type="cite" class=""><br class="">Hi Roman,<br class=""><br class="">Is "test" actually an implementation of a 64-bit-wide multiplication<br class="">compiler-rt builtin?<br class="">Then i'd think the main problem is that it is being optimized in the<br class="">first place, you could end up with endless recursion…<br class=""><br class=""><br class="">No, this is not a compiler-rt builtin. My example is of course incidentally taken from the implementation of a signed multiply, but as said, it has nothing to do with rt-builtins, I'm just using that code to show the issue. This function can’t create a recursion because it’s named ’test’, unlike any rt-buitin. You can replace the multiply in the source code by an addition, if you want to avoid calling rt-functions, but this does not change what I attempt to show. Also It’s not meant to be 64 bit wide, but 32 bit wide, because the targets I’m testing are 16 bit, so ints are 16 bit and longs are 32 bit. This is again the function I am testing:<br class=""><br class=""><br class="">long test (long a, long b)<br class="">{<br class=""> int neg = 0;<br class=""> long res;<br class=""><br class=""> if (a < 0)<br class=""> {<br class="">   a = -a;<br class="">   neg = 1;<br class=""> }<br class=""><br class=""> if (b < 0)<br class=""> {<br class="">   b = -b;<br class="">   neg = !neg;<br class=""> }<br class=""><br class=""> res = a*b;<br class=""><br class=""> if (neg)<br class="">   res = -res;<br class=""><br class=""> return res;<br class="">}<br class=""><br class=""><br class=""><br class="">LLVM, not clang.<br class=""><br class=""><br class="">I’m not sure about what you mean by that. The shown LLVM IR code is created by executing "clang” command line, so that’s what I attempt to show.<br class=""></blockquote>Not exactly, this is IR after optimizations, this is not what clang produces.<br class="">To see what clang produces you want to pass -O0.<br class="">All optimizations beyond that are done by LLVM.<br class=""><br class=""><blockquote type="cite" class="">So it’s actually the front-end that does such undesired optimisations sometimes, not only the LLVM back-end. This is in part why I am saying this is not right. See copied again the IR code that gets generated for the C code that I posted before. This IR code, including the presence of expensive shifts ( %a.lobit = lshr i32 %a, 31)  is generated when -mllvm -phi-node-folding-threshold=1 is specified in the command line, or when the Target implements getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy) to return TCC_Expensive for operator types that are bigger than the default target register size.<br class=""><br class=""><br class=""><br class="">; ModuleID = 'main.c'<br class="">source_filename = "main.c"<br class="">target datalayout = "e-m:e-p:16:16-i32:16-i64:16-f32:16-f64:16-a:8-n8:16-S16"<br class="">target triple = "msp430"<br class=""><br class="">; Function Attrs: norecurse nounwind optsize readnone<br class="">define dso_local i32 @test(i32 %a, i32 %b) local_unnamed_addr #0 {<br class="">entry:<br class=""> %cmp = icmp slt i32 %a, 0<br class=""> %sub = sub nsw i32 0, %a<br class=""> %spec.select = select i1 %cmp, i32 %sub, i32 %a<br class=""> %a.lobit = lshr i32 %a, 31<br class=""> %0 = trunc i32 %a.lobit to i16<br class=""> %cmp1 = icmp slt i32 %b, 0<br class=""> br i1 %cmp1, label %if.then2, label %if.end4<br class=""><br class="">if.then2:                                         ; preds = %entry<br class=""> %sub3 = sub nsw i32 0, %b<br class=""> %1 = xor i16 %0, 1<br class=""> br label %if.end4<br class=""><br class="">if.end4:                                          ; preds = %if.then2, %entry<br class=""> %b.addr.0 = phi i32 [ %sub3, %if.then2 ], [ %b, %entry ]<br class=""> %neg.1 = phi i16 [ %1, %if.then2 ], [ %0, %entry ]<br class=""> %mul = mul nsw i32 %b.addr.0, %spec.select<br class=""> %tobool5 = icmp eq i16 %neg.1, 0<br class=""> %sub7 = sub nsw i32 0, %mul<br class=""> %spec.select18 = select i1 %tobool5, i32 %mul, i32 %sub7<br class=""> ret i32 %spec.select18<br class="">}<br class=""><br class="">attributes #0 = { norecurse nounwind optsize readnone "correctly-rounded-divide-sqrt-fp-math"="false" "disable-tail-calls"="false" "less-precise-fpmad"="false" "min-legal-vector-width"="0" "no-frame-pointer-elim"="false" "no-infs-fp-math"="false" "no-jump-tables"="false" "no-nans-fp-math"="false" "no-signed-zeros-fp-math"="false" "no-trapping-math"="false" "stack-protector-buffer-size"="8" "unsafe-fp-math"="false" "use-soft-float"="false" }<br class=""><br class="">!llvm.module.flags = !{!0}<br class="">!llvm.ident = !{!1}<br class=""><br class="">!0 = !{i32 1, !"wchar_size", i32 2}<br class="">!1 = !{!"clang version 9.0.0 (<a href="https://github.com/llvm/llvm-project.git" target="_blank" class="">https://github.com/llvm/llvm-project.git</a> 6f7deba43dd25fb7b3eca70f9c388ec9174f455a)"}<br class=""><br class=""><br class=""><br class="">As you can see, Clang produces a 31 bit wide shift right ( %a.lobit = lshr i32 %a, 31) That’s the fourth instruction on the IR code above. So a shift is produced instead of creating a jump to a new block, as it should be the case as per the C source code.<br class=""><br class="">Just as a matter of information. This is the implementation of the getOperationCost function that causes ‘clang’ to correctly replace selects by branches (desirable), but to generate shifts to fold expensive selects (undesirable)<br class=""><br class=""><br class="">unsigned CPU74TTIImpl::getOperationCost(unsigned Opcode, Type *Ty, Type *OpTy)<br class="">{<br class=""> // Big types are expensive<br class=""> unsigned OpSize = Ty->getScalarSizeInBits();<br class=""> if ( OpSize > 16 )<br class="">   return TTI::TCC_Expensive;<br class=""><br class=""> return BaseT::getOperationCost(Opcode, Ty, OpTy);<br class="">}<br class=""><br class="">If the getOperationCost above function was not implemented, then clang would generate the usual series of ‘selects’. But this is even worse because selects imply speculative execution of expensive instructions, or duplicate branching created by the backend, which can’t be easily avoided.<br class=""><br class="">Ideally, the IR code above should just place an ‘if.then' block for the if (a < 0) statement in the C source code, instead of attempting to replace a select by a shift (!)<br class=""><br class="">If you want to play with these two scenarios, (1) IR code generated with branches, and (2) IR code generated with selects. This can easily be reproduced for the MSP430 target by compiling with the following options<br class="">(1)  -mllvm -phi-node-folding-threshold=1 -c -S -Os<br class="">(2)  -mllvm -phi-node-folding-threshold=2 -c -S -Os<br class=""><br class="">For 16 bit targets without selects, or expensive selects, the overall code is better with (1) because that prevents the creation of a different jump for every ‘select’ that (2) would cause. However, the presence of the ‘shift’ instruction for (1) spoils it all.<br class=""><br class="">Again, ideally, the use of shifts as a replacement of selects should be avoided, and an “if.then" block should be used as per the original C code.<br class=""><br class="">I hope this is clear now.<br class=""><br class="">John.<br class=""><br class=""><br class="">On 29 Sep 2019, at 15:57, Roman Lebedev <<a href="mailto:lebedev.ri@gmail.com" target="_blank" class="">lebedev.ri@gmail.com</a>> wrote:<br class=""><br class="">On Sun, Sep 29, 2019 at 3:35 PM Joan Lluch via llvm-dev<br class=""><<a href="mailto:llvm-dev@lists.llvm.org" target="_blank" class="">llvm-dev@lists.llvm.org</a>> wrote:<br class=""><br class=""><br class="">Hi Sanjay,<br class=""><br class="">Actually, the CodeGenPrepare::optimizeSelectInst is not doing the best it could do in some circumstances: The case of “OptSize" for targets not supporting Select was already mentioned to be detrimental.<br class=""><br class="">For targets that actually have selects, but branches are cheap and generally profitable, particularly for expensive operators, the optimizeSelectInst function does not do good either. The function tries to identify consecutive selects with the same condition in order to avoid duplicate branches, which is ok, but then this effort is discarded in isFormingBranchFromSelectProfitable because the identified condition is used more than once (on the said two consecutive selects, of course), which defeats the whole purpose of checking for them, resulting in poor codegen.<br class=""><br class="">Yet another issue is that Clang attempts to replace ‘selects’ in the source code, by supposedly optimised code that is not ok for all targets. One example is this:<br class=""><br class="">LLVM, not clang.<br class=""><br class="">long test (long a, long b)<br class="">{<br class="">int neg = 0;<br class="">long res;<br class=""><br class="">if (a < 0)<br class="">{<br class="">  a = -a;<br class="">  neg = 1;<br class="">}<br class=""><br class="">if (b < 0)<br class="">{<br class="">  b = -b;<br class="">  neg = !neg;<br class="">}<br class=""><br class="">res = a*b; //(unsigned long)a / (unsigned long)b;  // will call __udivsi3<br class=""><br class="">if (neg)<br class="">  res = -res;<br class=""><br class="">return res;<br class="">}<br class=""><br class=""><br class="">This gets compiled into<br class=""><br class="">; Function Attrs: norecurse nounwind readnone<br class="">define dso_local i32 @test(i32 %a, i32 %b) local_unnamed_addr #0 {<br class="">entry:<br class="">%cmp = icmp slt i32 %a, 0<br class="">%sub = sub nsw i32 0, %a<br class="">%a.addr.0 = select i1 %cmp, i32 %sub, i32 %a<br class="">%a.lobit = lshr i32 %a, 31<br class="">%0 = trunc i32 %a.lobit to i16<br class="">%cmp1 = icmp slt i32 %b, 0<br class="">br i1 %cmp1, label %if.then2, label %if.end4<br class=""><br class="">if.then2:                                         ; preds = %entry<br class="">%sub3 = sub nsw i32 0, %b<br class="">%1 = xor i16 %0, 1<br class="">br label %if.end4<br class=""><br class="">if.end4:                                          ; preds = %if.then2, %entry<br class="">%b.addr.0 = phi i32 [ %sub3, %if.then2 ], [ %b, %entry ]<br class="">%neg.1 = phi i16 [ %1, %if.then2 ], [ %0, %entry ]<br class="">%mul = mul nsw i32 %b.addr.0, %a.addr.0<br class="">%tobool5 = icmp eq i16 %neg.1, 0<br class="">%sub7 = sub nsw i32 0, %mul<br class="">%res.0 = select i1 %tobool5, i32 %mul, i32 %sub7<br class="">ret i32 %res.0<br class="">}<br class=""><br class="">The offending part here is this:  %a.lobit = lshr i32 %a, 31 . Instead of just creating a “select” instruction, as the original code suggested with the if (a < 0) { neg = 1;} statements, the front-end produces a lshr which is very expensive for small architectures, and makes it very difficult for the backend to fold it again into an actual select (or branch). In my opinion, the original C code should have produced a “select” and give the backend the opportunity to optimise it if required. I think that the frontend should perform only target independent optimisations.<br class=""><br class=""><br class="">You didn't specify how you compile that code.<br class="">We could also get: <a href="https://godbolt.org/z/B-5lj1" target="_blank" class="">https://godbolt.org/z/B-5lj1</a><br class="">Which can actually be folded further to just<br class="">long test(long a, long b) {<br class="">  return a * b;<br class="">}<br class="">Is "test" actually an implementation of a 64-bit-wide multiplication<br class="">compiler-rt builtin?<br class="">Then i'd think the main problem is that it is being optimized in the<br class="">first place, you could end up with endless recursion...<br class=""><br class="">I posted before my view that LLVM is clearly designed to satisfy big boys such as the x86 and ARM targets. This means that, unfortunately, it makes too many general assumptions about what’s cheap, without providing enough hooks to cancel arbitrary optimisations. As I am implementing backends for 8 or 16 bit targets, I find myself doing a lot of work just to reverse optimisations that should have not been applied in the first place. My example above is an instance of a code mutation performed by the frontend that is not desirable. Existing 8 and 16 bit trunk targets (particularly the MSP430 and the AVR) are also negatively affected by the excessively liberal use of shifts by LLVM.<br class=""><br class="">The CodeGenPrepare::optimizeSelectInst function needs some changes to respect targets with no selects, and targets that may want to avoid expensive speculative executions.<br class=""><br class="">John<br class=""><br class="">Roman<br class=""><br class="">On 25 Sep 2019, at 16:00, Sanjay Patel <<a href="mailto:spatel@rotateright.com" target="_blank" class="">spatel@rotateright.com</a>> wrote:<br class=""><br class="">Changing the order of the checks in CodeGenPrepare::optimizeSelectInst() sounds good to me.<br class=""><br class="">But you may need to go further for optimum performance. For example, we may be canonicalizing math/logic IR patterns into 'select' such as in the recent:<br class=""><a href="https://reviews.llvm.org/D67799" target="_blank" class="">https://reviews.llvm.org/D67799</a><br class=""><br class="">So if you want those to become ALU ops again rather than branches, then you need to do the transform later in the backend. That is, you want to let DAGCombiner run its set of transforms on 'select' nodes.<br class=""><br class="">On Wed, Sep 25, 2019 at 4:03 AM Joan Lluch via cfe-dev <<a href="mailto:cfe-dev@lists.llvm.org" target="_blank" class="">cfe-dev@lists.llvm.org</a>> wrote:<br class=""><br class=""><br class="">Hi Craig,<br class=""><br class="">Thank you for your reply. I have started looking at “CodeGenPrepare” and I assume you reffer to CodeGenPrepare::optimizeSelectInst. I will try to play a bit with that possibly later today. At first glance, it looks to me that for targets that do not support ’select’ at all, the fact that the function exits early for ‘OptSize’ can be detrimental, because this will just leave ALL existing selects in the code anyway. As said, I will try to play with that later, but right now it looks to me that maybe we should check  for TLI->isSelectSupported earlier in the function, to get some more opportunities to such targets without explicit ’select’ support?<br class=""><br class="">Thanks<br class=""><br class="">John<br class=""><br class=""><br class="">On 25 Sep 2019, at 08:59, Craig Topper <<a href="mailto:craig.topper@gmail.com" target="_blank" class="">craig.topper@gmail.com</a>> wrote:<br class=""><br class="">There is code in CodeGenPrepare.cpp that can turn selects into branches that tries to account for multiple selects sharing the same condition. It doesn't look like either AVR or MSP430 enable that code though.<br class=""><br class="">~Craig<br class=""><br class=""><br class="">On Tue, Sep 24, 2019 at 11:27 PM Joan Lluch via cfe-dev <<a href="mailto:cfe-dev@lists.llvm.org" target="_blank" class="">cfe-dev@lists.llvm.org</a>> wrote:<br class=""><br class=""><br class="">Hi Roman,<br class=""><br class="">Thank you for your reply. I understand your point. I just want to add something to clarify my original post in relation to your reply.<br class=""><br class="">There are already implemented 8-bit and 16-bit backends, namely the AVR and the MSP430, which already "aggressively convert selects into branches”, which already benefit (as they are) from setting "phi-node-folding-threshold’ to 1 or zero. This is because otherwise Clang will generate several selects depending on the same “icmp”. These backends are unable to optimise that, and they just create a comparison and a conditional branch for every “select” in the IR code, in spite that the original C code was already written in a much better way. So the resulting effect is the presence of redundant comparisons and branches in the final code, with a detrimental of generated code quality.<br class=""><br class="">The above gets improved by setting "phi-node-folding-threshold’ to 1 because some of these extra ‘selects' are no longer there so the backend stops generating redundant code.<br class=""><br class="">John.<br class=""><br class=""><br class=""><br class=""><br class="">On 21 Sep 2019, at 14:48, Roman Lebedev <<a href="mailto:lebedev.ri@gmail.com" target="_blank" class="">lebedev.ri@gmail.com</a>> wrote:<br class=""><br class="">On Sat, Sep 21, 2019 at 3:18 PM Joan Lluch via cfe-dev<br class=""><<a href="mailto:cfe-dev@lists.llvm.org" target="_blank" class="">cfe-dev@lists.llvm.org</a>> wrote:<br class=""><br class=""><br class="">Hi all,<br class=""><br class="">For my custom architecture, I want to relax the CFG simplification pass, and any other passes replacing conditional branches.<br class=""><br class="">I found that the replacement of conditional branches by “select" and other instructions is often too aggressive, and this causes inefficient code for my target as in most cases branches would be cheaper.<br class=""><br class="">For example, considering the following c code:<br class=""><br class="">long test (long a, long b)<br class="">{<br class="">int neg = 0;<br class="">long res;<br class=""><br class="">if (a < 0)<br class="">{<br class=""> a = -a;<br class=""> neg = 1;<br class="">}<br class=""><br class="">res = a*b;<br class=""><br class="">if (neg)<br class=""> res = -res;<br class=""><br class="">return res;<br class="">}<br class=""><br class=""><br class="">This code can be simplified in c, but it’s just an example to show the point.<br class=""><br class="">The code above gets compiled like this (-Oz flag):<br class=""><br class="">; Function Attrs: minsize norecurse nounwind optsize readnone<br class="">define dso_local i32 @test(i32 %a, i32 %b) local_unnamed_addr #0 {<br class="">entry:<br class="">%cmp = icmp slt i32 %a, 0<br class="">%sub = sub nsw i32 0, %a<br class="">%a.addr.0 = select i1 %cmp, i32 %sub, i32 %a<br class="">%mul = mul nsw i32 %a.addr.0, %b<br class="">%sub2 = sub nsw i32 0, %mul<br class="">%res.0 = select i1 %cmp, i32 %sub2, i32 %mul<br class="">ret i32 %res.0<br class="">}<br class=""><br class=""><br class="">All branching was removed and replaced by ‘select’ instructions. For my architecture, it would be desirable to keep the original branches in most cases, because even simple 32 bit operations are too expensive to speculatively execute them, and branches are cheap.<br class=""><br class="">Setting  'phi-node-folding-threshold’ to 1 or even 0 (instead of the default 2), definitely improves the situation in many cases, but Clang still creates many instances of ‘select’ instructions, which are detrimental to my target. I am unsure about where are they created, as I believe that the simplifycfg pass does not longer create them.<br class=""><br class="">You definitively can't ban llvm passes/clang from creating select's.<br class=""><br class="">So the question is: Are there any other hooks in clang, or custom code that I can implement, to relax the creation of ’select’ instructions and make it preserve branches in the original c code?<br class=""><br class="">I think this is backwards.<br class="">Sure, you could maybe disable most of the folds that produce selects.<br class="">That may be good for final codegen, but will also affect other passes<br class="">since not everything deals with 2-node PHI as good as wit selects.<br class=""><br class="">But, what happens if you still get the select-y IR?<br class="">Doesn't matter how, could be hand-written.<br class=""><br class="">I think you might want to instead aggressively convert selects into<br class="">branches in backend.<br class=""><br class="">Thanks,<br class=""><br class="">John<br class=""><br class="">Roman<br class=""><br class="">_______________________________________________<br class="">LLVM Developers mailing list<br class=""><a href="mailto:llvm-dev@lists.llvm.org" target="_blank" class="">llvm-dev@lists.llvm.org</a><br class=""><a href="https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev" target="_blank" class="">https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev</a><br class="">_______________________________________________<br class="">cfe-dev mailing list<br class=""><a href="mailto:cfe-dev@lists.llvm.org" target="_blank" class="">cfe-dev@lists.llvm.org</a><br class=""><a href="https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev" target="_blank" class="">https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev</a><br class=""><br class=""><br class="">_______________________________________________<br class="">cfe-dev mailing list<br class=""><a href="mailto:cfe-dev@lists.llvm.org" target="_blank" class="">cfe-dev@lists.llvm.org</a><br class=""><a href="https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev" target="_blank" class="">https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev</a><br class=""><br class=""><br class=""><br class="">_______________________________________________<br class="">cfe-dev mailing list<br class=""><a href="mailto:cfe-dev@lists.llvm.org" target="_blank" class="">cfe-dev@lists.llvm.org</a><br class=""><a href="https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev" target="_blank" class="">https://lists.llvm.org/cgi-bin/mailman/listinfo/cfe-dev</a><br class=""><br class=""><br class=""><br class="">_______________________________________________<br class="">LLVM Developers mailing list<br class=""><a href="mailto:llvm-dev@lists.llvm.org" target="_blank" class="">llvm-dev@lists.llvm.org</a><br class=""><a href="https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev" target="_blank" class="">https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev</a><br class=""><br class=""><br class=""></blockquote></blockquote><br class="">_______________________________________________<br class="">LLVM Developers mailing list<br class=""><a href="mailto:llvm-dev@lists.llvm.org" target="_blank" class="">llvm-dev@lists.llvm.org</a><br class=""><a href="https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev" target="_blank" class="">https://lists.llvm.org/cgi-bin/mailman/listinfo/llvm-dev</a><br class=""></div></div></blockquote></div>
</blockquote></div>
</div></blockquote></div><br class=""></div></blockquote></div></div>
</div></blockquote></div><br class=""></div></div></div></body></html>